code-rag-bench/online-tutorials huggingface dataset:
Write a program in JavaScript to check if two strings are anagrams of each other or not

Given two strings ‘a’ and string ‘b’, we have to check if they are anagrams of each other or not and return True/False. For example,
Input-1 −
String a= “india”
String b= “nidia”
Output −
True
Explanation − Since the given string ‘b’ contains all the characters in the string ‘a’ thus we will return True.
Input-2 −
String a= “hackathon”
String b= “achcthoon”
Output −
False
Explanation − Since the given string ‘b’ doesn’t have all the characters as string ‘a’ have thus we will return False.
In the given strings ‘a’ and ‘b’, we will check if they are of the same length and then we will sort the strings. If both the strings are equal, then return “True”; if not, then print “False”.
Take Input two strings ‘a’ and ‘b’
Take Input two strings ‘a’ and ‘b’
A function checkStringAnagrams(string a, string b) which will return true if they are anagram of each other otherwise false.
A function checkStringAnagrams(string a, string b) which will return true if they are anagram of each other otherwise false.
Find the length of both strings and check if they are the same.
Find the length of both strings and check if they are the same.
Now sort both strings in lexicographically order and check if they are equal or not.
Now sort both strings in lexicographically order and check if they are equal or not.
Return true or false accordingly.
Return true or false accordingly.
function checkStringsAnagram(a, b) {
   let len1 = a.length;
   let len2 = b.length;
   if(len1 !== len2){
      console.log('Invalid Input');
      return
   }
   let str1 = a.split('').sort().join('');
   let str2 = b.split('').sort().join('');
   if(str1 === str2){
      console.log("True");
   } else { 
      console.log("False");
   }
}
checkStringsAnagram("indian","ndiani")
Running the above code will generate the output as,
True
Since the string ‘indian’ has the same set of characters as in the other string ‘ndiani’, both are anagrams of each other, and hence, and we will return True.
HTML5 Canvas to PNG File

To convert HTML5 canvas to PNG, follow the below-given steps −
You need to add the generated data URL to the href attribute of an <a> tag.
Dialog for base64 image −
<img src="data:image/png;base64,iOBVRw0KGgoAAAANSUhEUg...." class="image" />
Add a filename −
<a download="newimg.png" href="...">
Now define http headers −
headers=Content-Disposition: attachment; filename=newimg.png
To deal with the RAM of the web browser and make its utilization less −
// generated the data URL dynamically
function myCanvas() {
   var d = canvas.toDataURL('image/png');
   this.href = d;
};
d.addEventListener('click', myCanvas, false);
How to clear an entire Treeview with Tkinter?

Tkinter Treeview widgets are used to display the hierarchy of the items in the form of a list. It generally looks like the file explorer in Windows or Mac OS.
Let us suppose we have created a list of items using treeview widget and we want to clear the entire treeview, then we can use the delete() function. The function can be invoked while iterating over the treeview items.
In this example, we will create a treeview for the Programming Language and will clear the list of items using delete() operation.
#Import the required library
from tkinter import *
from tkinter import ttk

#Create an instance of tkinter frame
win = Tk()
win.title("Application to represent the Programming Languages ")

#Set the geometry
win.geometry("600x200")

#Create a label
ttk.Label(win, text ="Treeview(hierarchical)").pack()

#Treeview List Instantiation
treeview = ttk.Treeview(win)
treeview.pack()
treeview.insert('', '0', 'i1', text ='Language')
treeview.insert('', '1', 'i2', text ='FrontEnd')
treeview.insert('', '2', 'i3', text ='Backend')
treeview.insert('i2', 'end', 'HTML', text ='RUBY')
treeview.insert('i2', 'end', 'Python', text ='JavaScript')
treeview.insert('i3', 'end', 'C++', text ='Java')
treeview.insert('i3', 'end', 'RUST', text ='Python')
treeview.move('i2', 'i1', 'end')
treeview.move('i3', 'i1', 'end')
treeview.move('i2', 'i1', 'end')

win.mainloop()
Running the above code will display a window that contains a treeview hierarchy of Programming languages categorized for FrontEnd and Backend.
Now, adding the following code before the mainloop will remove and clear the whole treeview list.
#Clear the treeview list items
for item in treeview.get_children():
   treeview.delete(item)
After invoking the function, it will clear the whole treeview list items from the window.
After clearing the treeview, it will display an empty treeview list.
C# Program for Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks

22 Aug, 2019
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.Example:
Example 1 : Consider the following 3 activities sorted
by finish time.
     start[]  =  {10, 12, 20};
     finish[] =  {20, 25, 30};
A person can perform at most two activities. The 
maximum set of activities that can be executed 
is {0, 2} [ These are indexes in start[] and 
finish[] ]

Example 2 : Consider the following 6 activities 
sorted by by finish time.
     start[]  =  {1, 3, 0, 5, 8, 5};
     finish[] =  {2, 4, 6, 7, 9, 9};
A person can perform at most four activities. The 
maximum set of activities that can be executed 
is {0, 1, 3, 4} [ These are indexes in start[] and 
finish[] ]

C#
// The following implementation assumes// that the activities are already sorted// according to their finish timeusing System;  class GFG {    // Prints a maximum set of activities    // that can be done by a single    // person, one at a time.    // n --> Total number of activities    // s[] --> An array that contains start    // time of all activities    // f[] --> An array that contains finish    // time of all activities    public static void printMaxActivities(int[] s,                                          int[] f, int n)    {        int i, j;          Console.Write("Following activities are selected : ");          // The first activity always gets selected        i = 0;        Console.Write(i + " ");          // Consider rest of the activities        for (j = 1; j < n; j++) {            // If this activity has start time greater than or            // equal to the finish time of previously selected            // activity, then select it            if (s[j] >= f[i]) {                Console.Write(j + " ");                i = j;            }        }    }      // Driver Code    public static void Main()    {        int[] s = { 1, 3, 0, 5, 8, 5 };        int[] f = { 2, 4, 6, 7, 9, 9 };        int n = s.Length;          printMaxActivities(s, f, n);    }}  // This code is contributed// by ChitraNayal
Following activities are selected : 0 1 3 4

Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details!
nidhi_biet
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Program to Demonstrate the IList Interface
How to Remove Duplicate Values From an Array in C#?
C# Program to Read and Write a Byte Array to File using FileStream Class
How to Calculate the Code Execution Time in C#?
C# Program to Check a Specified Type is an Enum or Not
How to Sort Object Array By Specific Property in C#?
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
C# Program to Sort a List of String Names Using the LINQ OrderBy() Method
C# Program to Delete an Empty and a Non-Empty Directory
C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method
C++ program to find the smallest element among three elements

In this tutorial, we will be discussing a program to find the smallest element among the provided three elements.
We will be provided with three elements/ integers and our task is to compare them and find the smallest element/ integer among them.
#include <bits/stdc++.h>
using namespace std;
int main() {
   int a = 45, b = 72, c = 10;
   if (a <= b && a <= c)
      cout << a << " is smallest" << endl;
   else if (b <= a && b <= c)
      cout << b << " is smallest" << endl;
   else
      cout << c << " is smallest" << endl;
      return 0;
}
10 is smallest
Frequency of each character in a String using unordered_map in C++ - GeeksforGeeks

26 Oct, 2020
Given a string str, the task is to find the frequency of each character of a string using an unordered_map in C++ STL.
Examples: 
Input: str = “geeksforgeeks” Output: r 1 e 4 s 2 g 2 k 2 f 1 o 1
Input: str = “programming” Output: n 1 i 1 p 1 o 1 r 2 a 1 g 2 m 2 
Approach: 
Traverse each character of the given string str.Check whether the current character is present in unordered_map or not.If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below: 
Traverse each character of the given string str.
Check whether the current character is present in unordered_map or not.
If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below: 
if(M.find(s[i])==M.end()) {
    M.insert(make_pair{s[i], 1});
}
else {
    M[s[i]]++;
}

        4. Traverse the unordered_map and print the frequency of each characters stored as a mapped value.
Below is the implementation of the above approach:
CPP
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; void printFrequency(string str){    // Define an unordered_map    unordered_map<char, int> M;     // Traverse string str check if    // current character is present    // or not    for (int i = 0; str[i]; i++)    {        // If the current characters        // is not found then insert        // current characters with        // frequency 1        if (M.find(str[i]) == M.end())        {            M.insert(make_pair(str[i], 1));        }         // Else update the frequency        else        {            M[str[i]]++;        }    }     // Traverse the map to print the    // frequency    for (auto& it : M) {        cout << it.first << ' ' << it.second << '\n';    }} // Driver Codeint main(){    string str = "geeksforgeeks";     // Function call    printFrequency(str);    return 0;}
r 1
e 4
s 2
g 2
k 2
f 1
o 1

rajahimanshu
cpp-strings
cpp-unordered_map
frequency-counting
STL
C++
cpp-strings
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Iterators in C++ STL
std::string class in C++
Inline Functions in C++
Number of Ways to Paint N × 3 Grid in C++

Suppose we have grid of size n x 3 and we want to paint each cell of the grid with exactly one of the three colors. The colors are Red, Yellow or Green. Now there is a constraint that is no two adjacent cells have the same color. We have n the number of rows of the grid. We have to find the number of ways we can paint this grid. The answer may be very large so return it modulo 10^9 + 7.
So, if the input is like 1, then the output will be 12
To solve this, we will follow these steps −
m = 1^9 + 7
m = 1^9 + 7
Define a function add(), this will take a, b,
Define a function add(), this will take a, b,
return ((a mod m) + (b mod m)) mod m
return ((a mod m) + (b mod m)) mod m
From the main method do the following −
From the main method do the following −
a123 := 6, a121 = 6
a123 := 6, a121 = 6
for initialize i := 2, when i <= n, update (increase i by 1), do −b121 := add(3 * a121, 2 * a123)b123 := add(2 * a121, 2 * a123)a121 := b121a123 := b123
for initialize i := 2, when i <= n, update (increase i by 1), do −
b121 := add(3 * a121, 2 * a123)
b121 := add(3 * a121, 2 * a123)
b123 := add(2 * a121, 2 * a123)
b123 := add(2 * a121, 2 * a123)
a121 := b121
a121 := b121
a123 := b123
a123 := b123
return add(a123, a121)
return add(a123, a121)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const lli mod = 1e9 + 7;
class Solution {
   public:
   lli add(lli a, lli b){
      return ((a % mod) + (b % mod)) % mod;
   }
   int numOfWays(int n){
      lli a123 = 6, a121 = 6;
      lli b123, b121;
      for (int i = 2; i <= n; i++) {
         b121 = add(3 * a121, 2 * a123);
         b123 = add(2 * a121, 2 * a123);
         a121 = b121;
         a123 = b123;
      }
      return add(a123, a121);
   }
};
main(){
   Solution ob;
   cout << (ob.numOfWays(3));
}
3
246
Alternate casing a string in JavaScript

We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters from the original string converted to lowercase and all the lowercase characters converted to uppercase from the original string.
For example: If the string is −
const str = 'The Case OF tHis StrinG Will Be FLiPped';
Then the output should be −
const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';
The code for this will be −
const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)<= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;
const flipCase = str => {
   let newStr = '';
   const margin = 32;
   for(let i = 0; i < str.length; i++){
      const curr = str[i];
      if(isLowerCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
      }else if(isUpperCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
      }else{
         newStr += curr;
      };
   };
   return newStr;
};
console.log(flipCase(str));
The output in the console −
tHE cASE of ThIS sTRINg wILL bE flipped
Tryit Editor v3.7

Tryit: HTML base element
Get value for key from nested JSON object in JavaScript

Suppose, we have a nested JSON object like this −
const obj = {
   "prop": [
      {
         "key": "FOO",
         "value": "Foo is wonderfull, foo is great"
      },
      {
         "key": "BAR",
         "value": "Bar is bad, really bad"
      }
   ]
};
We are required to write a JavaScript function that takes in one such object as the first argument, and a key string as the second argument.
Our function should then return the value for the "value" property to which that particular key property belongs.
The code for this will be −
const obj = {
   "prop": [
      {
         "key": "FOO",
         "value": "Foo is wonderfull, foo is great"
      },
      {
         "key": "BAR",
         "value": "Bar is bad, really bad"
      }
   ]
};
const findByKey = (obj, key) => {
   const arr = obj['prop'];
   if(arr.length){
      const result = arr.filter(el => {
         return el['key'] === key;
      });
      if(result && result.length){
         return result[0].value;
      }
      else{
         return '';
      }
   }
}
console.log(findByKey(obj, 'BAR'));
And the output in the console will be −
Bar is bad, really bad
How to get the nth percentile of a Pandas series?

A percentile is a term used in statistics to express how a score compares to other scores in the same set. In this program, we have to find nth percentile of a Pandas series.
Step 1: Define a Pandas series.
Step 2: Input percentile value.
Step 3: Calculate the percentile.
Step 4: Print the percentile.
import pandas as pd

series = pd.Series([10,20,30,40,50])
print("Series:\n", series)

n = int(input("Enter the percentile you want to calculate: "))
n = n/100

percentile = series.quantile(n)
print("The {} percentile of the given series is: {}".format(n*100, percentile))
Series:
0    10
1    20
2    30
3    40
4    50
dtype: int64
Enter the percentile you want to calculate: 50
The 50.0 percentile of the given series is: 30.0
The quantile function in the Pandas library takes values only between 0 and 1 as parameters. Therefore, we have to divide the percentile value by 100 before passing it to the quantile function.
How to change the tick size using ggplot2 in R?

To change the tick size using ggplot2, we can use theme function with argument axis.ticks.length. For example, if we have a data frame called df that contains two columns say x and y then the scatterplot between x and y with larger size of tick marks can be created by using the below command −
ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.8,"inch"))
Consider the below data frame −
 Live Demo
x<-rnorm(20)
y<-rnorm(20)
df<-data.frame(x,y)
df
      x              y
1   2.5494830  -0.587904992
2  -0.5864972   0.006669457
3   0.9554755  -3.925291145
4   0.6686948  -2.326550523
5  -0.3267310   0.738981444
6  -0.8751193  -0.438232843
7   0.5477108   0.214512133
8  -0.4767738   0.451001999
9  -0.5364709   0.335897135
10   0.5853087 -0.665692002
11 -1.7818255   0.944527193
12 -0.9670748   0.639372414
13  0.4873353   0.466036727
14  0.3669196   2.732934553
15  0.9450203  -0.201909686
16 -1.1646289  -0.533447384
17 -1.8637459   1.186856615
18 -1.5751590  -1.154048208
19 -0.2266776   1.813758654
20 -0.7125976   0.251823020
Loading ggplot2 package and creating scatterplot between x and y with default size of tick marks −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating scatterplot between x and y with larger size of tick marks −
ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.2,"inch"))
ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.50,"cm"))
How to toggle text with JavaScript?

To toggle text with JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .textDiv {
      font-size: 20px;
      background-color: rgb(199, 228, 157);
      width: 100%;
      padding: 15px;
      font-weight: bold;
   }
   .toggleBtn {
      padding: 15px;
      border: none;
      background-color: rgb(106, 41, 153);
      color: white;
      font-size: 18px;
   }
</style>
</head>
<body>
<h1>Toggle Text example</h1>
<button class="toggleBtn">Click Me</button>
<h2>Click on the above button to toggle below text</h2>
<div class="textDiv">Old Text</div>
<script>
   document .querySelector(".toggleBtn") .addEventListener("click", toggleText);
   function toggleText() {
      var x = document.querySelector(".textDiv");
      if (x.innerHTML === "Old Text") {
         x.innerHTML = "New Text";
      } else {
         x.innerHTML = "Old Text";
      }
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Click Me” button −
Converting images to a Base64 data URL using Javascript

To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it.
This will return the base64 encoded data URI of the image. For example,
if you have an image with id my-image, you can use the following −
function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = img.width;
   canvas.height = img.height;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}
// Select the image
const img = document.querySelector('#my-image');
img.addEventListener('load', function (event) {
   const dataUrl = getDataUrl(event.currentTarget);
   console.log(dataUrl);
});
This will give the output −
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB
ctype_upper() function in PHP

The ctype_upper() function in PHP check for uppercase character(s). It returns TRUE if every character in text is an uppercase letter in the current locale.
ctype_upper(str)
str − The tested string
str − The tested string
The ctype_upper() function returns TRUE if every character in text is an uppercase letter in the current locale.
The following is an example −
 Live Demo
<?php
   $arr = array('9898jjhh', 'PQR', 'Amit');

   foreach ($arr as $demo) {
      if (ctype_upper($demo)) {
         echo "$demo has all uppercase letters. \n";
      } else {
         echo "$demo does not have all uppercase letters. \n";
      }
   }
?>
The following is the output −
9898jjhh does not have all uppercase letters.
PQR has all uppercase letters.
Amit does not have all uppercase letters.
Let us see another example −
 Live Demo
<?php
   $str = 'AUSTRALIA';

   if (ctype_upper($str)) {
      echo "Word has all uppercase characters!\n";
   } else {
      // if False then return No
      echo "Word does not have all uppercase characters!\n";
   }
?>
The following is the output −
Word has all uppercase characters!
How to get the list of all versions of the object from S3 present in AWS Resource

In this article, we will see how to get the list of all versions of the object from S3 those are present in AWS Resource.
List out all the versions of test.zip from Bucket_1/testfolder of S3.
Problem Statement: Use boto3 library in Python to get list of all versions of the object from S3.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2: bucket_name is the required parameter.
Step 2: bucket_name is the required parameter.
Step 3: Create an AWS session using boto3 lib
Step 3: Create an AWS session using boto3 lib
Step 4: Create an AWS client for s3
Step 4: Create an AWS client for s3
Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any.
Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any.
Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket.
Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket.
Step 7: Return the list of all versions of the object.
Step 7: Return the list of all versions of the object.
Use the following code get the list of all versions of the object from AWS S3 −
import boto3
from botocore.exceptions import ClientError

def list_all_objects_version(bucket_name, prefix_name):  
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
      result = s3_client.list_object_versions(Bucket=bucket_name, Prefix=prefix_name)
   except ClientError as e:
      raise Exception("boto3 client error in list_all_objects_version function: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in list_all_objects_version function of s3 helper: " + e.__str__())
print(list_all_objects_version("Bucket_1","testfolder"))
{'ResponseMetadata': {'RequestId': 'H4VAGM3YP6', 'HostId': ***********', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': ***************', 'x-amz-request-id': 'H4VAGM3YP6', 'date': 'Sat, 03 Apr 2021 08:04:08 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': False, 'KeyMarker': '', 'VersionIdMarker': '',
'Versions': [{'ETag': '"705e2e674b04ca71"', 'Size': 1773, 'StorageClass': 'STANDARD', 'Key': 'testfolder/test.zip', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 12, 18, 14, 13, 18, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928*******************************'}}], 'Name': 'Bucket_1', 'Prefix': 'testfolder', 'MaxKeys': 1000, 'EncodingType': 'url'}
Format Date and Time in Perl

You can use localtime() function in Perl to get a list of 9-elements and later you can use the printf() function to format date and time based on your requirements as follows −
 Live Demo
#!/usr/local/bin/perl
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
printf("Time Format - HH:MM:SS\n");
printf("%02d:%02d:%02d", $hour, $min, $sec);
When the above code is executed, it produces the following result −
Time Format - HH:MM:SS
06:58:52
HTML - Fonts Reference

Fonts are specific to platform. You will have different look and feel of a web page on different machines running different operating systems like Windows, Linux or Mac iOS. Here we are giving a list of fonts which are available in various operating systems.
HTML <font> tag is deprecated in version 4.0 onwards and now all fonts are set by using CSS. Here is the simple syntax of setting font of a body of web page.
body {
   font-family: "new century schoolbook";
}  
or  
<body style = "font-family:new century schoolbook;">

<!DOCTYPE html>
<html>

   <head>
      <title>Font Setting Using CSS</title>
   </head>

   <body>
      <p>Change any of the style and try it.</p>
      <div style = "font-family:verdana;">This is demo for font family</div>
      <br />
      
      <div style = "font-size:120%;">This is demo for font size</div>
      <br />
      
      <div style = "font-size:14pt;">This is demo for font size</div>
   </body>

</html>
This will produce the following result −
Change any of the style and try it.
You can check example fonts here − Microsoft Fonts Examples
Following is the list of fonts supported by Macintosh System 7 and higher versions
You can check example fonts here − Mac Fonts Examples
Following is the list of fonts supported by most Unix System variants
You can check example fonts here − Unix Fonts Examples
There are 27 = 128 printable characters which can be represented by different 7-BIT ASCII codes. Another set of characters are not for HTML representation but they are devised to control hardware.
Following tables list down all the 7-BIT ASCII codes and their equivalent HTML Entity Codes.
If you want to see equivalent HEX, OCT and extended set of ASCII codes then check next chapter.

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to set JAVA_HOME on Linux | export JAVA_HOME

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
We can set JAVA_HOME on Linux in different ways. One of the prominent ways is to set the JAVA_HOME using an environment variable.
Environment variables can be set up in three different types:
Local Environment variables: Bind to a specific session.
User Environment variables: Bind to a specific user.
System Environment variables: Bind to system-wide.
Using export command we can set the JAVA_HOME, but as we discussed, this is volatile – as soon as we leave the terminal session, this setting will go away.
$ export JAVA_HOME=/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
$ echo $JAVA_HOME
/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
export PATH=$PATH:$JAVA_HOME/bin
We can permanently set the JAVA_HOME using /etc/environment file. This will be applied to system-level.
$ sudo vi /etc/environment

Add the below lines to add the JAVA_HOME
JAVA_HOME=/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
PATH=$PATH:$JAVA_HOME/bin
Apply the environment variables by using the source command.
$ source /etc/environment
$ echo $JAVA_HOME
/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
How to set JAVA_HOME on windows
Happy Learning 🙂

Java 8 – How to set JAVA_HOME on Windows10
How to install Java on Mac OS
How to restart MsSQL server on Linux
How to find Linux RHEL version ? OS and Kernel Version ?
Python – How to read environment variables ?
How to install Maven on windows 7 command line
How to install Maven in Mac OSX
How to install Maven on Windows10
Linux vi commands list
Difference between Path vs Classpath in Java
How set AWS Access Keys in Windows or Mac Environment
How to Install Ant on Windows 10
C How to Pass Arrays to Functions
Jdk Jre Jvm and differences
C Local and Global Variables

Java 8 – How to set JAVA_HOME on Windows10
How to install Java on Mac OS
How to restart MsSQL server on Linux
How to find Linux RHEL version ? OS and Kernel Version ?
Python – How to read environment variables ?
How to install Maven on windows 7 command line
How to install Maven in Mac OSX
How to install Maven on Windows10
Linux vi commands list
Difference between Path vs Classpath in Java
How set AWS Access Keys in Windows or Mac Environment
How to Install Ant on Windows 10
C How to Pass Arrays to Functions
Jdk Jre Jvm and differences
C Local and Global Variables
Bitwise AND of Numbers Range in C++

Suppose we have a range [m, n] where 0 <= m <= n <= 2147483647. We have to find the bitwise AND of all numbers in this range, inclusive. So if the range is [5, 7], then the result will be 4.
To solve this, we will follow these steps −
i := 0
i := 0
while m is not n, thenm := m/2, n := n / 2, increase i by 1
while m is not n, then
m := m/2, n := n / 2, increase i by 1
m := m/2, n := n / 2, increase i by 1
return m after shifting to the left i times.
return m after shifting to the left i times.
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int rangeBitwiseAnd(int m, int n) {
      int i = 0;
      while(m != n){
         m >>= 1;
         n >>= 1;
         i++;
      }
      return m << i;
   }
};
main(){
   Solution ob;
   cout << (ob.rangeBitwiseAnd(5,7));
}
5
7
4
\wedge - Tex Command

\wedge - Used to create wedge symbol.
{ \wedge}
\wedge command draws wedge symbol.

\wedge

∧



\wedge

∧


\wedge

    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
How to create a System Tray icon of a Tkinter application?

A System Tray icon is used for showing the application’s running state in the taskbar. It typically shows which application is currently running. The system tray icon is visible in the taskbar.
To create a System Tray icon of a tkinter application, we can use pystray module in Python. It has many inbuilt functions and methods that can be used to configure the system tray icon of the application.
To install pystray in your machine you can type "pip install pystray" command in your shell or command prompt.
To create a System Tray icon, you can follow these steps,
Import the required libraries − Pystray, Python PIL or Pillow.
Import the required libraries − Pystray, Python PIL or Pillow.
Define a function hide_window() to withdraw the window and provide the icon in the system tray.
Define a function hide_window() to withdraw the window and provide the icon in the system tray.
Add and define two menu items, "Show" and "Quit".
Add and define two menu items, "Show" and "Quit".
Add a command in the menu items by defining a function for Show and Quit.
Add a command in the menu items by defining a function for Show and Quit.
# Import the required libraries
from tkinter import *
from pystray import MenuItem as item
import pystray
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win=Tk()
win.title("System Tray Application")

# Set the size of the window
win.geometry("700x350")

# Define a function for quit the window
def quit_window(icon, item):
   icon.stop()
   win.destroy()

# Define a function to show the window again
def show_window(icon, item):
   icon.stop()
   win.after(0,win.deiconify())

# Hide the window and show on the system taskbar
def hide_window():
   win.withdraw()
   image=Image.open("favicon.ico")
   menu=(item('Quit', quit_window), item('Show', show_window))
   icon=pystray.Icon("name", image, "My System Tray Icon", menu)
   icon.run()

win.protocol('WM_DELETE_WINDOW', hide_window)

win.mainloop()
If you will run the above code, it will display a window.
When we close the window it will still appear in the Taskbar as a System Tray icon.
String Formatting in Java using %

Followimg is the code to implement String formatting in Java using % −
 Live Demo
public class Demo {
   public static void main(String args[]){
      String my_str = " sample.";
      String concat_Str = String.format("This is a" + "%s", my_str);
      String format_str_1 = String.format("The value is %.4f", 78.92367);
      System.out.println(concat_Str);
      System.out.println(format_str_1);
   }
}
This is a sample.
The value is 78.9237
A class named Demo contains the main function. Here a string value is defined, which is used to format the string, by concatenating it to another variable. Similarly, a floating point number is also formatted using the ‘%’ operator. Both these values are printed on the console.
Instruction set of 8051

The instructions of 8051 Microcontroller can be classified into five different groups. These groups are like below
Data Transfer Group
Data Transfer Group
Arithmetic Group
Arithmetic Group
Logical Group
Logical Group
Program Branch Group
Program Branch Group
Bit Processing Group
Bit Processing Group
This Bit-Processing group is also known as Boolean Variable Manipulation.
Like 8085, some instruction has two operands. The first operand is the Destination, and the second operator is Source.
In the following examples, you will get some notations. The notations are like −
Rn = Any register from R0to R7
Ri = Either R0 or R1
d8 = Any 8-bit immediate data (00H to FFH)
d16 = 16-bit immediate data
a8 = 8-bit address
bit = 8-bit address of bit which is bit addressable
rel = 8-bit signed displacement. The range is -128 to 127. It is relative to the first byte of the instruction.
Selenium - Synchronization

To synchronize between script execution and application, we need to wait after performing appropriate actions. Let us look at the ways to achieve the same.
Thread.Sleep is a static wait and it is not a good way to use in scripts as it is sleep without condition.
Thread.Sleep(1000); //Will wait for 1 second.
An 'explicit wait,' waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on an object once it is visible.
WebDriver driver = new FirefoxDriver();
driver.get("Enter an URL"S);
WebElement DynamicElement = 
   (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));
Implicit wait is used in cases where the WebDriver cannot locate an object immediately because of its unavailability. The WebDriver will wait for a specified implicit wait time and it will not try to find the element again during the specified time period.
Once the specified time limit is crossed, the webDriver will try to search the element once again for one last time. Upon success, it proceeds with the execution; upon failure, it throws exception.
It is a kind of global wait which means the wait is applicable for the entire driver. Hence, hardcoding this wait for longer time periods will hamper the execution time.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Enter an URL");
WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));
A FluentWait instance defines the maximum amount of time to wait for a condition to take place, as well as the frequency with which to check the existence of the object condition.
Let us say we will 60 seconds for an element to be available on the page, but we  will check its avilable once in every 10 seconds.
Wait wait = 
   new FluentWait(driver).withTimeout(60, SECONDS).pollingEvery(10, SECONDS).ignoring(NoSuchElementException.class);
   
   WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() {
   
   public WebElement apply(WebDriver driver) {
      return driver.findElement(By.id("dynamicelement"));
   }
});

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
Perl scalar Function

This function forces the evaluation of EXPR to be in scalar context, even if it would normally work in list context.
Following is the simple syntax for this function −
scalar EXPR

This function returns Scalar.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

@a = (1,2,3,4);
@b = (10,20,30,40);

@c = ( @a, @b );
print "1 - Final Array is @c\n";

@c = ( scalar(@a), scalar(@b) );
print "2 - Final Array is @c\n";
When above code is executed, it produces the following result −
1 - Final Array is 1 2 3 4 10 20 30 40
2 - Final Array is 4 4


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Google Guice - @Provides Annotation

Guice provides a way to create bindings with complex objects using @provides method.
@Provides
public SpellChecker provideSpellChecker() {
   String dbUrl = "jdbc:mysql://localhost:5326/emp";
   String user = "user";
   int timeout = 100;
   SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
   return SpellChecker;
}
This methods is being part of Binding Module and provides the complex object to be mapped. See the complete example below.
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provides;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck();
   } 
}
class TextEditor {
   private SpellChecker spellChecker;
   
   @Inject
   public TextEditor( SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
   public void makeSpellCheck() {
      spellChecker.checkSpelling();
   } 
}

//Binding Module
class TextEditorModule extends AbstractModule {
   @Override
   protected void configure() {} 

   @Provides
   public SpellChecker provideSpellChecker() {
      String dbUrl = "jdbc:mysql://localhost:5326/emp";
      String user = "user";
      int timeout = 100;

      SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
      return SpellChecker;
   }
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   private String dbUrl;
   private String user;
   private Integer timeout;

   @Inject
   public SpellCheckerImpl(String dbUrl, 
      String user, 
      Integer timeout) {
      this.dbUrl = dbUrl;
      this.user = user;
      this.timeout = timeout;
   } 
   @Override
   public void checkSpelling() { 
      System.out.println("Inside checkSpelling." );
      System.out.println(dbUrl);
      System.out.println(user);
      System.out.println(timeout);
   }
}
Now, compile and run the file. You can see the following output −
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
user
100


    27 Lectures 
     1.5 hours 

 Lemuel Ogbunude
 Print
 Add Notes
 Bookmark this page
Explain asynchronous functions in JavaScript with an example

The asynchronous functions are defined with async keyword and were introduced in ES 2015. These functions were introduced to define a better way to write consice promises than callback. The await keyword is used inside an async function to pause the flow of control
and it waits for promise.
Following is the code for asynchronous functions in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Asynchronous functions in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the function asyncFunc</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   function displayText() {
      return new Promise((resolve) => {
         setTimeout(() => {
            resolve("Hello World");
         }, 1500);
      });
   }
   async function asyncFunc() {
      resEle.innerHTML = await displayText();
   }
   BtnEle.addEventListener("click", () => {
      asyncFunc();
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button and waiting for 2 seconds −
SymPy - Solvers

Since the symbols = and == are defined as assignment and equality operators in Python, they cannot be used to formulate symbolic equations. SymPy provides Eq() function to set up an equation.
>>> from sympy import * 
>>> x,y=symbols('x y') 
>>> Eq(x,y)

The above code snippet gives an output equivalent to the below expression −
x = y
Since x=y is possible if and only if x-y=0, above equation can be written as −
>>> Eq(x-y,0)

The above code snippet gives an output equivalent to the below expression −
x − y = 0
The solver module in SymPy provides soveset() function whose prototype is as follows −
solveset(equation, variable, domain)

The domain is by default S.Complexes. Using solveset() function, we can solve an algebraic equation as follows −
>>> solveset(Eq(x**2-9,0), x)

The following output is obtained −
{−3, 3}
>>> solveset(Eq(x**2-3*x, -2),x)

The following output is obtained after executing the above code snippet −
{1,2}
The output of solveset is a FiniteSet of the solutions. If there are no solutions, an EmptySet is returned
>>> solveset(exp(x),x)

The following output is obtained after executing the above code snippet −
∅
We have to use linsolve() function to solve linear equations.
For example, the equations are as follows −
x-y=4
x+y=1
>>> from sympy import * 
>>> x,y=symbols('x y') 
>>> linsolve([Eq(x-y,4),Eq( x + y ,1) ], (x, y))

The following output is obtained after executing the above code snippet −
{(52,−32)}
The linsolve() function can also solve linear equations expressed in matrix form.
>>> a,b=symbols('a b') 
>>> a=Matrix([[1,-1],[1,1]]) 
>>> b=Matrix([4,1]) 
>>> linsolve([a,b], (x,y))

We get the following output if we execute the above code snippet −
{(52,−32)}
For this purpose, we use nonlinsolve() function. Equations for this example −
a2+a=0 a-b=0
>>> a,b=symbols('a b') 
>>> nonlinsolve([a**2 + a, a - b], [a, b])

We get the following output if we execute the above code snippet −
{(−1,−1),(0,0)}
First, create an undefined function by passing cls=Function to the symbols function. To solve differential equations, use dsolve.
>>> x=Symbol('x') 
>>> f=symbols('f', cls=Function) 
>>> f(x)

The following output is obtained after executing the above code snippet −
f(x)
Here f(x) is an unevaluated function. Its derivative is as follows −
>>> f(x).diff(x)

The above code snippet gives an output equivalent to the below expression −
ddxf(x)
We first create Eq object corresponding to following differential equation
>>> eqn=Eq(f(x).diff(x)-f(x), sin(x)) 
>>> eqn

The above code snippet gives an output equivalent to the below expression −
−f(x)+ddxf(x)=sin⁡(x)
>>> dsolve(eqn, f(x))

The above code snippet gives an output equivalent to the below expression −
f(x)=(c1−e−xsin(x)2−e−xcos(x)2)ex
 Print
 Add Notes
 Bookmark this page
Lexicographically next permutation in C++

Here we will see how to generate lexicographically next permutation of a string in C++. The lexicographically next permutation is basically the greater permutation. For example, the next of “ACB” will be “BAC”. In some cases, the lexicographically next permutation is not present, like “BBB” or “DCBA” etc.
In C++ we can do it by using a library function called next_permutation(). This is present in the algorithm header file.
#include <iostream>
#include <algorithm>
using namespace std;
main() {
   string s = "DBAC";
   for(int i = 0; i<5; i++) {
      bool val = next_permutation(s.begin(), s.end());
      if (val == false) {
         cout << "No next permutation" << endl;
         break;
      } else
      cout << "Next: " << s << endl;
   }
}
Next: DBCA
Next: DCAB
Next: DCBA
No next permutation
fread() function in C++

The C/C++ library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr. Following is the declaration for fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
The Following table contains the fread() parameters and description:
The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.
#include <stdio.h>
#include <string.h>
int main () {
   FILE *fp;
   char c[] = "this is tutorialspoint";
   char buffer[100];
   /* Open file for both reading and writing */
   fp = fopen("file.txt", "w+");
   /* Write data to the file */
   fwrite(c, strlen(c) + 1, 1, fp);
   /* Seek to the beginning of the file */
   fseek(fp, 0, SEEK_SET);
   /* Read and display data */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);
   return(0);
}
Let us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −
this is tutorialspoint
Working with Page Break – Python .docx Module

03 Jan, 2021
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also add page breaks using this module. To add a page break in a word document you can use add_page_break() method. 
This method adds a hard page break in the document and creates a new paragraph object. This is an essential paragraph styling tool. Whenever the requirement is to start a new page, mostly cases where you want a new page for a new topic, a single method is sufficient. It helps increase clarity and improves presentation to reap the most of word.
Syntax: doc.add_page_break()
Import module
Create docx object
Add add_page_break() function whenever the control need to be shift to a new page
Save document.
Example:
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Adding a paragraphdoc.add_heading('Page 1:', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')  # Adding a page breakdoc.add_page_break()  # Adding a paragraphdoc.add_heading('Page 2:', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Page – 1
Page – 2
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.