code-rag-bench/online-tutorials huggingface dataset:
0-1 BFS (Shortest Path in a Binary Weight Graph) In C Program?

Suppose we have a graph with some nodes and connected edges. Each edge has binary weights. So the weights will be either 0 or 1. A source vertex is given. We have to find shortest path from source to any other vertices. Suppose the graph is like below −
In normal BFS algorithm all edge weights are same. Here some are 0 and some are 1. In each step we will check the optimal distance condition. Here we will use the double ended queue to store the node. So we will check the edge weight. If it is 0, then push it at front, otherwise at back. Let us check the algorithm to get the better idea.
binaryBFS(src) −
begin
   define dist array to store source to vertex i into dist[i]. Initially fill with infinity
   dist[src] := 0
   insert src into queue Q.
   v := first element from Q, and delete it from queue
   while Q is not empty, do
      for all connected edge e of v, do
         if the weight of v to next of i > dist[v] + weight of v to i weight, then update the weight
            if the weight is 0, then store to front, otherwise back
         end if
      done
   done
   print all distance from dist array
end
#include<iostream>
#include<vector>
#include<deque>
#define V 8
using namespace std;
struct node {
   int next, weight;
};
vector <node> edges[V];
void binaryBFS(int src) {
   int dist[V];
   for (int i=0; i<V; i++) //initially set as infinity
      dist[i] = INT_MAX;
   deque <int> Q;
   dist[src] = 0; //distance from source to source is 0
   Q.push_back(src);
   while (!Q.empty()) {
      int v = Q.front(); //delete first vertex, and store to v
      Q.pop_front();
      for (int i=0; i<edges[v].size(); i++) {
         //check optimal distance
         if (dist[edges[v][i].next] > dist[v] + edges[v][i].weight) {
            dist[edges[v][i].next] = dist[v] + edges[v][i].weight;
            if (edges[v][i].weight == 0) //0 weight edge is stored at front, otherwise at back
               Q.push_front(edges[v][i].next);
            else
               Q.push_back(edges[v][i].next);
         }
      }
   }
   for (int i=0; i<V; i++)
      cout << dist[i] << " ";
}
void addEdge(int u, int v, int wt) {
   edges[u].push_back({v, wt});
   edges[v].push_back({u, wt});
}
int main() {
   addEdge(0, 1, 0);
   addEdge(0, 3, 1);
   addEdge(0, 4, 0);
   addEdge(1, 2, 1);
   addEdge(1, 7, 0);
   addEdge(2, 5, 1);
   addEdge(2, 7, 0);
   addEdge(3, 4, 0);
   addEdge(3, 6, 1);
   addEdge(4, 6, 1);
   addEdge(5, 7, 1);
   addEdge(6, 7, 1);
   int src = 6;
   binaryBFS(src);
}
1 1 1 1 1 2 0 1
Find minimum difference between any two element in C++

Suppose we have an array of n elements called A. We have to find the minimum difference between any two elements in that array. Suppose the A = [30, 5, 20, 9], then the result will be 4. this is the minimum distance of elements 5 and 9.
To solve this problem, we have to follow these steps −
Sort the array in non-decreasing order
Sort the array in non-decreasing order
Initialize the difference as infinite
Initialize the difference as infinite
Compare all adjacent pairs in the sorted array and keep track of the minimum one
Compare all adjacent pairs in the sorted array and keep track of the minimum one
#include<iostream>
#include<algorithm>
using namespace std;
int getMinimumDifference(int a[], int n) {
   sort(a, a+n);
   int min_diff = INT_MAX;
   for (int i=0; i<n-1; i++)
      if (a[i+1] - a[i] < min_diff)
         min_diff = a[i+1] - a[i];
   return min_diff;
}
int main() {
   int arr[] = {30, 5, 20, 9};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Minimum difference between two elements is: " << getMinimumDifference(arr, n);
}
Minimum difference between two elements is: 4
C++ Program to Implement Ternary Tree

A ternary tree, is a tree data structure in which each node has at most three child nodes, usually represented as “left”, “mid” and “right”. In this tree, nodes with children are parent nodes, and child nodes may contain references to their parents. This is a C++ Program to Implement Ternary Tree and traversal of the tree.
Begin
   Declare function insert(struct nod** root, char *w)
      if (!(*root)) then
         *root = newnod(*w);
         if ((*w) < (*root)->d) then
            insert(&( (*root)->l ), w);
         else if ((*w) > (*root)->d) then
            insert(&( (*root)->r ), w);
         else if (*(w+1))
            insert(&( (*root)->eq ), w+1);
      else
         (*root)->EndOfString = 1;
End.
For Traversal of tree:
Begin
   Declare function traverseTTtil(struct nod* root, char* buffer,
   int depth)
      if (root) then
         traverseTTtil(root->l, buffer, depth)
            buffer[depth] = root->d
            if (root->EndOfString) then
               buffer[depth+1] = '\0'
               print the value of buffer.
            traverseTTtil(root->eq, buffer, depth + 1);
            traverseTTtil(root->r, buffer, depth);
End.
#include<stdlib.h>
#include<iostream>
using namespace std;
struct nod {
   char d;
   unsigned End.
   fString: 1;
   struct nod *l, *eq, *r;
}*t = NULL;
struct nod* newnod(char d) {
   t = new nod;
   t->d = d;
   t->End.
   fString = 0;
   t->l = t->eq = t->r = NULL;
   return t;
}
void insert(struct nod** root, char *w) {
   if (!(*root))
      *root = newnod(*w);
   if ((*w) < (*root)->d)
      insert(&( (*root)->l ), w);
   else if ((*w) > (*root)->d)
      insert(&( (*root)->r ), w);
   else {
      if (*(w+1))
         insert(&( (*root)->eq ), w+1);
      else
         (*root)->End.
      fString = 1;
   }
}
void traverseTTtil(struct nod* root, char* buffer, int depth) {
   if (root) {
      traverseTTtil(root->l, buffer, depth);
      buffer[depth] = root->d;
      if (root->End. String) {
         buffer[depth+1] = '\0';
         cout<<buffer<<endl;
      }
      traverseTTtil(root->eq, buffer, depth + 1);
      traverseTTtil(root->r, buffer, depth);
   }
}
void traverseTT(struct nod* root) {
   char buffer[50];
   traverseTTtil(root, buffer, 0);
}
int main() {
   struct nod *root = NULL;
   insert(&root, "mat");
   insert(&root, "bat");
   insert(&root, "hat");
   insert(&root, "rat");
   cout<<"Following is traversal of ternary tree\n";
   traverseTT(root);
}
Following is traversal of ternary tree
bat
hat
mat
rat
How to write a global error handler in JavaScript?

The following global error handler will show how to catch unhandled exception −
<!DOCTYPE html>
<html>
   <body>
      <script>
         window.onerror = function(errMsg, url, line, column, error) {
            var result = !column ? '' : '\ncolumn: ' + column;
            result += !error;
            document.write("Error= " + errMsg + "\nurl= " + url + "\nline= " + line + result);
            var suppressErrorAlert = true;
            return suppressErrorAlert;
         };
         setTimeout(function() {
            eval("{");
         }, 500)
      </script>
   </body>
</html>
How to simulate pressing enter in html text input with Selenium?

We can simulate pressing enter in the html text input box with Selenium webdriver. We shall take the help of sendKeys method and pass Keys.ENTER as an argument to the method. Besides, we can pass Keys.RETURN as an argument to the method to perform the same task.
Also, we have to import org.openqa.selenium.Keys package to the code for using the Keys class. Let us press ENTER/RETURN after entering some text inside the below input box.
Code Implementation with Keys.ENTER.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class PressEnter{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.id("gsc-i-id1"));
      l.sendKeys("Selenium");
      // press enter with sendKeys method and pass Keys.ENTER
      l.sendKeys(Keys.ENTER);
      driver.close();
   }
}
Code Implementation with Keys.RETURN.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class PressReturn{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.id("gsc-i-id1"));
      l.sendKeys("Selenium");
      // press enter with sendKeys method and pass Keys.RETURN
      l.sendKeys(Keys.RETURN);
      driver.close();
   }
}
C++ Program for Longest Common Subsequence

A subsequence is a sequence with the same order of the set of elements. For the sequence “stuv”, the subsequences are “stu”, “tuv”, “suv”,.... etc.
For a string of length n, there can be 2n ways to create subsequence from the string.
The longest common subsequence for the strings “ ABCDGH ” and “ AEDFHR ” is of length 3.
 Live Demo
#include <iostream>
#include <string.h>
using namespace std;
int max(int a, int b);
int lcs(char* X, char* Y, int m, int n){
   if (m == 0 || n == 0)
      return 0;
   if (X[m - 1] == Y[n - 1])
      return 1 + lcs(X, Y, m - 1, n - 1);
   else
      return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
int max(int a, int b){
   return (a > b) ? a : b;
}
int main(){
   char X[] = "AGGTAB";
   char Y[] = "GXTXAYB";
   int m = strlen(X);
   int n = strlen(Y);
   printf("Length of LCS is %d\n", lcs(X, Y, m, n));
   return 0;
}
Length of LCS is 4
MFC - Activex Control

An ActiveX control container is a parent program that supplies the environment for an ActiveX (formerly OLE) control to run.
ActiveX control is a control using Microsoft ActiveX technologies.
ActiveX control is a control using Microsoft ActiveX technologies.
ActiveX is not a programming language, but rather a set of rules for how applications should share information.
ActiveX is not a programming language, but rather a set of rules for how applications should share information.
Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java.
Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java.
You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC.
You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC.
Let us look into simple example of add ActiveX controls in your MFC dialog based application.
Step 1 − Right-click on the dialog in the designer window and select Insert ActiveX Control.
Step 2 − Select the Microsoft Picture Clip Control and click OK.
Step 3 − Resize the Picture control and in the Properties window, click the Picture field.
Step 4 − Browse the folder that contains Pictures. Select any picture.
Step 5 − When you run this application, you will see the following output.
Let us have a look into another simple example.
Step 1 − Right-click on the dialog in the designer window.
Step 2 − Select Insert ActiveX Control.
Step 3 − Select the Microsoft ProgressBar Control 6.0, click OK.
Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical.
Step 5 − Add control variable for Progress bar.
Step 6 − Add the following code in the OnInitDialog()
m_progBarCtrl.SetScrollRange(0,100,TRUE);
m_progBarCtrl.put_Value(53);
Step 7 − When you run this application again, you will see the progress bar in Vertical direction as well.
 Print
 Add Notes
 Bookmark this page
Anagram checking in Python using collections.Counter() - GeeksforGeeks

31 Oct, 2017
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
Examples:
Input : str1 = “abcd”, str2 = “dabc”
Output : True

Input : str1 = “abcf”, str2 = “kabc”
Output : False

This problem has existing solution please refer Check whether two strings are anagram of each other link. We will solve this problem in python in a single line using collections.Counter() module.
# Python code to check if two strings are# anagramfrom collections import Counter  def anagram(input1, input2):      # Counter() returns a dictionary data    # structure which contains characters     # of input as key and their frequencies    # as it's corresponding value    return Counter(input1) == Counter(input2)  # Driver functionif __name__ == "__main__":    input1 = 'abcd'    input2 = 'dcab'    print anagram(input1, input2)
Output:
True

How dictionary comparison works in python ?If we have two dictionary data structures in python dict1 = {‘a’:2,’b’:3,’c’:1} and dict2 = {‘b’:3,’c’:1,’a’:2} and we compare both of them like dict1=dict2 then it will result True. In python ordinary dictionary data structure does not follow any ordering of keys, when we compare two dictionaries then it compares three checks in order number of keys (if they don’t match, the dicts are not equal), names of keys (if they don’t match, they’re not equal) and value of each key (they have to be ‘==’, too).
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
anagram
frequency-counting
Python
Strings
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Multiplication of two Matrices using Java

Matrix multiplication leads to a new matrix by multiplying 2 matrices. But this is only possible if the columns of the first matrix are equal to the rows of the second matrix. An example of matrix multiplication with square matrices is given as follows.
 Live Demo
public class Example {
   public static void main(String args[]) {
      int n = 3;
      int[][] a = { {5, 2, 3}, {2, 6, 3}, {6, 9, 1} };
      int[][] b = { {2, 7, 5}, {1, 4, 3}, {1, 2, 1} };
      int[][] c = new int[n][n];
      System.out.println("Matrix A:");
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            System.out.print(a[i][j] + " ");
         }
         System.out.println();
      }
      System.out.println("Matrix B:");
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            System.out.print(b[i][j] + " ");
         }
         System.out.println();
      }
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++){
            for (int k = 0; k < n; k++) {
               c[i][j] = c[i][j] + a[i][k] * b[k][j];
            }
         }
      }
      System.out.println("The product of two matrices is:");
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            System.out.print(c[i][j] + " ");
         }
         System.out.println();
      }
   }
}
Matrix A:
5 2 3
2 6 3
6 9 1
Matrix B:
2 7 5
1 4 3
1 2 1
The product of two matrices is:
15 49 34
13 44 31
22 80 58
How to declare a pointer to a function in C?

A pointer is a variable whose value is the address of another variable or memory block, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable or block address.
Datatype *variable_name
Begin.
   Define a function show.
      Declare a variable x of the integer datatype.
      Print the value of varisble x.
   Declare a pointer p of the integer datatype.
   Define p as the pointer to the address of show() function.
   Initialize value to p pointer.
End.
This is a simple example in C to understand the concept a pointer to a function.
#include
void show(int x)
{
   printf("Value of x is %d\n", x);
}
int main()
{
   void (*p)(int); // declaring a pointer
   p = &show; // p is the pointer to the show()
   (*p)(7); //initializing values.
   return 0;
}
Value of x is 7.
Importance of join() method in Java?


A join() is a final method of Thread class and it can be used to join the start of a thread's execution to the end of another thread's execution so that a thread will not start running until another thread has ended. If the join() method is called on a thread instance, the currently running thread will block until the thread instance has finished executing.
public final void join() throws InterruptedException
public class JoinTest extends Thread {
   public void run() {
      for(int i=1; i <= 3; i++) {
         try {
            Thread.sleep(1000);
         } catch(Exception e) {
            System.out.println(e);
         }
         System.out.println("TutorialsPoint "+ i);
      }
   }
   public static void main(String args[]) {
      JoinTest t1 = new JoinTest();
      JoinTest t2 = new JoinTest();
      JoinTest t3 = new JoinTest();
      t1.start();
      try {
         t1.join(); // calling join() method
      } catch(Exception e) {
         System.out.println(e);
      }
      t2.start();
      t3.start();
   }
}
TutorialsPoint 1
TutorialsPoint 2
TutorialsPoint 3
TutorialsPoint 1
TutorialsPoint 1
TutorialsPoint 2
TutorialsPoint 2
TutorialsPoint 3
TutorialsPoint 3
Set element to center with Bootstrap

Use class center-block to set an element to center.
You can try to run the following code to set the element to center
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "row">
         <div class = "center-block" style = "width:200px; background-color:#ccc; color: white;">
            Element at center
         </div>
      </div>
   </body>
</html>
Creating a sqlite database from CSV with Python - GeeksforGeeks

26 Dec, 2020
Prerequisites: 
Pandas
SQLite
SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embedded systems and mobile applications. To interact with a SQLite database in Python, the sqlite3 module is required. 
Import module
Create a database and establish connection-
To establish a connection, we use the sqlite3.connect() function which returns a connection object. Pass the name of the database to be created inside this function. The complete state of a SQLite database is stored in a file with .db extension. If the path is not specified then the new database is created in the current working directory. 
Syntax:
sqlite3.connect(‘database_name.db’)
Import csv using read_csv()
Syntax:
pandas.read_csv(‘file_name.csv’)
Write the contents to a new table-
The function to_sql() creates a new table from records of the dataframe. Pass the table name and connection object inside this function. The column names of the table are same as the header of the CSV file. By default, the dataframe index is written as a column. Simply toggle the index parameter to False in order to remove this column. Additionally, the if_exists parameter specifies the behavior in case the table name is already being used. It can either raise error (fail), append new values or replace the existing table.
pandas.DataFrame.to_sql(table_name, connection_object, if_exists, index)
Check the table contents-
Create a cursor object and execute the standard SELECT statement to fetch the contents of the newly created table. 
Close connection
Csv file in use: stud_data.csv
Program:
Python3
# Import required librariesimport sqlite3import pandas as pd  # Connect to SQLite databaseconn = sqlite3.connect(r'C:\User\SQLite\University.db')  # Load CSV data into Pandas DataFramestud_data = pd.read_csv('stud_data.csv')# Write the data to a sqlite tablestud_data.to_sql('student', conn, if_exists='replace', index=False)  # Create a cursor objectcur = conn.cursor()# Fetch and display resultfor row in cur.execute('SELECT * FROM student'):    print(row)# Close connection to SQLite databaseconn.close()
Output:
Picked
python-csv
Python-database
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
C++ Program to Implement Wheel Sieve to Generate Prime Numbers Between Given Range

Wheel Sieve method is used to find prime number between a given range. Wheel factorization is a graphical method for manually performing a preliminary to the Sieve of Eratosthenes that separates prime numbers from composites.
In this method, Prime numbers in the innermost circle have their Multiples in similar positions as themselves in the other circles, forming spokes of primes and their multiples. Multiple of these prime numbers in the innermost circle form spokes of composite numbers in the outer circles.
Begin
   Define max number
   gen_sieve_primes()
   Declare c
   Assign c = 2
   For p = 2 to max number
      If prime[p]==0
         prime[p]=1
         Mul = p multiply c
      For Mul less than max number
         prime[Mul] = -1
         Increment c
         Mul = p multiply c
      Done
   Done
   Print_all_prime()
   Assign c=0
   For i = 0 to max number
      if (prime[i] == 1)
         Increment c
   If c less than 4
      Switch(c)
         Case 1
            Print 1st prime number
         Case 2
            Print 2nd prime number
         Case 3
            Print 3rd prime number
   Else
      Print nth prime number
End
#include <iostream>
using namespace std;
#define MAX_NUMBER 40
int prime[MAX_NUMBER];
void gen_sieve_prime(void) {
   for (int p = 2; p < MAX_NUMBER; p++) {
      if (prime[p] == 0)
         prime[p] = 1;
         int c = 2;
         int mul = p * c;
      for (; mul < MAX_NUMBER;) {
         prime[mul] = -1;
         c++;
         mul = p * c;
      }
   }
}
void print_all_prime() {
   int c = 0;
   for (int i = 0; i < MAX_NUMBER; i++) {
      if (prime[i] == 1) {
         c++;
         if (c < 4) {
            switch (c) {
               case 1:
                  cout << c << "st prime is: " << i << endl;
                  break;
               case 2:
                  cout << c << "nd prime is: " << i << endl;
                  break;
               case 3:
                  cout << c << "rd prime is: " << i << endl;
                  break;
              default:
              break;
           }
        }else
         cout << c << "th prime is: " << i << endl;
      }
   }
}
int main() {
   gen_sieve_prime();
   print_all_prime();
   return 0;
}
1st prime is: 2
2nd prime is: 3
3rd prime is: 5
4th prime is: 7
5th prime is: 11
6th prime is: 13
7th prime is: 17
8th prime is: 19
9th prime is: 23
10th prime is: 29
11th prime is: 31
12th prime is: 37
Python Forensics - Cracking an Encryption

In this chapter, we will learn about cracking a text data fetched during analysis and evidence.
A plain text in cryptography is some normal readable text, such as a message. A cipher text, on the other hand, is the output of an encryption algorithm fetched after you enter plain text.
Simple algorithm of how we turn a plain text message into a cipher text is the Caesar cipher, invented by Julius Caesar to keep the plain text secret from his enemies. This cipher involves shifting every letter in the message "forward" by three places in the alphabet.
Following is a demo illustration.
a → D
b → E
c → F
....
w → Z
x → A
y → B
z → C
A message entered when you run a Python script gives all the possibilities of characters, which is used for pattern evidence.
The types of pattern evidences used are as follows −
Tire Tracks and Marks
Impressions
Fingerprints
Every biometric data comprises of vector data, which we need to crack to gather full-proof evidence.
The following Python code shows how you can produce a cipher text from plain text −
import sys

def decrypt(k,cipher): 
   plaintext = '' 
   
   for each in cipher: 
      p = (ord(each)-k) % 126 
      
      if p < 32: 
         p+=95 
         plaintext += chr(p) 
         print plaintext 

def main(argv):
   if (len(sys.argv) != 1): 
      sys.exit('Usage: cracking.py') 
      cipher = raw_input('Enter message: ') 
      
      for i in range(1,95,1): 
         decrypt(i,cipher)
         
if __name__ == "__main__": 
   main(sys.argv[1:])
Now, check the output of this code. When we enter a simple text "Radhika", the program will produce the following cipher text.

    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
HTML - textarea Tag

The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML textarea Tag</title>
   </head>

   <body>
      <form action = "/cgi-bin/hello_get.cgi" method = "get">
         Fill the Detail: 
         <br />
         
         <textarea rows = "5" cols = "50" name = "description">
            Enter your name
         </textarea>
         
         <input type = "submit" value = "submit" />
      </form>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <textarea> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    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
Check if a String is not empty ("") and not null in Java

Let’s say we have the following string −
String myStr1 = "Jack Sparrow";
Let us check the string now whether it is not null or not empty.
if(myStr != null || myStr.length() != 0) {
System.out.println("String is not null or not empty");
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String myStr = "Jack Sparrow";
      boolean res;
      if(myStr != null || myStr.length() != 0) {
         System.out.println("String is not null or not empty");
      } else {
         System.out.println("String is null or empty");
      }
   }
}
String is not null or not empty
HTML strong Tag - GeeksforGeeks

17 Mar, 2022
The <strong> tag in HTML is the parsed tag and used to show the importance of the text. Make that text bold.
Syntax: 
<strong> Contents... </strong>
Example: 
HTML
<!DOCTYPE html><html>       <body>        <h1>GeeksforGeeks</h1>        <h2><strong> Tag</h2>        <!-- html strong tag used here -->        <strong>Welcome to geeksforGeeks!</strong>    </body>   </html>
Output:  
Example 2: Use CSS property to set bold font weight. 
HTML
<!DOCTYPE html><html>    <head>        <title>strong Tag</title>        <style>            body {                text-align:center;            }            h1 {                color:green;            }            .gfg {                font-weight:bold;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>font-weight: bold;</h2>        <div class = "gfg">Welcome to geeksforGeeks!</div>    </body></html>                   
Output:  
Supported Browsers: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Can you create an array of Generics type in Java?

Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.
 Live Demo
class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      std1.display();
      Student<String> std2 = new Student<String>("25");
      std2.display();
      Student<Integer> std3 = new Student<Integer>(25);
      std3.display();
   }
}
Value of age: 25.5
Value of age: 25
Value of age: 25
No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.
 Live Demo
class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float>[] std1 = new Student<Float>[5];
   }
}
GenericsExample.java:12: error: generic array creation
      Student<Float>[] std1 = new Student<Float>[5];
                              ^
1 error
How to check if remote ports are open using PowerShell?

Earlier days we were using telnet clients to check the remote port connectivity, in fact, we are still using it with cmd and PowerShell but this feature is not by default installed in OS and some companies have restrictions on installing new features including telnet.
We can leverage PowerShell to test remote port connectivity without installing telnet and with the use of the Test-NetConnection command. This command is also very useful for other diagnostics but we are focusing here for the remote port check.
To check if the remote port is open or not we can use the Test-NetConnection command and it requires -ComputerName parameter and -Port to check the remote port status.
Test-NetConnection -ComputerName Test1-Win2k12 -Port 80
ComputerName     : Test1-Win2k12
RemoteAddress    : 192.168.0.107
RemotePort       : 80
InterfaceAlias   : Ethernet0
SourceAddress    : 192.168.0.106
TcpTestSucceeded : True
The above example will check Port number 80 con
ectivity on remote server Test1-Win2k12. You can see that the TcpTestSucceeded property is true so the port is open. One more example shown below is WInRM https port 5986.
Test-NetConnection -ComputerName Test1-Win2k12 -Port 5986
WARNING: TCP connect to Test1-Win2k12:5986 failed
ComputerName           : Test1-Win2k12
RemoteAddress          : 192.168.0.107 RemotePort : 5986
InterfaceAlias         : Ethernet0
SourceAddress          : 192.168.0.106
PingSucceeded          : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded       : False
You can see that the WinRM SSL port is not open on the remote server and a warning message is displayed in the first line as well as in the TcpTestSucceeded property.
Fetching multiple MySQL rows based on a specific input within one of the table columns?

Let us first create a table −
mysql> create table DemoTable1528
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentSubject varchar(20)
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Chris','MongoDB');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Bob','MySQL');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('David','Java');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Carol','C');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Sam','Java');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Mike','Java');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Adam','MySQL');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1528;
This will produce the following output −
+-----------+-------------+----------------+
| StudentId | StudentName | StudentSubject |
+-----------+-------------+----------------+
|         1 | Chris       | MongoDB        |
|         2 | Bob         | MySQL          |
|         3 | David       | Java           |
|         4 | Carol       | C              |
|         5 | Sam         | Java           |
|         6 | Mike        | Java           |
|         7 | Adam        | MySQL          |
+-----------+-------------+----------------+
7 rows in set (0.00 sec)
Following is the query to fetch multiple MySQL rows based on a specific input within one of the table columns. Here, our specific input is “Java” −
mysql> select StudentId,StudentName,StudentSubject from DemoTable1528 where StudentSubject='Java';
This will produce the following output −
+-----------+-------------+----------------+
| StudentId | StudentName | StudentSubject |
+-----------+-------------+----------------+
|         3 | David       | Java           |
|         5 | Sam         | Java           |
|         6 | Mike        | Java           |
+-----------+-------------+----------------+
3 rows in set (0.00 sec)
How to return 2 values from a Java method

A method can give multiple values if we pass an object to the method and then modifies its values. See the example below −
public class Tester {
   public static void main(String[] args) {
      Model model = new Model();
      model.data1 = 1;
      model.data2 = 2;
      System.out.println(model.data1 + ", " + model.data2);
      changeValues(model);
      System.out.println(model.data1 + ", " + model.data2);
   }
   public static void changeValues(Model model) {
      model.data1 = 100;
      model.data2 = 200;
   }
}
class Model {
   int data1;
   int data2;
}
1, 2
100, 200
Different ways to access Instance Variable in Python - GeeksforGeeks

04 May, 2020
Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different.
There are two ways to access the instance variable of class:
Within the class by using self and object reference.
Using getattr() method
Example 1: Using Self and object reference
#creating classclass student:          # constructor    def __init__(self, name, rollno):                  # instance variable        self.name = name        self.rollno = rollno           def display(self):                  # using self to access         # variable inside class        print("hello my name is:", self.name)        print("my roll number is:", self.rollno)          # Driver Code# object createds = student('HARRY', 1001)  # function call through objects.display()  # accessing variable from # outside the classprint(s.name)
Output:
hello my name is: HARRY
my roll number is: 1001
HARRY
Example 2: Using getattr()
# Python code for accessing attributes of class class emp:     name='Harsh'    salary='25000'    def show(self):         print(self.name)        print(self.salary)          # Driver Codee1 = emp() # Use getattr instead of e1.name print(getattr(e1,'name'))    # returns true if object has attribute print(hasattr(e1,'name'))    # sets an  attribute  setattr(e1,'height',152)     # returns the value of attribute name height print(getattr(e1,'height'))    # delete the attribute delattr(emp,'salary') 
Output:
Harsh
True
152
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
Output of C programs | Set 42

29 Oct, 2021
QUE.1 What is the output of following program? 
C
#include <stdio.h>int main(){    int x = 10, *y, **z;      y = &x;    z = &y;    printf("%d %d %d", *y, **z, *(*z));    return 0;}
a. 10 10 10 b. 100xaa54f10 c. Run time error d. No Output 
Answer : a
Explanation: Because y contains the address of x so *y print 10 then **z contains address of y of x so print the value of x 10 and 3rd *(*z) contains address of y of x that’s why print 10. So, final output is 10 10 10.
QUE.2 What is the output of following program? 
C
#include <stdio.h>int main(){    // initialize the val=1    int val = 1;      do {        val++;        ++val;    } while (val++ > 25);    printf("%d\n", val);    return 0;}
a) 25 b) 50 c) 12 d) 4 
Answer : d
Explanation: Here, do while loop executes once and then it will check condition while will be false meanwhile value will be increased 3 times (two times in do while body and once while checking the condition); Hence value will be 4.
QUE.3 What is the output of following program in the text file?  
C
#include <stdio.h>int main(){    int a = 1, b = 2, c = 3;    char d = 0;    if (a, b, c, d) {        printf("enter in the if\n");    }    printf("not entered\n");    return 0;}
a) enter in the if b) not entered c) run time error d) segmentation fault 
Answer : b
Explanation: In this program, We are check the if condition all (a, b, c)>0 but d = 0 so condition is false didn’t enter in the if so print not entered.
QUE.4 What is the output of following program?  
C
#include <stdio.h>int main(){    char str[10] = "Hello";    printf("%d, %d\n", strlen(str), sizeof(str));    return 0;}
a) 5, 10 b) 10, 5 c) 10, 20 d) None of the mentioned 
Answer: a
Explanation: strlen gives length of the string that is 5; sizeof gives total number of occupied memory for a variable that is 8; since str is a pointer so sizeof(str) may be 2, 4 or 8. It depends on the computer architecture.
QUE.5 What is the output of following program?  
C
#include <stdio.h>int main(){    if (0)        ;    printf("Hello");    printf("Hi");    return 0;}
OPTION a) Hi b) HelloHi c) run time error d) None of the mentioned 
Answer : b
Explanation: There is a semicolon after the if statement, so this statement will be considered as a separate statement; and here printf(“Hello”); will not be associated with the if statement. Both printf statements will be executed.
This article is contributed by Ajay Puri(ajay0007). 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. 
varshagumber28
chhabradhanvi
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Assign range of elements to List

13 May, 2019
Assigning elements to list is a common problem and many varieties of it have been discussed in the previous articles. This particular article discusses the insertion of range of elements in the list. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using extend()This can be solved using the extend function in which the insertion of range of numbers can be done on the rear end using the range function.
# Python3 code to demonstrate# Assigning range of elements to List# using extend()  # initializing listtest_list = [3, 5, 6, 8]  # printing original listprint("The original list : " + str(test_list))  # using extend()# Assigning range of elements to Listtest_list.extend(range(6))  # print resultprint("The list after adding range elements : " + str(test_list))
The original list : [3, 5, 6, 8]
The list after adding range elements : [3, 5, 6, 8, 0, 1, 2, 3, 4, 5]

 
Method #2 Using * operatorThis problem can also be solved using the * operator and with the advantage of flexibility of addition of elements at any position.
# Python3 code to demonstrate# Assigning range of elements to List# using * operator  # initializing listtest_list = [3, 5, 6, 8]  # printing original listprint("The original list : " + str(test_list))  # using * operator# Assigning range of elements to Listres = [3, 5, *range(6), 6, 8]  # print resultprint("The list after adding range elements : " + str(res))
The original list : [3, 5, 6, 8]
The list after adding range elements : [3, 5, 0, 1, 2, 3, 4, 5, 6, 8]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Which collection classes are thread-safe in Java?

A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
The Stack class in Java implements the stack data structure that is based on the principle of LIFO. So, the Stack class can support many operations such as push, pop, peek, search, empty, etc.
import java.util.*;
public class StackTest {
   public static void main (String[] args) {
      Stack<Integer> stack = new Stack<Integer>();
      stack.push(5);
      stack.push(7);
      stack.push(9);
      Integer num1 = (Integer)stack.pop();
      System.out.println("The element popped is: " + num1);
      Integer num2 = (Integer)stack.peek();
      System.out.println(" The element on stack top is: " + num2);
   }
}
The element popped is: 9
The element on stack top is: 7
An array of objects that grow as required is implemented by the Vector class in Java. The Vector class can support the methods like add(), remove(), get(), elementAt(), size(), etc
import java.util.*;
public class VectorTest {
   public static void main(String[] arg) {
      Vector vector = new Vector();
      vector.add(9);
      vector.add(3);
      vector.add("ABC");
      vector.add(1);
      vector.add("DEF");
      System.out.println("The vector is: " + vector);
      vector.remove(1);
      System.out.println("The vector after an element is removed is: " + vector);
   }
}
The vector is: [9, 3, ABC, 1, DEF]
The vector after an element is removed is: [9, ABC, 1, DEF]
Find the frequency of a digit in a number using C++.

Here we will see how to get the frequency of a digit in a number. Suppose a number is like 12452321, the digit D = 2, then the frequency is 3.
To solve this problem, we take the last digit from the number, then check whether this is equal to d or not, if so then increase the counter, then reduce the number by dividing the number by 10. This process will be continued until the number is exhausted.
 Live Demo
#include<iostream>
using namespace std;
int countDigitInNum(long long number, int d) {
   int count = 0;
   while(number){
      if((number % 10) == d)
         count++;
      number /= 10;
   }
   return count;
}
int main () {
   long long num = 12452321;
   int d = 2;
   cout << "Frequency of " << 2 << " in " << num << " is: " << countDigitInNum(num, d);
}
Frequency of 2 in 12452321 is: 3
Lodash _.isNumeric() Method - GeeksforGeeks

30 Sep, 2020
The Lodash _.isNumeric() method checks whether the given value is a Numeric value or not and returns the corresponding boolean value. It can be a string containing a numeric value, exponential notation or a Number object, etc.
Syntax:
_.isNumeric( value );

Parameters: This method takes single parameter as mentioned above and described below:
value: Given value to be checked for Numeric value.
Return Value: This method returns a Boolean value true if the given value is Numeric, else false.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib.
Example 1:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   // Checking for _.isNumeric() methodconsole.log("The Value is Numeric : " + _.isNumeric(10000));    console.log("The Value is Negative : " + _.isNumeric(10.5));   console.log("The Value is Negative : " + _.isNumeric('G'));   console.log("The Value is Negative : " + _.isNumeric('Geeks'));
Output:
The Value is Numeric : true
The Value is Negative : true
The Value is Negative : false
The Value is Negative : false

Example 2:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   // Checking for _.isNumeric() methodconsole.log("The Value is Numeric : " + _.isNumeric([1,10]));    console.log("The Value is Negative : " + _.isNumeric("500"));   console.log("The Value is Negative : " + _.isNumeric({}));   console.log("The Value is Negative : " + _.isNumeric(null));
Output:
The Value is Numeric : false
The Value is Negative : true
The Value is Negative : false
The Value is Negative : false

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript