code-rag-bench/online-tutorials huggingface dataset:
How to delete Session data in JSP?

When you are done with a user's session data, you have several options −
Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the particular key.
Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the particular key.
Delete the whole session − You can call the public void invalidate() method to discard an entire session.
Delete the whole session − You can call the public void invalidate() method to discard an entire session.
Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration − If you are using Tomcat, apart from the above-mentioned methods, you can configure the session time out in web.xml file as follows.
web.xml Configuration − If you are using Tomcat, apart from the above-mentioned methods, you can configure the session time out in web.xml file as follows.
<session-config>
   <session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.
Group by day/month/week based on the date range in MongoDB

To group, use weekandmonth in MongoDB. Let us create a collection with documents −
> db.demo133.insertOne({"Rank":18,"DueDate":new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31980968e7f832db1a7f78")
}
> db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31982568e7f832db1a7f79")
}
> db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-02-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31986568e7f832db1a7f7a")
}
> db.demo133.insertOne({"Rank":20,"DueDate":new ISODate("2020-02-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31986c68e7f832db1a7f7b")
}
Display all documents from a collection with the help of find() method −
> db.demo133.find();
This will produce the following output −
{ "_id" : ObjectId("5e31980968e7f832db1a7f78"), "Rank" : 18, "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e31982568e7f832db1a7f79"), "Rank" : 12, "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e31986568e7f832db1a7f7a"), "Rank" : 12, "DueDate" : ISODate("2020-02-01T00:00:00Z") }
{ "_id" : ObjectId("5e31986c68e7f832db1a7f7b"), "Rank" : 20, "DueDate" : ISODate("2020-02-01T00:00:00Z") }
Following is the query to group by day/month/week based on the date range −
> db.demo133.aggregate([
...    {
...       "$project": {
...          "DueDateWeek": { "$week": "$DueDate" },
...          "DueDateMonth": { "$month": "$DueDate" },
...          "Rank": 1
...       }
...    },
... {
...    "$group": {
...       "_id": "$DueDateWeek",
...       "AvgValue": { "$avg": "$Rank" },
...       "MonthValue": { "$first": "$DueDateMonth" }
...       }
...    }
... ])
This will produce the following output −
{ "_id" : 4, "AvgValue" : 16, "MonthValue" : 2 }
{ "_id" : 1, "AvgValue" : 15, "MonthValue" : 1 }
Style Bootstrap 4 card with bg-warning class

Use the bg-warning class with the card class in Bootstrap to set warning action on a Bootstrap card.
Set warning messages like −
Do not cross!
High Voltage!
Use the below code to style a Bootstrap card −
<div class="card bg-warning">
  <div class="card-body">You are trespassing on private property!</div>
</div>
You can try to run the following code to style Bootstrap card with the bg-warning class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>
<body>
  <div class="container">
    <h3>Warning</h3>
    <div class="card bg-warning">
      <div class="card-body">You are trespassing on private property!</div>
    </div>
  </div>
</body>
</html>
Tasks in C#

Task represents an asynchronous operation in C#. The following states how you can start a task in C#.
Use a delegate to start a task.
Task t = new Task(delegate { PrintMessage(); });
t.Start();
Use Task Factory to start a task.
Task.Factory.StartNew(() => {Console.WriteLine("Welcome!"); });
You can also use Lambda.
Task t = new Task( () => PrintMessage() );
t.Start();
The most basic way to start a task is using the run().
using System;
using System.Threading.Tasks;

public class Example {
   public static void Main() {
      Task task = Task.Run( () => {
         int a = 0;
         for (a = 0; a <= 1000; a++){}
         Console.WriteLine("{0} loop iterations ends",a);
      } );
      task.Wait();
   }
}
JavaScript Trigger a button on ENTER key

To trigger a button on ENTER key, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,
   .result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Trigger a button on ENTER key</h1>
Enter text<input type="text" class="sample" />
<button class="Btn">CLICK HERE</button>
<div class="result"></div>
<h3>
Press enter in the above text field to trigger the button
</h3>
<script>
   let resultEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   sampleEle.addEventListener("keyup", (event) => {
      if (event.keyCode === 13) {
         event.preventDefault();
         document.querySelector(".Btn").click();
      }
   });
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML ="Button has been clicked and text = " + sampleEle.value;
   });
</script>
</body>
</html>
On entering some text and pressing enter key in the input field −
C - Variable Arguments

Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function.
int func(int, ... ) {
   .
   .
   .
}

int main() {
   func(1, 2, 3);
   func(1, 2, 3, 4);
}
It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed. To use such functionality, you need to make use of stdarg.h header file which provides the functions and macros to implement the functionality of variable arguments and follow the given steps −
Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments.
Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments.
Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.
Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.
Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.
Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.
Use va_arg macro and va_list variable to access each item in argument list.
Use va_arg macro and va_list variable to access each item in argument list.
Use a macro va_end to clean up the memory assigned to va_list variable.
Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take the variable number of parameters and return their average −
#include <stdio.h>
#include <stdarg.h>

double average(int num,...) {

   va_list valist;
   double sum = 0.0;
   int i;

   /* initialize valist for num number of arguments */
   va_start(valist, num);

   /* access all the arguments assigned to valist */
   for (i = 0; i < num; i++) {
      sum += va_arg(valist, int);
   }
	
   /* clean memory reserved for valist */
   va_end(valist);

   return sum/num;
}

int main() {
   printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
   printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
When the above code is compiled and executed, it produces the following result. It should be noted that the function average() has been called twice and each time the first argument represents the total number of variable arguments being passed. Only ellipses will be used to pass variable number of arguments.
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000

 Print
 Add Notes
 Bookmark this page
Create a new Django project in Pycharm using Pycharm Terminal - GeeksforGeeks

20 Aug, 2021
PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides many useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development mainly in Python.
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. It is very scalable. 
Let’s Start Creating a new Django Project in PyCharm using Pycharm Terminal.
Step By Step Implementation
Step 1: Open Your PyCharm and Click on Create New Project.
Step 2: Select Your Directory and then give a name to your project and then Click on Create.
Step 3 : Then Check if Django is installed or not in your Computer.
Type the following Command in pycharm Terminal located at Bottom Left.:
python -m django --version
 If it is Already installed then you will see the Django version installed in Your Computer. If not Then You can refer to Django Introduction and Installation.
Step 4: Start a project by using following command-
django-admin startproject firstproject
Step 5: Change directory to firstproject.
cd firstproject
Step 6: Start the server by typing following command in cmd–
python manage.py runserver
After You Click on the given Url (http://127.0.0.1:8000/) . You Will See your Development Server as shown in Below Image.
clintra
Project
Python
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Swing | Simple User Registration Form
Face Detection using Python and OpenCV with webcam
Snake Game in C
Simple registration form using Python Tkinter
Program for Employee Management System
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
What is the use of the '&' symbol in C++?

The & symbol is used as an operator in C++. It is used in 2 different places, one as a bitwise and operator and one as a pointer address of operator.
The bitwise AND operator (&) compares each bit of the first operand to that bit of the second operand. If both bits are 1, the bit is set to 1. Otherwise, the bit is set to 0. Both operands to the bitwise AND operator must be of integral types. 
#include <iostream>  
using namespace std;
 
int main() {  
   unsigned short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xAAAA;      // pattern 1010 ...  

   cout << hex << ( a & b ) << endl;
}
This gives the output −
0
C++ provides two-pointer operators, which are Address of Operator (&) and Indirection Operator (*).
A pointer is a variable that contains the address of another variable or you can say that a variable that contains the address of another variable is said to "point to" the other variable. A variable can be any data type including an object, structure or again pointer itself.
The address of Operator (&), and it is the complement of *. It is a unary operator that returns the address of the variable(r-value) specified by its operand. For example,
#include <iostream>
using namespace std;

int main () {
   int  var;
   int  *ptr;
   int  val;

   var = 3000;

   // take the address of var
   ptr = &var;

   // take the value available at ptr
   val = *ptr;
   cout << "Value of var :" << var << endl;
   cout << "Value of ptr :" << ptr << endl;
   cout << "Value of val :" << val << endl;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var :3000
Value of ptr :0xbff64494
Value of val :3000
C Program to build DFA accepting the languages ending with “01”

Design deterministic finite automata (DFA) with ∑ = {0, 1} that accepts the languages ending with “01” over the characters {0, 1}.
The strings that are generated for a given language are as follows −
L={01,001,101,110001,1001,..........}
The minimum length of the string is 2, the number of states that the DFA consists of for the given language is: 2+1 = 3 states.
Here,
q0 − On input 0 it goes to state q1 and on input 1 it goes to itself.
q0 − On input 0 it goes to state q1 and on input 1 it goes to itself.
q1 − On input 0 it goes to itself and on input 1 it goes to State q2.
q1 − On input 0 it goes to itself and on input 1 it goes to State q2.
q2 − On input 0 it goes to State q1 and on input 1 goes to State q0. State to q2 is the final state.
q2 − On input 0 it goes to State q1 and on input 1 goes to State q0. State to q2 is the final state.
Following is the C program to construct a DFA with ∑ = {0, 1} that accepts the languages ending with “01” over the characters {0, 1} -
 Live Demo
#include
#define max 100
main() {
   char str[max],f='a';
   int i;
   printf("enter the string to be checked: ");
   scanf("%s",str);
   for(i=0;str[i]!='\0';i++) {
      switch(f) {
         case 'a': if(str[i]=='0') f='b';
            else if(str[i]=='1') f='a';
         break;
         case 'b': if(str[i]=='0') f='b';
            else if(str[i]=='1') f='c';
         break;
         case 'c': if(str[i]=='0') f='b';
            else if(str[i]=='1') f='a';
         break;
      }
   }
   if(f=='c')
      printf("\nString is accepted", f);
   else printf("\nString is not accepted", f);
      return 0;
}
The output is as follows −
Run 1:
enter the string to be checked: 10101001
String is accepted.
Run 2:
enter the string to be checked: 10000010
String is not accepted.
The best data type to store 0, 1, null values in MySQL?

You need to use tinyint(1) unsigned NULL to store the value 0,1 and null values. The syntax is as follows −
yourColumnName TINYINT(1) UNSIGNED NULL;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table StoreValue0and1orNULLDemo
   -> (
   -> isDigit TINYINT(1) UNSIGNED NULL
   -> );
Query OK, 0 rows affected (0.63 sec)
Now you can insert records 0,1, and NULL in the table using insert command. The query is as follows −
mysql> insert into StoreValue0and1orNULLDemo values(0);
Query OK, 1 row affected (0.18 sec)
mysql> insert into StoreValue0and1orNULLDemo values(1);
Query OK, 1 row affected (0.18 sec)
mysql> insert into StoreValue0and1orNULLDemo values(NULL);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from StoreValue0and1orNULLDemo;
The following is the output −
+---------+
| isDigit |
+---------+
|       0 |
|       1 |
|    NULL |
+---------+
3 rows in set (0.00 sec)
Weka - File Formats

WEKA supports a large number of file formats for the data. Here is the complete list −
arff
arff.gz
bsi
csv
dat
data
json
json.gz
libsvm
m
names
xrff
xrff.gz
The types of files that it supports are listed in the drop-down list box at the bottom of the screen. This is shown in the screenshot given below.
As you would notice it supports several formats including CSV and JSON. The default file type is Arff.
An Arff file contains two sections - header and data.
The header describes the attribute types.
The data section contains a comma separated list of data.
As an example for Arff format, the Weather data file loaded from the WEKA sample databases is shown below −
From the screenshot, you can infer the following points −
The @relation tag defines the name of the database.
The @relation tag defines the name of the database.
The @attribute tag defines the attributes.
The @attribute tag defines the attributes.
The @data tag starts the list of data rows each containing the comma separated fields.
The @data tag starts the list of data rows each containing the comma separated fields.
The attributes can take nominal values as in the case of outlook shown here −
The attributes can take nominal values as in the case of outlook shown here −
@attribute outlook (sunny, overcast, rainy)

The attributes can take real values as in this case −
The attributes can take real values as in this case −
@attribute temperature real

You can also set a Target or a Class variable called play as shown here −
You can also set a Target or a Class variable called play as shown here −
@attribute play (yes, no)

The Target assumes two nominal values yes or no.
The Target assumes two nominal values yes or no.
The Explorer can load the data in any of the earlier mentioned formats. As arff is the preferred format in WEKA, you may load the data from any format and save it to arff format for later use. After preprocessing the data, just save it to arff format for further analysis.
Now that you have learned how to load data into WEKA, in the next chapter, you will learn how to preprocess the data.

    6 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy
 Print
 Add Notes
 Bookmark this page
How to Use Particles.js in React Project ? - GeeksforGeeks

31 Jan, 2020
Particles.js is a dependency-free, light-weighted and responsive JavaScript plugin for flexible and reactive particles like design which looks like this.
We can add Particles.js in our react project by using react-particles. Adding this to your react project will surely attract more audiences.
1. Installation Process: Run the following command on terminal to install Particles.js
For npm:npm install react-particles-js
npm install react-particles-js
For yarn:yarn add react-particles-js
yarn add react-particles-js
2. Import the packages: Import the package in your file. To import the package paste the following code:
import Particles from 'react-particles-js';
3. Render: Inside return of render function of your component add the element <particles />. Some important props are:
width: Width of Canvas.
Height: Height of Canvas.
Params: Parameter to be passed.
Example:
// Complete React Codeimport React from 'react';import './App.css';import Particles from 'react-particles-js';   function App() {  return (    <div className="App">      By Ankit Bansal      <Particles        params={{          particles: {            number: {              value: 200,              density: {                enable: true,                value_area: 1000,              }            },          },        }}      />       </div>  );}   export default App;
4. Start Start the npm by using npm start command and you will get a great attractive background.
Note: Add <particles /> element as the last element in your returning div.
react-js
Technical Scripter 2019
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
File uploading in React.js
Python Mongodb - Delete_many() - GeeksforGeeks

10 May, 2020
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditional table model.
Delete_many() is used when one needs to delete more than one document. A query object containing which document to be deleted is created and is passed as the first parameter to the delete_many().
Sample Database:
Example 1: Deleting all the documents where the name starts with ‘A’.
import pymongo    client = pymongo.MongoClient("mongodb://localhost:27017/")  # Connecting to the databasemydb = client["GFG"]  # Connecting the to collectioncol = mydb["Geeks"]  query = {"Name": {"$regex": "^A"}}d = col.delete_many(query)  print(d.deleted_count, " documents deleted !!")
Output:
2  documents deleted !!

MongoDB Shell:
Example 2:
import pymongo    client = pymongo.MongoClient("mongodb://localhost:27017/")  # Connecting to the databasemydb = client["GFG"]  # Connecting the to collectioncol = mydb["Geeks"]  query = {"Class": '3'}d = col.delete_many(query)  print(d.deleted_count, " documents deleted !!")
Output:
1  documents deleted !!

MongoDB Shell:
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Text transliteration from English to Indian languages - Using indic-transliteration - GeeksforGeeks

08 Jun, 2020
Transliteration is the process of transferring a word from the alphabet of one language to another. Transliteration helps people pronounce words and names in foreign languages. It is also useful for non-Latin script language speakers to use in their own language, as typing in Latin is more convenient.
Examples :
Input : namaskaara
Output : 
Transliterating from English(Latin) to Hindi(Devanagari)

Input : namaskaara
Output : 
Transliterating from English(Latin) to Telugu(Telugu)

To implement transliteration of Latin to Indian scripts we will use the indic-transliteration module.
Installation :
pip install indic-transliteration
We will use the transliterate() method of the sanscript class of the indic-transliteration module.
Syntax : transliterate(text, romanization_style, script)
Parameters :test : The text totransliteratedromanization_style : The following romanization styles are available :
HK = ‘hk’
IAST = ‘iast’
ITRANS = ‘itrans’
OPTITRANS = ‘optitrans’
KOLKATA = ‘kolkata’
SLP1 = ‘slp1’
VELTHUIS = ‘velthuis’
WX = ‘wx’
script : The script to be transliterated into. The following scripts are available :
Bengali
Devanagari
Gujarati
Kannada
Malayalam
Telugu
Tamil
Oriya
Gurmukhi/ Punjabi/ Panjabi
Returns : A string of the transliterated text.
Example 1:Transliterating from Latin to Devanagari.
# import the modulefrom indic_transliteration import sanscriptfrom indic_transliteration.sanscript import transliterate  # the text to be transliteratedtext = "Apa sabhii kaa yahaan svaagat hai."  # printing the transliterated textprint(transliterate(text, sanscript.ITRANS, sanscript.DEVANAGARI))
Output :
Example 2:Transliterating from Latin to Gujarati.
# import the modulefrom indic_transliteration import sanscriptfrom indic_transliteration.sanscript import transliterate  # the text to be transliteratedtext = "Suprabhaata"  # printing the transliterated textprint(transliterate(text, sanscript.IAST, sanscript.GUJARATI))
Output :
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
XML | Elements - GeeksforGeeks

27 Sep, 2018
The XML elements are the basic building block of the XML document. It is used as a container to store text elements, attributes, media objects etc. Every XML documents contain at least one element whose scopes are delimited by start and end tags or in case of empty elements it is delimited by an empty tag.
Syntax:
<element-name attributes> Contents...</element-name>
element-name: It is the name of element.
attributes: The attributes are used to define the XML element property and these attributes are separated by white space. It associates the name with a value, which is a string of characters.
Example:
name="Geeks"
Here, Geeks represents the value of attribute

Rules to define XML elements: There are some rules to create XML elements which are given below:
An element an contain alphanumeric values or characters. But only three special characters are required in the names these are hyphen, underscore and period.
Names are case sensitive. It means lower case letters have different meaning and upper case characters have different meaning. For example address, Address, aDDress are different names.
Both start and end tags for elements need to be same.
An element, which is a container, can contain text or elements
Empty Elements: An element in XML document which does not contains the content is known as Empty Element. The basic syntax of empty element in XML as follows:
<elements-name attributename/>
Example 1: Following is the example of an XML document describing the address of a college student using XML elements.
<?xml version = “1.0”?><contactinfo>    <address category = “college”>        <name>G4G</name>        <College>Geeksforgeeks</College>        <mobile>2345456767</mobile>    </address></contactinfo>
Output:
      G4G
      Geeksforgeeks
      2345456767

Example 2:
<?xml version = "1.0"?><student>    <_personal_details = "Personal Details">        <name>xyz</name>        <father_name>abc</father_name>    </personal_details>    <edu_details = "Educational Details">        <hsc_perc>80%</hsc_perc>        <ssc_perc>98%</ssc_perc>    </edu_details></student>
Output:
      xyz 
      abc
      80%
      98%
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML and XML
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
How to execute PHP code using command line ?
matplotlib.axes.Axes.use_sticky_edges() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.use_sticky_edges() function in axes module of matplotlib library is used whether to obey all Artist.sticky_edges.
Syntax:
Axes.use_sticky_edges

Below examples illustrate the matplotlib.axes.Axes.use_sticky_edges() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function  import numpy as npimport matplotlib.pyplot as plt  y, x = np.mgrid[:6, 1:6]poly_coords = [    (0.25, 2.75), (3.25, 2.75),    (2.25, 0.75), (0.25, 0.75)]fig, ax = plt.subplots()  ax.use_sticky_edges = False  ax.pcolor(x, y, y + 20 * x, cmap ='Greens')  ax.margins(x = 0.1, y = 0.05)ax.set_aspect('equal')  fig.suptitle('matplotlib.axes.Axes.use_sticky_edges() \function Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib function  import numpy as npimport matplotlib.pyplot as plt  y, x = np.mgrid[:6, 1:6]poly_coords = [    (0.25, 2.75), (3.25, 2.75),    (2.25, 0.75), (0.25, 0.75)]fig, (ax1, ax2) = plt.subplots(nrows = 2)  ax2.use_sticky_edges = False  for ax, status in zip((ax1, ax2),                       ('Is', 'Is Not')):          # sticky    cells = ax.pcolor(x, y, x + y,                       cmap ='PuBuGn')    ax.add_patch(        plt.Polygon(poly_coords, color ='green',                    alpha = 0.5)    )  # not sticky    ax.margins(x = 0.1, y = 0.05)    ax.set_aspect('equal')    ax.set_title('use_sticky_edges() function {} used'.format(status),                  fontweight ="bold")  fig.suptitle('matplotlib.axes.Axes.use_sticky_edges() function \Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Output of Python Program | Set 4 - GeeksforGeeks

16 May, 2020
Difficulty level : IntermediatePredict the output of the following Python Programs.
Program 1:
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']  print nameList[1][-1]
Output:
k

Explanation:The index position -1 represents either the last element in a list or the last character in a String. In the above given list of names “nameList”, the index 1 represents the second element i.e, the second string “Pratik” and the index -1 represents the last character in the string “Pratik”. So, the output is “k”.
 
Program 2:
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']  pos = nameList.index("GeeksforGeeks")  print pos * 5 
Output:
An Exception is thrown, ValueError: 'GeeksforGeeks' is not in list  

Explanation:The task of the index is to find the position of a supplied value in a given list. In the above program the supplied value is “GeeksforGeeks” and the list is nameList. As GeeksforGeeks is not present in the list, an exception is thrown.
 
Program 3:
geekCodes = [1, 2, 3, 4]  # List will look like as [1,2,3,4,[5,6,7,8]]geekCodes.append([5,6,7,8])print len(geekCodes)    print(geekCodes)#new list will be appended at the index 4 of geekCodes.
Output:
5
[1,2,3,4,[5,6,7,8]]

Explanation:The task of append() method is to append a passed obj into an existing list. But instead of passing a list to the append method will not merge the two lists, the entire list which is passed is added as an element of the list. So the output is 5.
 
Program 4:
def addToList(listcontainer):    listcontainer += [10]  mylistContainer = [10, 20, 30, 40]addToList(mylistContainer)print len(mylistContainer)
Output:
5

Explanation:In Python, everything is a reference, and references are passed by value. Parameter passing in Python is the same as reference passing in Java. As a consequence, the function can modify the value referred by passed argument, i.e. the value of the variable in the caller’s scope can be changed. Here the task of the function “addToList” is to add an element 10 in the list, So this will increase the length of the list by 1. So the output of the program is 5.
This article is contributed by Pratik Agarwal. 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.
chaudhary_19
umangsharma9533
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Output of Java program | Set 28
Runtime Errors
Output of Java program | Set 5
Output of Java Programs | Set 12
Difference between require() and include() in PHP - GeeksforGeeks

11 Jan, 2022
PHP require() Function: The require() function in PHP is basically used to include the contents/code/data of one PHP file to another PHP file. During this process if there are any kind of errors then this require() function will pop up a warning along with a fatal error and it will immediately stop the execution of the script. In order to use this require() function, we will first need to create two PHP files. Using the include() function, include one PHP file into another one. After that, you will see two PHP files combined into one HTML file.
Example 1:
HTML
<html><body>  <h1>Welcome to geeks for geeks!</h1>  <p>Myself, Gaurav Gandal</p>  <p>Thank you</p>  <?php require 'GFG.php'; ?></body></html>
GFG.php
<?php    echo "<p>visit Again-" . date("Y") . " geeks for geeks.com</p>";?>
Output:
PHP include() Function: The include() function in PHP is basically used to include the contents/code/data of one PHP file to another PHP file. During this process if there are any kind of errors then this include() function will pop up a warning but unlike the require() function, it will not stop the execution of the script rather the script will continue its process. In order to use this include() function, we will first need to create two PHP files. Using the include() function, include one PHP file into another one. After that, you will see two PHP files combined into one HTML file. 
Example 2:
HTML
<html><body>  <h1>Welcome to geeks for geeks!</h1>  <p>Myself, Gaurav Gandal</p>    <p>Thank you</p>    <?php include 'GFG.php'; ?></body></html>
GFG.php
<?php   echo "<p>Visit Again; " . date("Y") . " Geeks for geeks.com</p>";?>
Output:
Difference between require() and include():
mortadarsh
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Get parameters passed by urls in Django - GeeksforGeeks

05 Sep, 2020
Django is a fully fleshed framework which can help you create web applications of any form. This article discusses how to get parameters passed by URLs in django views in order to handle the function for the same. You might have seen various blogs serving with urls like: – 
www.example.com/articles/991 
In the url above 991 is the Id of article which is being currently served to you. We are going to make this functionality in Django.
Create an new virtual environment and install Django.
Start a new Django project by typing this command: –
django-admin startproject test

Create a very simple Article model in your models.py.
class Article(models.Model):    author = models.CharField(max_length = 20)    content = models.TextField()
Now go to django admin and add some articles for testing.
Now open your urls.py file and add the url pattern as given below: –
url_patterns += [    path("articles/<id>/", views.article_detail, name ="article_detail"),]
Make sure to import your views.py file here.
The <id> here will help us get and use the id parameter in our view.
Now create a new views.py file and add the following view: –
def article_detail(request, id):  article = Article.objects.filter(id = id)  return render("your_template", context ={"article":article})
Make sure to replaxe your_template with your template path. Now you should be able to access article inside your template and render it.
Visit http://localhost:8000/articles/1 in your browser and you will be able to see your article. If you replace 1 with any non-existent id it will show a 404 not found error.
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Selenium on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Check the OS Version in Linux?
How to Set Java Path in Windows and Linux?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
How to Install Flutter on Visual Studio Code?
How To Pass and Parse Linux Bash Script Arguments and Parameters
Lookbehind Assertions JavaScript Regular Expressions

Lookbehind allows matching a pattern only if there’re something before.Following is an example −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample, .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Look behind Assertions Regular Expressions</h1>
<div class="sample">The price for 4 tables are $50 , $99 , $121 and $150.</div>
<div style="color: green;" class="result"></div>
<button class="btn">CLICK HERE</button>
<h3>
Click on the above button to extract the table price using lookbehind
</h3>
<script>
   let sampleEle = document.querySelector(".sample").innerHTML;
   let btnEle = document.querySelector(".btn");
   let resEle = document.querySelector(".result");
   const priceRegex=/(?<=\$)\d+/g;
   btnEle.addEventListener("click", () => {
      resEle.innerHTML = "Table price are = "+sampleEle.match(priceRegex);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
How to write Assertions in Postman with Chai Assertion Library?

We can write Assertions in Postman with Chai Assertion Library. Assertions are added in tests to verify if the actual and expected results are similar. In case, they are dissimilar, an Assertion error gets thrown along with the cause of the error.
Boolean value of either true or false is returned by an Assertion. In Postman, Assertion is handled by Chai Assertion Library which is developed in JavaScript. It is provided in the Postman application by default.
Assertions in Postman are added under the Tests tab. The documentation of the Chai library details are present in the link − https://www.chaijs.com/.
Let us create an Assertion to verify if a specific text – Postman is present in an array of strings.
   pm.test["Text is present"], function(){
      pm.expect(['Java', 'Postman']).to.include('Postman')
   })
Output −
Let us create another Assertion to verify if an array contains elements.
   pm.test["Array contains element"], function(){
      pm.expect(['Java', 'Postman']).to.be.an('array').that.is.not .empty
   })
Output −
Let us implement an Assertion for verification of objects with eql function. This function compares properties of one object with another.
   pm.test("Equality", function(){
   let i = {
      "subject" : "Postman"
   };
   let j= {
      "subject" : "Cypress"
   };
   pm.expect(i).to.not.eql(j);
Output −
The property declared for object i is Postman while the property declared for j is Cypress. Hence not.eql Assertion gives a true result.
Transpose of a two-dimensional array - JavaScript

The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). We can transpose a matrix (2-D array) by switching its rows with its columns.
Let’s say the following is our 2d array −
const arr = [
   [1, 1, 1],
   [2, 2, 2],
   [3, 3, 3],
];
Let’s write the code for this function −
Following is the code −
const arr = [
   [1, 1, 1],
   [2, 2, 2],
   [3, 3, 3],
];
const transpose = arr => {
   for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < i; j++) {
         const tmp = arr[i][j];
         arr[i][j] = arr[j][i];
         arr[j][i] = tmp;
      };
   }
}
transpose(arr);
console.log(arr);
The output in the console: −
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
How to set JavaScript Cookie with no expiration date?

The expires option in a JavaScript cookie is optional. The “expires” attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
To set JavaScript cookie with no expiration date, try to run the following code −
Live Demo
<html>
   <head>
      <script>
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );

               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');

               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         <p> click the following button and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>
Subscripting [] Operator Overloading in C++

The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.
Following example explains how  a subscript operator [] can be overloaded.
#include <iostream>
using namespace std;
const int SIZE = 10;

class safearay {
   private:
      int arr[SIZE];
      
   public:
      safearay() {
         register int i;
         for(i = 0; i < SIZE; i++) {
           arr[i] = i;
         }
      }
      
      int &operator[](int i) {
         if( i > SIZE ) {
            cout << "Index out of bounds" <<endl; 
            // return first element.
            return arr[0];
         }
         
         return arr[i];
      }
};

int main() {
   safearay A;

   cout << "Value of A[2] : " << A[2] <<endl;
   cout << "Value of A[5] : " << A[5]<<endl;
   cout << "Value of A[12] : " << A[12]<<endl;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
How to find the column names and row names from a matrix in R?

The rownames and colnames functions are used to define the corresponding names of a matrix and if we want to extract those names then the same function will be used. For example, if we have a matrix called M that has row names and column names then these names can be found by using rownames(M) and colnames(M).
Live Demo
> M1<-matrix(1:100,ncol=10)
> M1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
> rownames(M1)<-LETTERS[1:10]
> colnames(M1)<-LETTERS[1:10]
> M1
A B C D E F G H I J
A 1 11 21 31 41 51 61 71 81 91
B 2 12 22 32 42 52 62 72 82 92
C 3 13 23 33 43 53 63 73 83 93
D 4 14 24 34 44 54 64 74 84 94
E 5 15 25 35 45 55 65 75 85 95
F 6 16 26 36 46 56 66 76 86 96
G 7 17 27 37 47 57 67 77 87 97
H 8 18 28 38 48 58 68 78 88 98
I 9 19 29 39 49 59 69 79 89 99
J 10 20 30 40 50 60 70 80 90 100
> Row_Names_M1<-rownames(M1)
> Row_Names_M1
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
> Column_Names_M1<-colnames(M1)
> Column_Names_M1
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
Live Demo
> M2<-matrix(rpois(25,2),nrow=5)
> M2
[,1] [,2] [,3] [,4] [,5]
[1,] 2 1 4 0 2
[2,] 3 3 0 3 3
[3,] 0 4 3 4 1
[4,] 4 1 0 1 0
[5,] 0 4 2 4 1
> rownames(M2)<-c("India","Russia","China","Canada","USA")
> colnames(M2)<-c("India","Russia","China","Canada","USA")
> M2
India Russia China Canada USA
India 2 1 4 0 2
Russia 3 3 0 3 3
China 0 4 3 4 1
Canada 4 1 0 1 0
USA 0 4 2 4 1
> Row_Names_M2<-rownames(M2)
> Row_Names_M2
[1] "India" "Russia" "China" "Canada" "USA"
Column_Names_M2<-colnames(M2)
> Column_Names_M2
[1] "India" "Russia" "China" "Canada" "USA"
Live Demo
> M3<-matrix(rnorm(36),nrow=6)
> M3
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] -0.81749436 -0.32603647 0.03249139 1.5090542 -0.9081710 1.2238853
[2,] -0.04507115 1.07842603 -1.11499780 0.4417905 -0.2758092 -0.9476823
[3,] -1.03613764 -2.65759584 -1.15795880 -1.9723598 -0.8386178 -0.2994112
[4,] 0.10289330 -0.06578772 -0.11692342 0.6313891 0.9125360 -0.2126542
[5,] 0.28185191 1.13375235 -0.47490971 0.2593980 -0.9350917 -0.4375274
[6,] 0.08914057 -0.32701974 1.25754633 -1.7432336 1.1584573 0.4017967
> rownames(M3)<-c("C1","C2","C3","C4","C5","C6")
> colnames(M3)<-c("S1","S2","S3","S4","S5","S6")
> M3
S1 S2 S3 S4 S5 S6
C1 -0.81749436 -0.32603647 0.03249139 1.5090542 -0.9081710 1.2238853
C2 -0.04507115 1.07842603 -1.11499780 0.4417905 -0.2758092 -0.9476823
C3 -1.03613764 -2.65759584 -1.15795880 -1.9723598 -0.8386178 -0.2994112
C4 0.10289330 -0.06578772 -0.11692342 0.6313891 0.9125360 -0.2126542
C5 0.28185191 1.13375235 -0.47490971 0.2593980 -0.9350917 -0.4375274
C6 0.08914057 -0.32701974 1.25754633 -1.7432336 1.1584573 0.4017967
> Row_Names_M3<-rownames(M3)
> Row_Names_M3
[1] "C1" "C2" "C3" "C4" "C5" "C6"
> Column_Names_M3<-colnames(M3)
> Column_Names_M3
[1] "S1" "S2" "S3" "S4" "S5" "S6"