code-rag-bench/online-tutorials huggingface dataset:
How to push an array in MongoDB?

To push an array, use $push in MongoDB. Let us first create a collection with documents −
> db.demo399.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610339fac4d418a017856d")
}
> db.demo399.insertOne({Name:"David",Age:22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610341fac4d418a017856e")
}
> db.demo399.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610355fac4d418a017856f")
}
> db.demo399.insertOne({Name:"Bob",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e61035efac4d418a0178570")
}
> db.demo399.insertOne({Name:"David",Age:22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610364fac4d418a0178571")
}
Display all documents from a collection with the help of find() method −
> db.demo399.find();
This will produce the following output −
{ "_id" : ObjectId("5e610339fac4d418a017856d"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e610341fac4d418a017856e"), "Name" : "David", "Age" : 22 }
{ "_id" : ObjectId("5e610355fac4d418a017856f"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e61035efac4d418a0178570"), "Name" : "Bob", "Age" : 23 }
{ "_id" : ObjectId("5e610364fac4d418a0178571"), "Name" : "David", "Age" : 22 }
Following is the query to push an array −
> db.demo399.aggregate(
...    [
...       {
...          $group:
...          {
...             _id: null,
...             array: { $push: { Name: "$Name", Age: "$Age" } }
...          }
...       }
...    ]
... )
This will produce the following output −
{ "_id" : null, "array" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 }, { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 23 }, { "Name" : "David", "Age" : 22 } ] }
Check if a Java ArrayList contains a given item or not

The java.util.ArrayList.contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      if(aList.contains("C"))
         System.out.println("The element C is available in the ArrayList");
      else
         System.out.println("The element C is not available in the ArrayList");
      if(aList.contains("H"))
         System.out.println("The element H is available in the ArrayList");
      else
         System.out.println("The element H is not available in the ArrayList");
   }
}
The element C is available in the ArrayList
The element H is not available in the ArrayList
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “H” are available in the ArrayList. Then an if statement is used to print if they are available or not. A code snippet which demonstrates this is as follows −
List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");
if(aList.contains("C"))
   System.out.println("The element C is available in the ArrayList");
else
   System.out.println("The element C is not available in the ArrayList");
if(aList.contains("H"))
   System.out.println("The element H is available in the ArrayList");
else
   System.out.println("The element H is not available in the ArrayList");
JavaScript String - fontsize() Method

This method causes a string to be displayed in the specified size as if it were in a <font size = "size"> tag.
Its syntax is as follows −
string.fontsize( size )

size − An integer between 1 and 7, a string representing a signed integer between 1 and 7.
Returns the string with <font size="size"> tag.
Try the following example.
<html>
   <head>
      <title>JavaScript String fontsize() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String("Hello world");
         alert(str.fontsize( 3 ));
      </script>     
   </body>
</html>
<font size = "3">Hello world</font>


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to serialize and deserialize an object in Java?

The Serialization is a process of changing the state of an object into a byte stream, an object is said to be serializable if its class or parent classes implement either the Serializable or Externalizable interface and the Deserialization is a process of converting the serialized object back into a copy of an object.
During serialization, if we don’t want to write the state of a particular variable in a byte stream using a transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of a variable and stores a default value of that data type i.e. 0 for int,
0 for byte, 0.0 for float, etc. A Serialization of an object can be done through FileOutputStream and ObjectOutputStream class.
import java.io.*;
public class SerializationTest implements Serializable {
   int a = 1, b = 2;
   transient int c = 3;
   public static void main(String[] args) throws Exception {
      SerializationTest obj = new SerializationTest();
      // serialization
      FileOutputStream fos = new FileOutputStream("serialization.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
      // de-serialization
      FileInputStream fis = new FileInputStream("serialization.txt");
      ObjectInputStream ois = new ObjectInputStream(fis);
      SerializationTest test = (SerializationTest)ois.readObject();
      System.out.println("a = " + test.a);
      System.out.println("b = " + test.b);
      System.out.println("c = " + test.c);
   }
}
a = 1
b = 2
c = 0
MySQL error 1452 - Cannot add or a child row: a foreign key constraint fails

To understand error 1452, first we need to create a table and relate that to another table with
the help of a foreign key constraint.
Creating the first table −
mysql> CREATE table ForeignTable
-> (
-> id int,
-> name varchar(200),
-> Fk_pk int
-> );
Query OK, 0 rows affected (0.43 sec)
After creating the first table successfully, we will create the second table −
mysql> CREATE table primaryTable1
-> (
-> Fk_pk int,
-> DeptName varchar(200),
-> Primary key(Fk_pk)
-> );
Query OK, 0 rows affected (0.48 sec)
Now, we have created both tables. Then both the tables are related with the help of alter
command as well as adding foreign key constraint. The syntax is as follows −
alter table yourFirstTable add constraint anyConstraintName foreign key(column_name which is
acts foreign key in second table) yourSecondTable(column_name which acts primary key in
second table).
Now, the above query is used to relate both the tables. This is given as follows −
mysql> alter table ForeignTable add constraint constFKPK foreign key(Fk_pk) references
primaryTable1(Fk_pk);
Query OK, 0 rows affected (1.57 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now, both the tables are related. The records are inserted into the table ‘foreignTable’ as
follows −
mysql> INSERT into ForeignTable values(1,'John',1);

This results in an error that is shown in the below output −
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
(`business`.`foreigntable`, CONSTRAINT `constFKPK` FOREIGN KEY (`Fk_pk`)
REFERENCES `primarytable1` (`fk_pk`))
In the above output, we are getting the error ‘Cannot add or update a child row: a foreign key
constraint fails’. We can remove this error by inserting the records into the table primaryTable1
as shown below −
mysql> INSERT into primaryTable1 values(1,'ComputerScience');
Query OK, 1 row affected (0.14 sec)
After inserting the records into the table primaryTable1, we can insert the required records into
the table ForeignTable without any errors. This is shown below −
mysql> INSERT into ForeignTable values(1,'John',1);
Query OK, 1 row affected (0.13 sec)
Now, we can display the table records of ForeignTable with the help of the select command,
which is as follows −
mysql> SELECT * from ForeignTable;

The output of the above query is −
+------+------+-------+
| id   | name | Fk_pk |
+------+------+-------+
| 1    | John | 1     |
+------+------+-------+
1 row in set (0.00 sec)
We can also display the table records of primarytable1 with the help of the select command,
which is as follows −
mysql> SELECT * from primarytable1;

The output of the above query is −
+-------+-----------------+
| Fk_pk | DeptName        |
+-------+-----------------+
| 1     | ComputerScience |
+-------+-----------------+
1 row in set (0.00 sec)
The error 1452 - Cannot add or update a child row: a foreign key constraint fails occurs when data record is initially inserted into the ForeignTable.
Note: First, add the record into the second table i.e primarytable1 to avoid the above error.
Get the aggregated result and find the count of repeated values in different MongoDB
documents

To get the count of repeated values in different documents, use aggregate(). Let us create a collection with documents −
> db.demo452.insertOne({"StudentName":"John","StudentAge":21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e3371f552a0ebb0a6f3")
}
> db.demo452.insertOne({"StudentName":"John","StudentAge":22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e3671f552a0ebb0a6f4")
}
> db.demo452.insertOne({"StudentName":"John","StudentAge":23});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e3971f552a0ebb0a6f5")
}
> db.demo452.insertOne({"StudentName":"David","StudentAge":24});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e4371f552a0ebb0a6f6")
}
> db.demo452.insertOne({"StudentName":"David","StudentAge":25});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e4571f552a0ebb0a6f7")
}
Display all documents from a collection with the help of find() method −
> db.demo452.find();
This will produce the following output −
{ "_id" : ObjectId("5e7b7e3371f552a0ebb0a6f3"), "StudentName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5e7b7e3671f552a0ebb0a6f4"), "StudentName" : "John", "StudentAge" : 22 }
{ "_id" : ObjectId("5e7b7e3971f552a0ebb0a6f5"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5e7b7e4371f552a0ebb0a6f6"), "StudentName" : "David", "StudentAge" : 24}
{ "_id" : ObjectId("5e7b7e4571f552a0ebb0a6f7"), "StudentName" : "David", "StudentAge" : 25}
Following is the query to find the count of repeated values in different MongoDB documents −
> db.demo452.aggregate([
...    {$group: {_id:"$StudentName", count:{$sum:1}}},
...    {$sort: {count:-1}},
...
...    {$group: {_id:1, StudentName:{$push:{StudentName:"$_id", count:"$count"}}}},
...    {$project: {
...       first : {$arrayElemAt: ["$StudentName", 0]},
...       second: {$arrayElemAt: ["$StudentName", 1]},
...       others: {$slice:["$StudentName", 2, {$size: "$StudentName"}]}
...    }
... },
...
... {$project: {
...    status: [
...       "$first",
...       "$second",
...       {
...          StudentName: "New Student Name",
...          count: {$sum: "$others.count"}
...       }
...    ]
... }
... },
...
... {$unwind: "$status"},
... {$project: { _id:0, StudentName: "$status.StudentName", count: "$status.count" }}
... ])
This will produce the following output −
{ "StudentName" : "John", "count" : 3 }
{ "StudentName" : "David", "count" : 2 }
{ "StudentName" : "New Student Name", "count" : 0 }
Fast XML parsing using Expat in Python

Python allows XML data to be read and processed through its inbuilt module called expat. It is a non-validating XML parser. it creates an XML parser object and captures the attributes of its objects into various handler functions. In the below example we will see how the various handler functions can help us read the XML file as well as give the attribute values as the output data. This generated data can be used for the processing.
import xml.parsers.expat
# Capture the first element
def first_element(tag, attrs):
   print ('first element:', tag, attrs)
# Capture the last element
def last_element(tag):
   print ('last element:', tag)
# Capture the character Data
def character_value(value):
   print ('Character value:', repr(value))
parser_expat = xml.parsers.expat.ParserCreate()
parser_expat.StartElementHandler = first_element
parser_expat.EndElementHandler = last_element
parser_expat.CharacterDataHandler = character_value
parser_expat.Parse(""" <?xml version="1.0"?>
<parent student_rollno="15">
<child1 Student_name="Krishna"> Strive for progress, not perfection</child1>
<child2 student_name="vamsi"> There are no shortcuts to any place worth going</child2>
</parent>""", 1)
Running the above code gives us the following result −
first element: parent {'student_rollno': '15'}
Character value: '\n'
first element: child1 {'Student_name': 'Krishna'}
Character value: 'Strive for progress, not perfection'
last element: child1
Character value: '\n'
first element: child2 {'student_name': 'vamsi'}
Character value: ' There are no shortcuts to any place worth going'
last element: child2
Character value: '\n'
last element: parent
Highcharts - Column Chart using HTML Table

Following is an example of a Column Chart using HTML table.
We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. Let us now see additional configurations and also how we have added table under data.
An example of a Column Chart using the HTML table is given below.
The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or grid views.
A HTML table or the id of such is to be parsed as input data. The related options are startRow, endRow, startColumn and endColumn to delimit what part of the table is used.
data: {
   table: 'dataTable'  
}
highcharts_column_table.htm
<html>
   <head>
      <title>Highcharts Tutorial</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
      <script src = "https://code.highcharts.com/highcharts.js"></script> 
      <script src = "https://code.highcharts.com/modules/data.js"></script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
      <script language = "JavaScript">
         $(document).ready(function() {
            var data = {
               table: 'datatable'
            };
            var chart = {
               type: 'column'
            };
            var title = {
               text: 'Data extracted from a HTML table in the page'   
            };      
            var yAxis = {
               allowDecimals: false,
               title: {
                  text: 'Units'
               }
            };
            var tooltip = {
               formatter: function () {
                  return '<b>' + this.series.name + '</b><br/>' +
                     this.point.y + ' ' + this.point.name.toLowerCase();
               }
            };
            var credits = {
               enabled: false
            };  
            var json = {};   
            json.chart = chart; 
            json.title = title; 
            json.data = data;
            json.yAxis = yAxis;
            json.credits = credits;  
            json.tooltip = tooltip;  
            $('#container').highcharts(json);
         });
      </script>
      
      <table id = "datatable">
         <thead>
            <tr>
               <th></th>
               <th>Jane</th>
               <th>John</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <th>Apples</th>
               <td>3</td>
               <td>4</td>
            </tr>
            <tr>
               <th>Pears</th>
               <td>2</td>
               <td>0</td>
            </tr>
            <tr>
               <th>Plums</th>
               <td>5</td>
               <td>11</td>
            </tr>
            <tr>
               <th>Bananas</th>
               <td>1</td>
               <td>1</td>
            </tr>
            <tr>
               <th>Oranges</th>
               <td>2</td>
               <td>4</td>
            </tr>
         </tbody>
      </table>
   </body>
   
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Write a C program to find out the largest and smallest number in a series

Let the user enter four series of integers in the console, find out a number which is smallest and largest in a series
To calculate the small and large number, we use if conditions. The logic we use to find the largest and smallest number is −
if(minno>q) //checking 1st and 2nd number
   minno=q;
else if(maxno&l;q)
   maxno=q;
if(minno>r) //checking 1st and 3rd number
   minno=r;
 Live Demo
#include<stdio.h>
int main(){
   int minno,maxno,p,q,r,s;
   printf("enter any four numbers:");
   scanf("%d%d%d%d",&p,&q,&r,&s);
   minno=p;
   maxno=p;
   if(minno>q) //checking 1st and 2nd number
      minno=q;
   else if(maxno<q)
      maxno=q;
   if(minno>r) //checking 1st and 3rd number
      minno=r;
   else if(maxno<r)
      maxno=r;
   if(minno>s) //checking 1st and 4th number
      minno=s;
   else if(maxno<s)
      maxno=s;
   printf("Largest number from the given 4 numbers is:%d\n",maxno);
   printf("Smallest numbers from the given 4 numbers is:%d",minno);
   return 0;
}
enter any four numbers:34 78 23 12
Largest number from the given 4 numbers is:78
Smallest numbers from the given 4 numbers is:12
The below program finds the smallest and largest element in an array −
#include<stdio.h>
int main(){
   int a[50],i,num,large,small;
   printf("Enter the number of elements :");
   scanf("%d",&num);
   printf("Input the array elements :\n");
   for(i=0;i<num;++i)
      scanf("%d",&a[i]);
   large=small=a[0];
   for(i=1;i<num;++i){
      if(a[i]>large)
         large=a[i];
      if(a[i]<small)
         small=a[i];
   }
   printf("small= %d\n",small);
   printf("large= %d\n",large);
   return 0;
}
Enter the number of elements :8
Input the array elements :
1
2
6
4
8
9
3
9
small= 1
large= 9
Why do we use jQuery over JavaScript?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier. It will reduce the development time. Use it to add animation and even handling on your website.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is easier to use compared to JavaScript and its other JavaScript libraries. You need to write fewer lines of code while using jQuery, in comparison with JavaScript.
Let us see the following code snippet as an example of jQuery and JavaScript to change the background color:
function changeColor(color) {
   document.body.style.background = color;
}
Onload=”changeColor('blue');”
$ ('body') .css ('background', '#0000FF');

As shown above, both the code snippets are doing the same work of changing the background color. But jQuery takes less code and in this way you can work around other examples, which shows that jQuery minimizes the code and is easier to use.
HTML | <details> open Attribute - GeeksforGeeks

17 Oct, 2019
The HTML <details> open attribute is used to indicate whether the details will be display on page load. It is a boolean attribute. If this attribute is present then the detail will be visible.
Syntax:
<details open> Contents... </details>
Example: This example illustrates the use of open attribute in <details> element.
<!-- HTML program to illustrate details open Attribute -->  <!DOCTYPE html> <html>     <head>         <title>HTML details open Attribute</title>     </head>           <body>         <h1 style="text-align:center;">            GeeksForGeeks        </h1>                  <h2 style = "color: green; text-align: center;">             HTML <Details>open Attribute         </h2>                   <!-- Below details tag has "open" attribute -->        <details open>             <summary>Geeks classes</summary>                           <p>                 An extensive classroom programme to build                 and enhance Data Structures and Algorithm                 concepts.             </p>         </details>     </body> </html>                    
Output :
Supported Browsers: The browser supported by HTML <details> open attribute are listed below:
Google Chrome 12.0
Firefox 49.0
Safari 6.0
Opera 15.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubham_singh
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using HTML and JavaScript
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Print the corner elements and their sum in a 2-D matrix in C Program.

Given an array of size 2X2 and the challenge is to print the sum of all the corner elements stored in an array.
Assume a matrix mat[r][c], with some row “r” and column “c” starting row and column from 0, then its corner elements will be; mat[0][0], mat[0][c-1], mat[r-1][0], mat[r-1][c-1]. Now the task is to get these corner elements and sum those corner elements i.e., mat[0][0] + mat[0][c-1] + mat[r-1][0] + mat[r-1][c-1], and print the result on the screen.
Input: Enter the matrix elements :
   10 2 10
   2 3 4
   10 4 10
Output: sum of matrix is : 40
START
Step 1-> create macro for rows and column as #define row 3 and #define col 3
Step 2 -> main()
   Declare int sum=0 and array as a[row][col] and variables int i,j,n
   Loop For i=0 and i<3 and i++
      Loop For j=0 and j<3 and j++
         Input a[i][j]
      End
   End
   Print [0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1]
STOP
#include<stdio.h>
#define row 3
#define col 3
int main(){
   int sum=0,a[row][col],i,j,n;
   printf("Enter the matrix elements : ");
   for(i=0;i<3;i++){
      for(j=0;j<3;j++){
         scanf("%d",&a[i][j]);
      }
   }
   printf("sum of matrix is : %d",a[0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1] );
   return 0;
}
if we run above program then it will generate following output
Enter the matrix elements :
10 2 10
2 3 4
10 4 10
sum of matrix is : 40
MongoDB query to count the frequency of every element of the array

To count, you can also use aggregate() along with $sum. Let us create a collection with documents −
> db.demo184.insertOne({"Names":["Chris","David","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3999fb9e4f06af55199805")
}
> db.demo184.insertOne({"Names":["Chris","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399a0d9e4f06af55199806")
}
> db.demo184.insertOne({"Names":["Chris","Bob","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399a209e4f06af55199807")
}
Display all documents from a collection with the help of find() method −
> db.demo184.find();
This will produce the following output −
{ "_id" : ObjectId("5e3999fb9e4f06af55199805"), "Names" : [ "Chris", "David", "Bob" ] }
{ "_id" : ObjectId("5e399a0d9e4f06af55199806"), "Names" : [ "Chris", "Mike" ] }
{ "_id" : ObjectId("5e399a209e4f06af55199807"), "Names" : [ "Chris", "Bob", "Carol" ] }
Following is the query to count the frequency of every element −
> db.demo184.aggregate([
...   { "$unwind" : "$Names" },
...   { "$group": { "_id": "$Names", "count": { "$sum": 1} } },
...   { "$group": {
...      "_id": null,
...         "counts": {
...            "$push": {
...               "k": "$_id",
...               "v": "$count"
...            }
...         }
...      } },
...      { "$replaceRoot": {
...         "newRoot": { "$arrayToObject": "$counts" }
...   } }
...])
This will produce the following output −
{ "Carol" : 1, "David" : 1, "Chris" : 3, "Bob" : 2, "Mike" : 1 }
Valid Palindrome in Python

Suppose we have a string with alphanumeric values and symbols. There are lower case and uppercase letters as well. We have to check whether the string is forming a palindrome or not by considering only the lowercase letters (uppercases will be converted into lower case), other symbols like a comma, space will be ignored.
Suppose the string is like “A Man, a Plan, a Canal: Panama”, then by considering these rules, it will be “amanaplanacanalpanama”. This is a palindrome.
To solve this, follow these steps −
define x = “”
read each character c in str −if c is lowercase letter or number, then append c into xelse c is an uppercase letter, then simply convert it to lowercase and append after x
if c is lowercase letter or number, then append c into x
else c is an uppercase letter, then simply convert it to lowercase and append after x
if x is a palindrome, then return True, otherwise False
Let us see the implementation to get a better understanding
 Live Demo
class Solution(object):
   def isPalindrome(self, s):
      """
      :type s: str
      :rtype: bool
      """
      x = ""
      diff = ord('a') - ord('A')
      for i in s:
         if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"):
            x+=i
         elif ord(i)>=ord('A') and ord(i)<=ord('Z'):
            i = chr(diff+ord(i))
            x+=i
      #print(s)
      #print(x)
      return x == x[::-1]
ob1 = Solution()
print(ob1.isPalindrome("A Man, a Plan, a Canal: Panama"))
s = "A Man, a Plan, a Canal: Panama"
true
How to check total space and available space in Linux using the terminal?

In the Linux/Unix system to check storage details, we use the df command.
the df command is used to report file system disk space usage using the terminal in the Linux system. It displays total space, used space, and available space.
The general syntax of the df command is as follow:
$ df [OPTION]... [FILE]...
Brief description of options available in the df command.
To check space usage, we use the df command. By default, it is hard to understand the output of the df command.
$ df
The below snapshot is the output screen after the execution of the df command in the Linux system.
We can see that /dev/sda5 (root partition) 9736500 have total size 5813352 have used size and 3408844 have available size but what are these numbers? These numbers don’t have any units so we can’t understand.
Make it human readable there is an option available -h or --human-readable that makes it readable.
To display output in human readable format, we use -h or --human-readable option with the df command as shown in below.
$ df --human-readable
Or
$ df -h
After executing above command, it reports the disk space usage in human readable form then we can easily understand disk space usage.
To display output in powers of 1000, we use -H or --si option with the df command in the Linux system using terminal
$ df --si
Or
$ df -H
After executing above command, it reports the disk space usage in powers of 1000. Now we can easily understand disk space usage because we are more familiar with GB.
For more details about df command and check option description use below command.
$ df --help
And check the version information of df command use below command.
$ df --version
Firebase - Read Data

In this chapter, we will show you how to read Firebase data. The following image shows the data we want to read.
We can use the on() method to retrieve data. This method is taking the event type as "value" and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data.
Let us consider the following example.
var ref = firebase.database().ref();

ref.on("value", function(snapshot) {
   console.log(snapshot.val());
}, function (error) {
   console.log("Error: " + error.code);
});
If we run the following code, our console will show the data.
In our next chapter, we will explain other event types that you can use for reading data.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: link to stylesheet using relative url
Cypress - Test Runner

Cypress Test Runner helps to trigger the test execution. As we complete Cypress installation, there comes a suggestion from the tool on the terminal, as mentioned below −
You can open Cypress by running − node_modules/.bin/cypress open

To open the Test Runner, we have to run the below mentioned command −
node_modules/.bin/cypress open

The Test Runner window opens up after some time with the message that a sample project folder structure has been provided by Cypress under examples folder.
Click on the OK, got it! button. The screen that will appear on your computer would be as follows −
Then the Test Runner is launched, with the more than one spec files available under the examples folder, as stated below −
To run a specific file, for example, test2.spec.js, we have to click it. Also, the browser and the option to Stop the execution are available.
The execution shall begin with the following screen showing the test steps, name of test
case, test suite, URL, test duration, dimension of browser, and so on.

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
What is Binary Serialization and Deserialization in C# and how to achieve Binary Serialization in C#?

Converting an Object to a Binary format which is not in a human readable format is called Binary Serialization.
Converting back the binary format to human readable format is called deserialization?
To achieve binary serialization in C# we have to make use of library System.Runtime.Serialization.Formatters.Binary Assembly
Create an object of BinaryFormatter class and make use of serialize method inside the class
Serialize an Object to Binary
[Serializable]
public class Demo {
   public string ApplicationName { get; set; } = "Binary Serialize";
   public int ApplicationId { get; set; } = 1001;
}
class Program {
   static void Main()    {
      Demo sample = new Demo();
      FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(fileStream, sample);
      Console.ReadKey();
   }
}
ÿÿÿÿ
AConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ConsoleApp.Demo<ApplicationName>k__BackingField-<ApplicationId>k__BackingField Binary Serializeé
Converting back from Binary to Object
[Serializable]
public class Demo {
   public string ApplicationName { get; set; }
   public int ApplicationId { get; set; }
}
class Program {
   static void Main()    {
      FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat ", FileMode.Open);
      BinaryFormatter formatter = new BinaryFormatter();
      Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream);
      Console.WriteLine($"ApplicationName { deserializedSampledemo.ApplicationName} --- ApplicationId       { deserializedSampledemo.ApplicationId}");
      Console.ReadKey();
   }
}
ApplicationName Binary Serialize --- ApplicationId 1001
How to resolve the error that occurs while using a reserved word as a table or column name in MySQL?

This error occurs when you try to use a reserved word as a table or column name. It can occur due to −
Case 1: Whenever you use reserved word as a table name −
mysql> create table insert
−> (
−> Id int
−> );
The error is as follows −
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert
(
Id int
)' at line 1
The above error occurred because the word ‘insert’ is a keyword in MySQL.
Case 2 − Whenever you use reserved word as a column name in MySQL.
mysql> create table Customers
   −> (
   −> Add int
   −> );
The error is as follows −
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Add int
)' at line 3
The above error occurred because the column name ‘Add’ is a reserved word in MySQL.
To avoid the above error, you need to know about all the reserved words of MySQL
Some of the MySQL reserved words are as follows −
Insert
Add
Is
Key
Like etc.
The complete list of MySQL reserved keywords are as follows. This is the official website of MySQL − https://dev.mysql.com/doc/refman/5.7/en/keywords.html
Use a backtick with the reserved keyword to solve this issue.
Note - You cannot use a reserved keyword for table or column name. However, including them with backtick would be considered correct.
For Example −
create table `insert`
Demo of backtick with table as well as column name.
mysql> create table `Insert`
   −> (
   −> `Add` int
   −> );
Query OK, 0 rows affected (0.59 sec)
With the help of backtick, you will not get any error.
HTML novalidate Attribute

The HTML novalidate attribute define that while submitting the form the form data should not be validated in an HTML document.
Following is the syntax −
<form novalidate></form>
Let us see an example of HTML novalidate Attribute −
 Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
      text-align: center;
   }
   input[type='text'] {
      width: 300px;
      padding: 8px 16px;
      border: 2px solid #fff;
      background: transparent;
      border-radius: 20px;
      display: block;
      margin: 1rem auto;
      outline: none;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 20px;
      width: 330px;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   ::placeholder {
      color: #000;
   }
</style>
<body>
<h1>HTML novalidate attribute Demo</h1>
<form>
<input type="text" placeholder="Enter your name" required>
<input type="submit" value="Submit" class="btn" onclick='check()'>
</form>
<button type='button' class="btn" onclick="set()">Set No Validation</button>
<div class="show"></div>
<script>
   function set() {
      document.querySelector('form').setAttribute('novalidate', 'true');
   }
</script>
</body>
</html>
Try to click on “Submit” button without entering any name in the text field, it will produce a warning message −
Now click on “Set No Validation” button to set novalidate attribute on the form element and now try to submit the form without entering any name in the text field, this time it will easily get submitted without showing any warning message 
−
8086 program to convert 8 bit BCD number into ASCII Code - GeeksforGeeks

13 Jan, 2022
Problem – Write an assembly language program in 8086 microprocessor to convert 8 bit BCD number to its respective ASCII Code. 
Assumption – Starting address of program: 400 Input memory location: 2000 Output memory location: 3000 
Example : 
Input: 
DATA: 98H in memory location 2000

Output:
DATA: 38H in memory location 3000 and 
      39H in memory location 3001 
Algorithm – 
Load contents of memory location 2000 in register AL  Copy contents of register AL in register AH  Perform AND operation on register AL with 0F  Assign 04 to CL Register  Shift the contents of AH by executing SHR instruction using CL  Perform OR operation on register AX with 3030  Store the content of AX in memory location 3000  
Load contents of memory location 2000 in register AL  
Copy contents of register AL in register AH  
Perform AND operation on register AL with 0F  
Assign 04 to CL Register  
Shift the contents of AH by executing SHR instruction using CL  
Perform OR operation on register AX with 3030  
Store the content of AX in memory location 3000  
Program – 
Explanation – 
MOV AL, [2000]: loads contents of memory location 2000 in AL  MOV AH, AL: copy contents of AL in AH  AND AL, 0F: do AND operation on AL with 0F  MOV CL, 04 assign 04 to CL register  SHR AH, CL: shift the content of AH register right by 4 bits i.e. value of CL register  OR AX, 3030: do OR operation on AX with 3030  MOV [3000], AX: stores the content of AX register pair in 3000 memory address  HLT: stops executing the program
MOV AL, [2000]: loads contents of memory location 2000 in AL  
MOV AH, AL: copy contents of AL in AH  
AND AL, 0F: do AND operation on AL with 0F  
MOV CL, 04 assign 04 to CL register  
SHR AH, CL: shift the content of AH register right by 4 bits i.e. value of CL register  
OR AX, 3030: do OR operation on AX with 3030  
MOV [3000], AX: stores the content of AX register pair in 3000 memory address  
HLT: stops executing the program
gulshankumarar231
rkbhola5
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | Von Neumann architecture
Architecture of 8085 microprocessor
Interrupts
Difference between Von Neumann and Harvard Architecture
IEEE Standard 754 Floating Point Numbers
Pin diagram of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
C++ String Library - find_last_of

It searches the string for the last character that matches any of the characters specified in its arguments.
Following is the declaration for std::string::find_last_of.
size_t find_last_of (const string& str, size_t pos = npos) const;
size_t find_last_of (const string& str, size_t pos = npos) const noexcept;
size_t find_last_of (const string& str, size_t pos = npos) const noexcept;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::find_last_of.
#include <iostream>
#include <string>
#include <cstddef>
void SplitFilename (const std::string& str) {
   std::cout << "Splitting: " << str << '\n';
   std::size_t found = str.find_last_of("/\\");
   std::cout << " path: " << str.substr(0,found) << '\n';
   std::cout << " file: " << str.substr(found+1) << '\n';
}

int main () {
   std::string str1 ("/usr/bin/man");
   std::string str2 ("c:\\windows\\winhelp.exe");

   SplitFilename (str1);
   SplitFilename (str2);

   return 0;
}
 Print
 Add Notes
 Bookmark this page
Knock - Subdomain Scanner Tool in Kali Linux - GeeksforGeeks

18 Jul, 2021
Knock is a tool written in Python and is designed to enumerate subdomains in a target domain through a wordlist.
First clone the tool from the GitHub repository by using the below command.
git clone https://github.com/santiko/KnockPy.git
Then Change to your preferred directory.
cd KnockPy
Fig 1: Cloning tool from GitHub repository.
Run tool: To run the tool and to know its options, type the following command.
python knock.py -h
Fig 2: Options provided by Knock.
Show version: To show version of the tool, enter:
python knock.py -v
Fig 3: Version of knock.
Short information: To find out short information about any domain, enter:
python knock.py -i domain name (which in our case is google.com)
Fig 4: Short info about google.com
Resolve: To resolve domain name, type:
python knock.py -r google.com
Fig 5: Resolving domain google.com
Zone Transfer: To check if zone transfer is enabled or not, enter the following command.
python knock.py -z youtube.com
Fig 6: Checking zone transfer enabled or not.
Subdomains: To get the subdomain of a website, type the following command
python knock.py tesla.com
Fig 7: Getting subdomains.
As we can see from the image shown below, that knock found 48 subdomains in 12 hosts of tesla.com
Fig 8: subdomains
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Check if an integer can be expressed as a sum of two semi-primes in Python

Suppose we have a number n, we have to check whether n can be expressed as a sum of two semi-primes or not.
As we know the semi-prime is a number if it can be expressed as product of two primes number. First few semi-prime numbers are (1 - 100 range): 4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95.
So, if the input is like n = 108, then the output will be True as this is sum of 14 and 94 both are semi-prime.
To solve this, we will follow these steps −
MAX := 10000 assuming given inputs are sum of semi-primes which are in range 1 to 10000
nums := a new list
s_prime_flags := an array of size MAX and fill with False
Define a function get_semi_primes() . This will take
for i in range 2 to MAX - 1, docount := 0num := ij := 2while count < 2 and j^2 <= num, dowhile num is divisible by j, donum := num / jcount := count + 1j := j + 1if num > 1, thencount := count + 1if count is same as 2, thens_prime_flags[i] := True
count := 0
num := i
j := 2
while count < 2 and j^2 <= num, dowhile num is divisible by j, donum := num / jcount := count + 1j := j + 1
while num is divisible by j, donum := num / jcount := count + 1
num := num / j
count := count + 1
j := j + 1
if num > 1, thencount := count + 1
count := count + 1
if count is same as 2, thens_prime_flags[i] := True
s_prime_flags[i] := True
insert i at the end of nums
From the main method do the following −
call get_semi_primes()
i := 0
while nums[i] <= quotient of (n / 2), doif s_prime_flags[n - nums[i]] is True, thenreturn Truei := i + 1
if s_prime_flags[n - nums[i]] is True, thenreturn True
return True
i := i + 1
return False
Let us see the following implementation to get better understanding −
 Live Demo
MAX = 10000
nums = []
s_prime_flags = [False] * MAX
def get_semi_primes():
   for i in range(2, MAX):
      count = 0
      num = i
      j = 2
      while count < 2 and j * j <= num:
         while num % j == 0:
            num /= j
            count += 1
      j += 1
      if num > 1:
         count += 1
      if count == 2:
         s_prime_flags[i] = True
         nums.append(i)
def solve(n):
   get_semi_primes()
   i = 0
   while nums[i] <= n // 2:
      if s_prime_flags[n - nums[i]] == True:
         return True
      i += 1
   return False
n = 108
print(solve(n))
[4, 2, 3], 11
True
Replace null values with default value in Java Map

To replace null values with default value in Java Map, the code is as follows −
 Live Demo
import java.util.*;
import java.util.stream.*;
public class Demo{
   public static <T, K> Map<K, T> null_vals(Map<K, T> my_map, T def_val){
      my_map = my_map.entrySet().stream().map(entry -> {
         if (entry.getValue() == null)
         entry.setValue(def_val);
         return entry;
      })
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
      return my_map;
   }
   public static void main(String[] args){
      Map<Integer, Integer> my_map = new HashMap<>();
      my_map.put(1, null);
      my_map.put(2, 56);
      my_map.put(3, null);
      my_map.put(4, 99);
      int defaultValue = 0;
      System.out.println("The map with null values is : "+ my_map);
      my_map = null_vals(my_map, defaultValue);
      System.out.println("The map with null values replaced is : " + my_map);
   }
}
The map with null values is : {1=null, 2=56, 3=null, 4=99}
The map with null values replaced is : {1=0, 2=56, 3=0, 4=99}
A class named Demo contains a function named ‘null_vals’ that checks for null values in an array and replaces them with a default value that is previously defined. In the main function, a Map instance is created and elements are pushed into it using the ‘put’ function. The ‘null_vals’ function is called on this map and the null values are replaced with a default value.
Calendar getTime() Method in Java with Examples - GeeksforGeeks

24 Jun, 2021
The getTime() method in Calendar class is used to return an object resembling the Date that is represented by this Calendar’s time value.Syntax:  
public final Date getTime()
Parameters: The method does not take any parameters.Return Value: The method returns the Date, represented by this Calendar.Below programs illustrate the working of getTime() Method of Calendar class: Example 1:  
Java
// Java code to illustrate// getTime() method import java.util.*; public class Calendar_Demo {     public static void main(String args[])        throws InterruptedException    {         // Creating a calendar        Calendar calndr1            = Calendar.getInstance();         // Displaying the current time        System.out.println("The Current"                           + " Time is: "                           + calndr1.getTime());         // Adding few delay        Thread.sleep(10000);         // Creating another calendar        Calendar calndr2 = Calendar.getInstance();         // Displaying the upcoming time        Date dt = calndr2.getTime();        System.out.println("The upcoming"                           + " time is: " + dt);    }}
The Current Time is: Wed Feb 20 14:40:37 UTC 2019
The upcoming time is: Wed Feb 20 14:40:47 UTC 2019
 
Example 2:  
Java
// Java code to illustrate// getTime() method import java.util.*; public class Calendar_Demo {     public static void main(String args[])        throws InterruptedException    {         // Creating a calendar        Calendar calndr1            = Calendar.getInstance();         // Displaying the current time        System.out.println("The Current"                           + " Time is: "                           + calndr1.getTime());         // Adding few delay        Thread.sleep(5000);         // Creating another calendar        Calendar calndr2 = Calendar.getInstance();         // Displaying the upcoming time        Date dt = calndr2.getTime();        System.out.println("The upcoming"                           + " time is: " + dt);    }}
The Current Time is: Wed Feb 20 14:40:50 UTC 2019
The upcoming time is: Wed Feb 20 14:40:55 UTC 2019
 
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getMaximum-int- 
adnanirshad158
Java - util package
Java-Calendar
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Collections in Java