code-rag-bench/online-tutorials huggingface dataset:
JQuery | type() method - GeeksforGeeks

27 Apr, 2020
This type() Method in jQuery is used to determine the internal JavaScript [[Class]] of an object.
Syntax:
jQuery.type( obj )

Parameters: The type() method accepts only one parameter that is mentioned above and described below:
obj: This parameter is the object to get the internal JavaScript [[Class]] of.
Return Value: It returns the string.
jQuery.type( true ) === “boolean”
jQuery.type( new Boolean() ) === “boolean”
jQuery.type( 3 ) === “number”
jQuery.type( new Number(3) ) === “number”
jQuery.type( undefined ) === “undefined”
jQuery.type() === “undefined”
jQuery.type( window.notDefined ) === “undefined”
jQuery.type( null ) === “null”
jQuery.type( “test” ) === “string”
jQuery.type( new String(“test”) ) === “string”
jQuery.type( function(){} ) === “function”
jQuery.type( [] ) === “array”
jQuery.type( new Array() ) === “array”
jQuery.type( new Date() ) === “date”
jQuery.type( new Error() ) === “error”
jQuery.type( Symbol() ) === “symbol”
jQuery.type( Object(Symbol()) ) === “symbol”
jQuery.type( /test/ ) === “regexp”
Example 1: In this example, the type() method check whether the parameter is a array or not.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | type() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script><style>    div {        color: blue;    }</style></head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | type() method</h3>    <p> Check Whether the [] is array type:</p>    <b></b>    <script>    $( "b" ).append( "" + jQuery.type( [] ) === "array");    </script>  </body></html>                                    
Output:
Example 2: In this example, the type() method the object is undefined or null.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | type() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script><style>    b {        color: blue;    }</style></head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | type() method</h3>    <p> If Object is undefined or null, <br>Value return:</p>    <b></b>    <script>    $( "b" ).append("undefined : " + jQuery.type( undefined )+ "<br>"+    "window.notDefined  : " + jQuery.type(window.notDefined )+ "<br>"+    "null  : " + jQuery.type( null  )+ "<br>"    );    </script>  </body></html>                                    
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Difference Between JavaScript and jQuery
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to save an Android Activity state using save instance state?

This example demonstrate about How to save an Android Activity state using save instance state
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/actionEvent"
      android:textSize = "40sp"
      android:layout_marginTop = "30dp"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show restore instance elements.
Step 3 − Add the following code to src/MainActivity.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView actionEvent;
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      actionEvent = findViewById(R.id.actionEvent);
   }
   @Override
   public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
      savedInstanceState.putString("MyString", "Welcome back to Android");
   }
   @Override
   protected void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      String myString = savedInstanceState.getString("MyString");
      actionEvent.setText(myString);
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Rotate the screen you will get text as shown above.
Click here to download the project code
Scala String getBytes() method with example - GeeksforGeeks

03 Oct, 2019
The getBytes() method is utilized to encode a stated string into a series of bytes and then it stores it into a new byte array. Moreover, here platforms default charset is utilized.
Method Definition: byte getBytes()Return Type: It returns a new byte array storing series of bytes.
Example #1:
// Scala program of getBytes()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying getBytes method        val result = "Nidhi".getBytes()                  // Displays output        println(result)          }} 
[B@506e1b77

Example #2:
// Scala program of getBytes()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying getBytes method        val result = " ".getBytes()                  // Displays output        println(result)              }} 
[B@506e1b77

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hello World in Scala
Scala Map get() method with example
Scala ListBuffer
Scala List map() method with example
Scala List length() method with example
How to install Scala on Windows?
Scala | Traits
Scala | Case Class and Case Object
Inheritance in Scala
Python - Network Interface

When we have multiple interfaces in a machine we need to keep track of their names, status etc. In Python we can list the interfaces and their status. 
In the below example we use the python module netifaces which gives the details of the interfaces and their status. The methods used are very simple and straight forward.
import netifaces

print (netifaces.interfaces())


print (netifaces.ifaddresses('lo'))

print (netifaces.AF_LINK)

addrs = netifaces.ifaddresses('ens33')
print(addrs[netifaces.AF_INET])


print(addrs[netifaces.AF_LINK])
When we run the above program, we get the following output −
# Result

['lo', 'ens33']
{17: [{'peer': '00:00:00:00:00:00', 'addr': '00:00:00:00:00:00'}], 2: [{'peer': '127.0.0.1', 'addr': '127.0.0.1', 'netmask': '255.0.0.0'}], 10: [{'addr': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128'}]}

17

[{'netmask': '255.255.255.0', 'addr': '192.168.232.128', 'broadcast': '192.168.232.255'}]
[{'addr': '00:0c:29:ea:13:0a', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]



    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
chdir() in C language with Examples - GeeksforGeeks

04 Jan, 2019
The chdir command is a system function (system call) which is used to change the current working directory. On some systems, this command is used as an alias for the shell command cd. chdir changes the current working directory of the calling process to the directory specified in path.
Syntax:
int chdir(const char *path);
Parameter: Here, the path is the Directory path which the user want to make the current working directory.
Return Value: This command returns zero (0) on success. -1 is returned on an error and errno is set appropriately.
Note: It is declared in unistd.h.
Example 1:
#include<stdio.h>  // chdir function is declared// inside this header#include<unistd.h> int main(){       char s[100];      // printing current working directory    printf("%s\n", getcwd(s, 100));      // using the command    chdir("..");      // printing current working directory    printf("%s\n", getcwd(s, 100));      // after chdir is executed    return 0;}
Output:
Note:The above program changes the working directory of a process. But, it doesn’t change the working directory of current shell. Because when the program is executed in the shell, the shell follows fork on exec mechanism. So, it doesn’t affect the current shell.
Example 2:
#include <unistd.h>#include <stdio.h>  // Main Methodint main() {    // changing the current   // working directory(cwd)  // to /usr  if (chdir("/usr") != 0)     perror("chdir() to /usr failed");    // changing the cwd to /tmp  if (chdir("/tmp") != 0)     perror("chdir() to /temp failed");    // there is no /error   // directory in my pc  if (chdir("/error") != 0)       // so chdir will return -1     perror("chdir() to /error failed");      return 0;}
Output:
Errors: There can be errors which can be returned. These depend on the filesystem.
EACCES: If the search permission is denied for one of the components of path.
EFAULT: If the path points lie outside the accessible address space.
EIO: If there is an I/O error occurred.
ELOOP: If there are too many symbolic links were encountered in the resolving path.
ENAMETOOLONG: If the path is too long.
ENOENT: If the file does not exist.
ENOMEM: If there is insufficient kernel memory is available.
ENOTDIR: If the component of path is not a directory.
C-Functions
linux-command
Picked
system-programming
C Language
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
SQL Query to Alter Column Size in MySQL

31 Aug, 2021
Sometimes you may need to change column size or change field length in MySQL. In this article, we will look at how to change column size in MySQL. You can use these commands to increase column size in MySQL or decrease it.
SQL ALTER TABLE Statement:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
Syntax:
ALTER TABLE table_name
MODIFY column_name
varchar(new_length);
Example:
Let’s create a table with table_name; “student”
-- create a table
CREATE TABLE students (Sr_No integer,Name varchar(20), Gender integer);
DESCRIBE is used to describe something. Since in database we have tables, that’s why we use DESCRIBE or DESC(both are same) command to describe the structure of a table.
Syntax:
DESCRIBE student;
 OR
DESC student;
Using this command for an above table (in Xampp);
Output:
Now change the size of the column using Alter command
ALTER TABLE student
MODIFY Name
varchar(50);
To see the table structure, use Describe command:
DESCRIBE student;
Output:
Column size is altered from 20 to 50.
For decreasing size of Column “Gender”
ALTER TABLE student
MODIFY Gender
varchar(9);
To see the table structure, use Describe command:
DESCRIBE student;
Output:
Column size is altered from 11 to 9.
arorakashish0911
mysql
Picked
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Find LCM using Python?

LCM (Least common multiple) of two (or more) numbers is a number which is the smallest number that is divisible by both (or all).
First we find the larger number of two given numbers. Starting from it we try and find the first number that is divisible by both, which is LCM
x=12
y=20
if x > y:  
   greater = x  
else:  
   greater = y  
while(True):  
   if((greater % x == 0) and (greater % y == 0)):  
        lcm = greater  
        break  
    greater += 1

print ("LCM of {} and {}={}".format(x,y,lcm))
The result is −
LCM of 12 and 20=60
How to save Matplotlib Animation?

03 Mar, 2021
In this article, we will learn How to save Matplotlib Animation. The animated graphs made with the help of matplotlib can be saved as videos in Python. As we can create captivating animations using the matplotlib library. If you want to learn to create animations, here is a link to the article to create animations using the matplotlib. In this article, we will learn how to save animation in matplotlib. To save an animation, we can use Animation.save() or Animation.to_html5_video().
Animation.to_html5_video() returns the animation as an HTML5 video tag. It saves the animation as h264 encoded video, which can be directly displayed in the notebook.
Example 1:
Python3
# importing required librariesfrom matplotlib import pyplot as pltimport numpy as npimport matplotlib.animation as animationfrom IPython import display  # initializing a figurefig = plt.figure()  # labeling the x-axis and y-axisaxis = plt.axes(xlim=(0, 4),  ylim=(-1.5, 1.5))  # initializing a line variableline, = axis.plot([], [], lw=3)  def animate(frame_number):    x = np.linspace(0, 4, 1000)      # plots a sine graph    y = np.sin(2 * np.pi * (x - 0.01 * frame_number))    line.set_data(x, y)    line.set_color('green')    return line,    anim = animation.FuncAnimation(fig, animate, frames=100,                                interval=20, blit=True)fig.suptitle('Sine wave plot', fontsize=14)  # converting to an html5 videovideo = anim.to_html5_video()  # embedding for the videohtml = display.HTML(video)  # draw the animationdisplay.display(html)plt.close()
Output:
For using the Animation.save() method to save the animation, we need to provide the writer parameter. Here are few common writers available to write the animation:
PillowWriter: It relies on pillow library. It is preferred when you want to save the animation in gif format.
FFMpegWriter: pipe-based ffmpeg writer.
ImageMagickWriter: pipe-based animated gif.
AVConvWriter: pipe-based avconv writer.
Example 2:
Python3
# importing required librariesfrom matplotlib import pyplot as pltimport numpy as npimport matplotlib.animation as animationfrom IPython import display  # initializing a figurefig = plt.figure()  # labeling the x-axis and y-axisaxis = plt.axes(xlim=(0, 1000),  ylim=(0, 1000))  # lists storing x and y valuesx, y = [], []  line, = axis.plot(0, 0)    def animate(frame_number):    x.append(frame_number)    y.append(frame_number)    line.set_xdata(x)    line.set_ydata(y)    return line,    anim = animation.FuncAnimation(fig, animate, frames=1000,                                interval=20, blit=True)fig.suptitle('Straight Line plot', fontsize=14)  # saving to m4 using ffmpeg writerwritervideo = animation.FFMpegWriter(fps=60)anim.save('increasingStraightLine.mp4', writer=writervideo)plt.close()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
std::string::back() in C++ with Examples

28 May, 2019
This function returns a direct reference to the last character of the string. This shall only be used on non-empty strings.This can be used to access the last character of the string as well as to append a character at the end of the string. Length of the string remains unchanged after appending a character, last character of string gets replaced by the new one
Syntax
string str ("GeeksforGeeks");

Accessing last character
char end_char = str.back();

Appending character at end of string
str.back() = '#';

Parameter: This function takes no parameter
Return value: A reference to the last character in the string
Exception: If the string is empty it shows undefined behavior.
Below examples illustrate the use of the above method:
Program 1:
// C++ program to demonstrate// the use of the above method  #include <iostream>  // for std::string::back#include <string>  using namespace std;  int main(){    string str("GeeksforGeeks");      // Accessing last character of string    char end_char = str.back();      cout << "Last character of string = "         << end_char << endl;      // Appending a character to    // the end of string    str.back() = '#';      cout << "New string = " << str << endl;      return 0;}
Last character of string = s
New string = GeeksforGeek#

Program 2: It shows undefined behavior when the string is empty.
// C++ program to demonstrate// the use of the above method  #include <iostream>  // for std::string::front#include <string>  using namespace std;  int main(){    string str(""); // Empty string      // trying to access last character    // of an empty string    char end_char = str.back();      cout << "Last character of string = "         << end_char << endl;      // Appending a character to    // the end of an empty string    str.back() = '#';      cout << "New string = " << str << endl;      return 0;}
Last character of string = 
New string = ÉGu0005Ãu000e@·u000bùu0014þ?aPé£Îýu000e@?k ̄u0004ÃÿÿÿÿÿÿÿXé£Îýÿÿÿu0001u0016
@Ï? ̈Õu0006,Äu000f f@Pé£ÎýÏ??u0019Á±?ðÏ?u0016u001eØ%Bð3ÇGu0005Ã ̧ÂEu0005Ã:μ# f@Pé£ÎýIf@Hé£Îýu001cu0001aÿ£Îý!P·Îýu0010ÿû?u001fu0006u0010u0011du0003@@u00048u0005    u0007ÀFu0005Ãb     f@u000béu0003féu0003
éu0003u000eéu0003u0017u0019©ê£Îýu001fÑÿ£Îýu000f1ê£Îý3⁄4·u000bùu0014þ?aDdCu0016â?gCx86_64

Reference: std::string::back()
CPP-Functions
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Inheritance in C++
Object Oriented Programming in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Python | Replace multiple characters at once

01 Jul, 2019
The replacement of one character with another is a common problem that every python programmer would have worked with in the past. But sometimes, we require a simple one line solution which can perform this particular task. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using nested replace()This problem can be solved using the nested replace method, which internally would create a temp. variable to hold the intermediate replacement state.
# Python3 code to demonstrate working of# Replace multiple characters at once# Using nested replace()  # initializing string test_str = "abbabba"  # printing original string print("The original string is : " + str(test_str))  # Using nested replace()# Replace multiple characters at onceres = test_str.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')  # printing result print("The string after replacement of positions : " + res)
The original string is : abbabba
The string after replacement of positions : baabaab

 
Method #2 : Using translate() + maketrans()There is also a dedication function which can perform this type of replacement task in a single line hence this is a recommended way to solve this particular problem. Works only in Python2.
# Python code to demonstrate working of# Replace multiple characters at once# Using translate() + maketrans()import string  # initializing string test_str = "abbabba"  # printing original string print("The original string is : " + str(test_str))  # Using translate() + maketrans()# Replace multiple characters at onceres = test_str.translate(string.maketrans("ab", "ba"))  # printing result print("The string after replacement of positions : " + res)
The original string is : abbabba
The string after replacement of positions : baabaab

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
VBA - LBound Function

The LBound Function returns the smallest subscript of the specified array. Hence, LBound of an array is ZERO.
LBound(ArrayName[,dimension])

ArrayName − A required parameter. This parameter corresponds to the name of the array.
ArrayName − A required parameter. This parameter corresponds to the name of the array.
Dimension − An optional parameter. This takes an integer value that corresponds to the dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension and so on.
Dimension − An optional parameter. This takes an integer value that corresponds to the dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension and so on.
Add a button and add the following function.
Private Sub Constant_demo_Click()
   Dim arr(5) as Variant
   arr(0) = "1"           'Number as String
   arr(1) = "VBScript     'String
   arr(2) = 100           'Number
   arr(3) = 2.45          'Decimal Number
   arr(4) = #10/07/2013#  'Date
   arr(5) = #12.45 PM#    'Time
   msgbox("The smallest Subscript value of  the given array is : " & LBound(arr))

   ' For MultiDimension Arrays :
   Dim arr2(3,2) as Variant
   msgbox("The smallest Subscript of the first dimension of arr2 is : " & LBound(arr2,1))
   msgbox("The smallest Subscript of the Second dimension of arr2 is : " & LBound(arr2,2))
End Sub
When you execute the above function, it produces the following output.
The smallest Subscript value of the given array is : 0
The smallest Subscript of the first dimension of arr2 is : 0
The smallest Subscript of the Second dimension of arr2 is : 0


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How do I verify that a string only contains letters, numbers, underscores and dashes in Python?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$". 
import re
print(bool(re.match("^[A-Za-z0-9_-]*$", 'aValidString123--__')))
print(bool(re.match("^[A-Za-z0-9_-]*$", 'inv@lid')))
True
False
You can also get this result by using Sets. Declare a set using the characters you want to allow and use the following code −
from sets import Set
allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
validationString = 'inv@lid'
if Set(validationString).issubset(allowed_chars):
    print True
else:
    print False
This will give you the result −
False
Requests - Handling Redirection

This chapter will take a look at how the Request library handles the url redirection case.
import requests
getdata = requests.get('http://google.com/')
print(getdata.status_code)
print(getdata.history)    
The url: http://google.com will be redirected using status code 301(Moved Permanently) to https://www.google.com/. The redirection will be saved in the history.
When the above code is executed, we get the following result −
E:\prequests>python makeRequest.py
200
[<Response [301]>]

You can stop redirection of a URL using allow_redirects = False. It can be done on GET, POST, OPTIONS, PUT, DELETE, PATCH methods used.
Here is an example on the same.
import requests
getdata = requests.get('http://google.com/', allow_redirects=False)
print(getdata.status_code)
print(getdata.history)
print(getdata.text)    
Now if you check the output, the redirection will not be allowed and will get a status code of 301.
E:\prequests>python makeRequest.py
301
[]
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

 Print
 Add Notes
 Bookmark this page
Python Support for bzip2 compression (bz2)

The bzip2 is an open source algorithm for compression and decompression of files. Python’s bz2 module provides functionality to implement bzip2 algorithm programmatically.
The open() function is the primary interface to this module.
This function opens a bzip2 compressed file and returns a file object. The file can be opened as binary/text mode with read/write permission. The function performs compression based on compressionlevel argument between 1 to 9.
When the file is opened in ‘w’ or ‘wb’ mode, this function is available to the file object. In binary mode, it writes compressed binary data to the file. In normal text mode, the file object is wrapped in TetIOWrapper object to perform encoding.
read() − When opened in read mode, this function reads it and returns the uncompressed data.
Following code writes the compressed data to a bzip2 file.
>>> f = bz2.open("test.bz2", "wb")
>>> data = b'Welcome to TutorialsPoint'
>>> f.write(data)
>>> f.close()
This will create test.bz2 file in current directory. Any unzipping tool will show a ‘test’ file in it. To read the uncompressed data from this test.bz2 file use following code.
>>> f = bz2.open("test.bz2", "rb")
>>> data=f.read()
>>> data
b'Welcome to TutorialsPoint'
The bz2 module also defines BZ2File class. Its object acts as a compressor and decompressor depending upon mode parameter to the constructor.
This is the constructor. As in open() function, file and mode parameters are required. The compressionlevel by default is 9 and can be between 1 to 9.
This function returns object of Incremental compressor class. Each call to compress() method in this class returns a chunk of compressed data. Multiple chunks can be concatenated together and finally written to the bzip2 compression file.
This method empties the buffer and returns chunk of data in it to be appended to the compressed object.
This function returns incremental decompressor’s object. Individual chinks of decompressed data concatenated together with fludhed data form the uncompressed data.
Following example first compresses each iem in the list object and writes the concatenated byte object to the file. The data is retrieved by BZ2Decompressor object.
>>> data = [b'Hello World', b'How are you?', b'welcome to Python']
>>> obj = bz2.BZ2Compressor()
>>> f = bz2.open("test.bz2", "wb")
>>> d1 = obj.compress(data[0])
>>> d2 = obj.compress(data[1])
>>> d3 = obj.compress(data[2])
>>> d4 = obj.flush()
>>> d1,d2,d3,d4
(b'', b'', b'', b'BZh91AY&SYS\x9a~\x99\x00\x00\x03\x1f\x80@\x00\x00\x00\x80@@\x80.G\x96\xa0 \x00!\xa8\xd0\x06\x9a6\x90\xa6LL\x83#\x18\x1d\x83\xee^]\x1e|\xa9\xddgu\x15G/\x1a\x8c\xd1\x90\x14\x8f\x8b\xb9"\x9c(H)\xcd?L\x80')
>>> compressedobj=d1+d2+d3+d4
>>> f.write(compressedobj)
>>> f.close()
>>> obj=bz2.BZ2DeCompressor()
>>> f=bz2.open("test.bz2", "rb")
>>> data=f.read()
>>> obj.decompress(data)
b'Hello WorldHow are you?welcome to Python'
Java Examples - Multiple Exceptions (Array out of bound)

How to handle multiple exceptions while array is out of bound ?
This example shows how to handle multiple exception methods by using System.err.println() method of System class.
public class Main {
   public static void main (String args[]) {
      int array[] = {20,20,40};
      int num1 = 15, num2 = 10;
      int result = 10;
      try {
         result = num1/num2;
         System.out.println("The result is" +result);
         for(int i = 5; i >= 0; i--) {
            System.out.println("The value of array is" +array[i]);
         }
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Array is out of Bounds"+e);
      } catch (ArithmeticException e) {
         System.out.println ("Can't divide by Zero"+e);
      }
   }
}
The above code sample will produce the following result.
The result is1
Array is out of Boundsjava.lang.ArrayIndexOutOfBoundsException : 5

 Print
 Add Notes
 Bookmark this page
HTML | <bgsound> tag

27 Aug, 2019
The HTML <bgsound> tag is used to play the soundtrack in the background, when you leave the page behind and open a new tab this tag will continuously play the track in the background.This tag is not for other browsers except the Internet Explorer. It does not display any graphical interface just played the track in the background.
Syntax:
<bgsound src="">
Attribute:
src: This attribute holds the path of the tack that will be played in the background.
loop: This attribute holds a number that the number of times the track will play looping around.
Below example illustrate the HTML <bgsound> tag:Example:
<!DOCTYPE html><html>  <head>    <title>      HTML <bgsound> Tag  </title>    <style>        h1 {            color: green;        }    </style></head>  <body>    <center>        <h1>GeeksforGeeks</h1>        <h2>HTML <bgsound> tag</h2>        <bgsound src="https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3" />         <p>please plugin speaker/headphone to listen to the sound.</p>    </center></body>  </html>
Output:
Supported Browsers: The supported browsers by HTML | <bgsound> tag are listed below:
Internet Explorer
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove given character from Strings list

29 Nov, 2019
Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let’s discuss certain ways to solve this problem.
Method #1 : Using replace() + enumerate() + loopThis is brute force way in which this problem can be solved. In this, we iterate through each string and replace specified character with empty string to perform removal.
# Python3 code to demonstrate working of# Remove character from Strings list# using loop + replace() + enumerate()  # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list print("The original list : " + str(test_list))  # initialize characterchar = 's'  # Remove character from Strings list# using loop + replace() + enumerate()for idx, ele in enumerate(test_list):        test_list[idx] = ele.replace(char, '')  # printing resultprint("The list after removal of character : " + str(test_list))
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

 
Method #2 : Using list comprehension + replace()This task can also be performed using above functionalities. In this, we offer a one-liner solution to this problem compacting the code using similar method as above.
# Python3 code to demonstrate working of# Remove character from Strings list# using list comprehension + replace()  # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list print("The original list : " + str(test_list))  # initialize characterchar = 's'  # Remove character from Strings list# using list comprehension + replace()res = [ele.replace(char, '') for ele in test_list]  # printing resultprint("The list after removal of character : " + str(res))
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
YACC program to check whether given string is Palindrome or not

15 Oct, 2019
Problem: Write a YACC program to check whether given string is Palindrome or not.
Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc.
Examples:
Input: naman
Output: palindrome

Input: geeksforgeeks
Output: not palindrome 
Lexical Analyzer Source Code :
%{    /* Definition section */    #include <stdio.h>    #include <stdlib.h>    #include "y.tab.h"%}  /* %option noyywrap */  /* Rule Section */%%  [a-zA-Z]+   {yylval.f = yytext; return STR;}[-+()*/]    {return yytext[0];}[ \t\n]      {;}  %%   int yywrap() {   return -1;  }  
Parser Source Code:
%{    /* Definition section */    #include <stdio.h>    #include <string.h>       #include <stdlib.h>    extern int yylex();         void yyerror(char *msg);    int flag;         int i;    int k =0;       %}  %union {    char* f; }  %token <f> STR%type <f> E  /* Rule Section */%%  S : E    {         flag = 0;         k = strlen($1) - 1;         if(k%2==0){                       for (i = 0; i <= k/2; i++) {           if ($1[i] == $1[k-i]) {            } else {               flag = 1;              }          }         if (flag == 1) printf("Not palindrome\n");         else printf("palindrome\n");         printf("%s\n", $1);                   }else{                  for (i = 0; i < k/2; i++) {          if ($1[i] == $1[k-i]) {          } else {              flag = 1;             }            }        if (flag == 1) printf("Not palindrome\n");        else printf("palindrome\n");        printf("%s\n", $1);                                }       }  ;  E :  STR    {$$ = $1;}  ;  %%  void yyerror(char *msg) {    fprintf(stderr, "%s\n", msg);    exit(1); }  //driver code int main() {    yyparse();    return 0; }
Output:
rahulsangwan3
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
How to set input type date in dd-mm-yyyy format using HTML ?

28 Jul, 2021
To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from. If min and max values are not set then default min value is set to “01-01-1920” and default max value is set to “01-01-2120”.
Example 1: This example uses <input type=”date”> attribute to get the date in dd-mm-yyyy format.
<!DOCTYPE html><html>  <head>    <title>        How to get input type date        in dd-mm-yyyy format ?    </title>          <style>        body {            text-align: center;        }        h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <h3>        Get input date in        dd-mm-yyyy format    </h3>          <label for="start">        Enter the Date:    </label>      <input type="date" name="begin"         placeholder="dd-mm-yyyy" value=""        min="1997-01-01" max="2030-12-31"></body>  </html>
Output:
Example 2: This example uses <input type=”date”> attribute to get the date in dd-mm-yyyy format.
<!DOCTYPE html><html>  <head>    <title>        How to get input type date        in dd-mm-yyyy format ?    </title>          <style>        body {            text-align: center;        }        h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <h3>        Get input date in        dd-mm-yyyy format    </h3>          <label for="Date of Birth">        Enter the Date:        <input type="date" name="date">    </label></body>  </html>
Output:
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
__tostring element in Lua Programming

The _tostring element in Lua receives an argument of any type and converts it to a string in a reasonable format.
If the metatable of e has a "__tostring" field, then tostring calls the corresponding value with e as argument, and uses the result of the call as its result.
The __tostring element method is a part of the metatables that Lua library provides us and is used to modify the behaviour of the table that we get as an output.
The __tostring element method is used to modify the behavior of the output table.
 Live Demo
currtable = setmetatable({ 10, 20, 30 }, {
   __tostring = function(currtable)
      sum = 0
      for k, v in pairs(currtable) do
         sum = sum + v
      end
      return "The sum is: " .. sum
   end
})
print(currtable)
print(type(currtable))
The sum is: 60
table
Python | Difference between two dates (in minutes) using datetime.timedelta() method

08 Sep, 2020
To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects. To find the difference between two dates in form of minutes, the attribute seconds of timedelta object can be used which can be further divided by 60 to convert to minutes.Example 1:The following program takes two datetime objects and finds the difference between them in minutes. 
import datetime  # datetime(year, month, day, hour, minute, second)a = datetime.datetime(2017, 6, 21, 18, 25, 30)b = datetime.datetime(2017, 5, 16, 8, 21, 10)  # returns a timedelta objectc = a-b print('Difference: ', c)  minutes = c.total_seconds() / 60print('Total difference in minutes: ', minutes)  # returns the difference of the time of the dayminutes = c.seconds / 60print('Difference in minutes: ', minutes)
Output:
Difference:  36 days, 10:04:20
Difference in minutes:  604.3333333333334
Example 2: To get a more appropriate answer divmod() can be used which will return the fractional part of the minutes in terms of seconds: 
import datetime  # datetime(year, month, day, hour, minute, second)a = datetime.datetime(2017, 6, 21, 18, 25, 30)b = datetime.datetime(2017, 5, 16, 8, 21, 10)  # returns a timedelta objectc = a-b print('Difference: ', c)  # returns (minutes, seconds)minutes = divmod(c.total_seconds(), 60) print('Total difference in minutes: ', minutes[0], 'minutes',                                 minutes[1], 'seconds')  # returns the difference of the time of the day (minutes, seconds)minutes = divmod(c.seconds, 60) print('Total difference in minutes: ', minutes[0], 'minutes',                                 minutes[1], 'seconds')
Output:
Difference:  36 days, 10:04:20
Difference in minutes:  604 minutes 20 seconds
alexanderlewang
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Security Testing - Injection

Injection technique consists of injecting a SQL query or a command using the input fields of the application.
A successful SQL injection can read, modify sensitive data from the database, and can also delete data from a database. It also enables the hacker to perform administrative operations on the database such as shutdown the DBMS/dropping databases.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
The application uses untrusted data in the construction of the following vulnerable SQL call −
String query = "SELECT * FROM EMP WHERE EMPID = '" + request.getParameter("id") + "'";
Step 1 − Navigate to the SQL Injection area of the application as shown below.
Step 2 − As given in the exercise, we use String SQL Injection to bypass authentication. Use SQL injection to log in as the boss ('Neville') without using the correct password. Verify that Neville's profile can be viewed and that all functions are available (including Search, Create, and Delete).
Step 3 − We will Inject a SQL such that we are able to bypass the password by sending the parameter as 'a' = 'a' or 1 = 1
Step 4 − Post Exploitation, we are able to login as Neville who is the Admin as shown below.
There are plenty of ways to prevent SQL injection. When developers write the code, they should ensure that they handle special characters accordingly. There are cheat sheets/prevention techniques available from OWASP which is definitely a guide for developers.
Using Parameterized Queries
Escaping all User Supplied Input
Enable Least Privilege for the database for the end users
How to remove rows that contain all zeros in R dataframe?

27 Mar, 2021
In this article, let’s discuss how to rows that contain all zeroes in R dataframe.
Approach:
Create dataframe
Get the sum of each row
Simply remove those rows that have zero-sum. Based on the sum we are getting we will add it to the new dataframe. if the sum is greater than zero then we will add it otherwise not.
Display dataframe
To calculate the sum of each row rowSums() function can be used.
Syntax:
df[rowSums(df[])>0,]
Where, df is the dataframe.
Example 1:
R
df <- data.frame(x = c(0, 1, 3, 0, 0), y = c(0, 1, 5, 0, 3))  print("data frame is ")print(df)  ans = df[rowSums(df[])>0,]  print("rows after removing rows that have all zeros")print(ans)
Output:
Example 2:
R
a = rep(0,10)b = sample(c(0,1),10,replace=TRUE)df = data.frame(a,b)print("dataframe is ")print(df)  ans = df[rowSums(df[])>0,]print("rows after removing rows that have all zeros")print(ans)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.combine()

30 Sep, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.combine() is a series mathematical operation method. This is used to combine two series into one. The shape of output series is same as the caller series. The elements are decided by a function passed as parameter to combine() method. The shape of both series has to be same otherwise it will throw an error.
Syntax: Series.combine(other, func, fill_value=nan)
Parameters:other: other series or list type to be combined with caller seriesfunc: Function passed as parameter which will decide from which series the element should be put at that indexfill_value: integer value of level in case of multi index
Return: Combined series with same shape as caller series
Example #1:
In this example, two lists are made and converted into pandas series using .Series() method. A function is made using lambda which checks which values is smaller in both series and returns whichever is the smaller.
# importing pandas moduleimport pandas as pd  # creating first seriesfirst =[1, 2, 5, 6, 3, 7, 11, 0, 4]  # creating second seriessecond =[5, 3, 2, 1, 3, 9, 21, 3, 1]  # making seriesfirst = pd.Series(first)  # making seriesasecond = pd.Series(second)  # calling .combine() methodresult = first.combine(second, (lambda x1, x2: x1 if x1 < x2 else x2))  # displayresult
Output:As shown in the output image, the returned series is having smaller values from both series. Example #2:
In this example, Null values are passed too using Numpy.nan method. Since series contains null values, 5 is passed to fill_value parameter to replace null values by 5. A lambda function is passed which will compare values in both series and will return the greater one.
# importing pandas moduleimport pandas as pd  # importing numpy moduleimport numpy as np  # creating first seriesfirst =[1, 2, np.nan, 5, 6, 3, np.nan, 7, 11, 0, 4, 8]  # creating second seriessecond =[5, 3, 2, np.nan, 1, 3, 9, 21, 3, np.nan, 1, np.nan]  # making seriesfirst = pd.Series(first)  # making seriesasecond = pd.Series(second)  # calling .combine() methodresult = first.combine(second, func =(lambda x1, x2: x1 if x1 > x2 else x2), fill_value = 5)  # displayresult
Output:As shown in the output, the NaN values in the series were replaced by 5 before combining the series.

0      5.0
1      3.0
2      2.0
3      5.0
4      6.0
5      3.0
6      9.0
7     21.0
8     11.0
9      5.0
10     4.0
11     8.0
dtype: float64
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find parity in C++

In this tutorial, we will be discussing a program to find parity.
For this we will be provided with a number. Our task is to find its parity i.e count of whether the number of ones are odd or even.
 Live Demo
# include<bits/stdc++.h>
# define bool int
using namespace std;
//finding the parity of given number
bool getParity(unsigned int n) {
   bool parity = 0;
   while (n){
      parity = !parity;
      n = n & (n - 1);
   }
   return parity;
}
int main() {
   unsigned int n = 7;
   cout<<"Parity of no "<<n<<": "<<(getParity(n)? "Odd": "even");
   getchar();
   return 0;
}
Parity of no 7: odd