code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Series.itemsize

28 Jan, 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 is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.itemsize attribute return the size of the dtype of the item of the underlying data for the given Series object.
Syntax:Series.itemsize
Parameter : None
Returns : size
Example #1: Use Series.itemsize attribute to check the size of the underlying data for the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4']   # Print the seriesprint(sr)
Output :
Now we will use Series.itemsize attribute to check the size of the underlying data in the given Series object.
# return the sizesr.itemsize
Output :As we can see in the output, the Series.itemsize attribute has returned 8 indicating that the size of the underlying data for the given Series object is 8 bytes. Example #2 : Use Series.itemsize attribute to check the size of the underlying data for the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.itemsize attribute to check the size of the underlying data in the given Series object.
# return the sizesr.itemsize
Output :As we can see in the output, the Series.itemsize attribute has returned 8 indicating that the size of the underlying data for the given Series object is 8 bytes.
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.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Python | Selective value selection in list of tuples

12 Mar, 2019
Sometimes, while using list of tuples, we come across a problem in which we have a certain list of keys and we just need the value of those keys from list of tuples. This has a utility in rating or summation of specific entities. Let’s discuss certain ways in which this can be done.
Method #1 : Using dict() + get() + list comprehensionWe can perform this particular task by first, converting the list into the dictionary and then employing list comprehension to get the value of specific keys using get function.
# Python3 code to demonstrate  # Selective Value selection in list of tuples# using dict() + get() + list comprehension  # initializing list of tuples test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]  # initializing selection list select_list = ['Nikhil', 'Akshat']  # printing original list print ("The original list is : " + str(test_list))  # printing selection list print ("The selection list is : " + str(select_list))  # using dict() + get() + list comprehension# Selective Value selection in list of tuplestemp = dict(test_list)res = [temp.get(i, 0) for i in select_list]  # printing resultprint ("The selective values of keys : " + str(res))
The original list is : [(‘Nikhil’, 1), (‘Akash’, 2), (‘Akshat’, 3), (‘Manjeet’, 4)]The selection list is : [‘Nikhil’, ‘Akshat’]The selective values of keys : [1, 3]
 
Method #2 : Using next() + list comprehensionThis particular problem can be solved using the next function which performs the iteration using the iterators and hence more efficient way to achieve a possible solution.
# Python3 code to demonstrate  # Selective Value selection in list of tuples# using next() + list comprehension  # initializing list of tuples test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]  # initializing selection list select_list = ['Nikhil', 'Akshat']  # printing original list print ("The original list is : " + str(test_list))  # printing selection list print ("The selection list is : " + str(select_list))  # using next() + list comprehension# Selective Value selection in list of tuplesres = [next((sub[1] for sub in test_list        if sub[0] == i), 0) for i in select_list]  # printing resultprint ("The selective values of keys : " + str(res))
The original list is : [(‘Nikhil’, 1), (‘Akash’, 2), (‘Akshat’, 3), (‘Manjeet’, 4)]The selection list is : [‘Nikhil’, ‘Akshat’]The selective values of keys : [1, 3]
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | sleep( ) Function

03 Jul, 2018
The sleep() function in PHP is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds. The sleep( ) function accepts seconds as a parameter and returns TRUE on success or FALSE on failure.
If the call is interrupted by a signal, sleep() function returns a non-zero value. On Windows, this value will always be 192 whereas, on other platforms, the return value will be the number of seconds left to sleep.
Syntax:
sleep($seconds)
Parameters Used: The sleep() function in PHP accepts one parameter.
$seconds : It is a mandatory parameter which specifies the number of seconds.
Return Value: It returns TRUE on success or FALSE on failure.
Errors And Exceptions:
If the call is interrupted by a signal, sleep() function returns a non-zero value.The value of seconds passed as parameter should be non-negative else this function will generate a E_WARNING..
If the call is interrupted by a signal, sleep() function returns a non-zero value.
The value of seconds passed as parameter should be non-negative else this function will generate a E_WARNING..
Below programs illustrate the sleep() function:
Program 1:
<?php// displaying timeecho date('h:i:s')."\n" ;   // delaying execution of the script for 2 secondssleep(2);   // displaying time againecho date('h:i:s');?>
Output:
06:53:48
06:53:50

Program 2:
<?php// displaying timeecho date('h:i:s')."\n" ;   // using rand() function to randomly choose// a value and delay execution of the scriptsleep(rand(1, 5));   // displaying time againecho date('h:i:s');  ?>
Output:
06:53:48
06:53:52

Reference: http://php.net/manual/en/function.sleep.php
PHP-function
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
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
What are event handlers in JavaScript?

JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click to is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
Here are some examples:
onclick Event Type
This is the most frequently used event type, which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Try the following example.
Live Demo
<html>
   <head>
      <script>
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button and see result</p>
      <form>
         <input type="button" onclick="sayHello()" value="Say Hello" />
      </form>
   </body>
</html>
 onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example.
Live Demo
<html>
   <head>
      <script>
         <!--
            function over() {
               document.write ("Mouse Over");
            }
            function out() {
               document.write ("Mouse Out");
            }
         //-->
      </script>
   </head>
   <body>
      <p>Bring your mouse inside the division to see the result:</p>
      <div onmouseover="over()" onmouseout="out()">
         <h2> This is inside the division </h2>
      </div>
   </body>
</html>
How to import CSV file in SQLite database using Python ?

09 May, 2021
In this article, we’ll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students.
Contents of the CSV file
Approach:
Importing necessary modules
Read data from CSV file DictReader()
Establish a connection with the database.
sqliteConnection = sqlite3.connect('sql.db')
cursor = sqliteConnection.cursor()
Create the student table and execute the query using execute() method.
Inserting data into the table
cursor.executemany("insert into student (name, age) VALUES (?, ?);", student_info)
Read data from the table
And close the database.
Below is the implementation:
Python3
import csvimport sqlite3    try:      # Import csv and extract data    with open('student_info.csv', 'r') as fin:        dr = csv.DictReader(fin)        student_info = [(i['NAME'], i['AGE']) for i in dr]        print(student_info)      # Connect to SQLite    sqliteConnection = sqlite3.connect('sql.db')    cursor = sqliteConnection.cursor()      # Create student table    cursor.execute('create table student(name varchar2(10), age int);')      # Insert data into table    cursor.executemany(        "insert into student (name, age) VALUES (?, ?);", student_info)      # Show student table    cursor.execute('select * from student;')      # View result    result = cursor.fetchall()    print(result)      # Commit work and close connection    sqliteConnection.commit()    cursor.close()  except sqlite3.Error as error:    print('Error occured - ', error)  finally:    if sqliteConnection:        sqliteConnection.close()        print('SQLite Connection closed')
Output:
Picked
Python-SQLite
Python
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
sciPy stats.zscore() function | Python

20 Feb, 2019
scipy.stats.zscore(arr, axis=0, ddof=0) function computes the relative Z-score of the input data, relative to the sample mean and standard deviation.
Its formula:
Parameters :arr : [array_like] Input array or object for which Z-score is to be calculated.axis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation.
Results : Z-score of the input data.
Code #1: Working
# stats.zscore() method  import numpy as npfrom scipy import stats    arr1 = [[20, 2, 7, 1, 34],        [50, 12, 12, 34, 4]]  arr2 = [[50, 12, 12, 34, 4],         [12, 11, 10, 34, 21]]  print ("\narr1 : ", arr1)print ("\narr2 : ", arr2)  print ("\nZ-score for arr1 : \n", stats.zscore(arr1))print ("\nZ-score for arr1 : \n", stats.zscore(arr1, axis = 1))
Output :
arr1 :  [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]]

arr2 :  [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]]

Z-score for arr1 : 
 [[-1. -1. -1. -1.  1.]
 [ 1.  1.  1.  1. -1.]]

Z-score for arr1 : 
 [[ 0.57251144 -0.85876716 -0.46118977 -0.93828264  1.68572813]
 [ 1.62005758 -0.61045648 -0.61045648  0.68089376 -1.08003838]]

 Code #2 : Z-score
import numpy as npfrom scipy import stats   arr2 = [[50, 12, 12, 34, 4],         [12, 11, 10, 34, 21]]  print ("\nZ-score for arr2 : \n", stats.zscore(arr2, axis = 0))print ("\nZ-score for arr2 : \n", stats.zscore(arr2, axis = 1))
Output :

Z-score for arr2 : 
 [[ 1.  1.  1. nan -1.]
 [-1. -1. -1. nan  1.]]

Z-score for arr2 : 
 [[ 1.62005758 -0.61045648 -0.61045648  0.68089376 -1.08003838]
 [-0.61601725 -0.72602033 -0.83602341  1.80405051  0.37401047]]

Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inline Functions in C++

C++ inline function is a powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because the compiler would need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of the inline function to return a max of two numbers −
 Live Demo
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
   return (x > y)? x : y;
}
// Main function for the program
int main() {
   cout << "Max (20,10): " << Max(20,10) << endl;
   cout << "Max (0,200): " << Max(0,200) << endl;
   cout << "Max (100,1010): " << Max(100,1010) << endl;
   return 0;
}
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
How to find the length of the longest substring from the given string without repeating the characters using C#?

From the given string input, use the sliding window technique by having 2 pointers i and j . both i and j will point to the same character in the string. Traverse through the string and add it to the list. If the repeated character is found then remove it from the list else append to the list.
Input − s = "abcabcbb"
Output − 3
Explanation − The answer is "abc", with the length of 3.
Input − s = "bbbbb"
Output − 1
Explanation − The answer is "b", with the length of 1.
Time complexity − O(N)
Space complexity − O(N)
public class Arrays{
   public int LongestSubstringWithNoRepeatingCharacters(string s){
      List<char> c = new List<char>();
      int iPointer = 0;
      int jpointer = 0;
      int max = 0;
      while (jpointer < s.Length){
         if (c.Contains(s[jpointer])){
            c.Remove(s[iPointer]);
            iPointer++;
         }
         else{
            max = Math.Max(c.Count(), max);
            c.Add(s[jpointer]);
            jpointer++;
         }
      }
      return max;
   }
}

static void Main(string[] args){
   int res = s.LongestSubstringWithNoRepeatingCharacters("abcabcbb");
   Console.WriteLine(res);
}
2
How to subset rows of an R data frame using grepl function?

The grepl function in R search for matches to argument pattern within each element of a character vector or column of an R data frame. If we want to subset rows of an R data frame using grepl then subsetting with single-square brackets and grepl can be used by accessing the column that contains character values.
Consider the below data frame:
Live Demo
> x1<-sample(c("A","B","C"),20,replace=TRUE)
> y1<-rnorm(20,1,0.24)
> z1<-rpois(20,2)
> df1<-data.frame(x1,y1,z1)
> df1
  x1   y1    z1
1 A 0.8833979 5
2 B 0.5400075 1
3 C 0.6923827 3
4 B 1.5069186 2
5 B 0.8190962 2
6 B 0.8296171 1
7 B 1.2793876 4
8 B 1.1401782 2
9 C 1.5187263 0
10 C 0.6187501 2
11 B 1.3837516 0
12 C 0.8790544 0
13 A 0.7818624 3
14 B 0.8659361 2
15 B 0.9503166 2
16 A 0.8711020 2
17 B 1.0646814 2
18 A 1.2973144 1
19 C 0.9172171 2
20 B 0.7062629 3
Subsetting df1 by excluding A in x1:
> df1[!grepl("A",df1$x1),]
  x1   y1    z1
2 B 0.5400075 1
3 C 0.6923827 3
4 B 1.5069186 2
5 B 0.8190962 2
6 B 0.8296171 1
7 B 1.2793876 4
8 B 1.1401782 2
9 C 1.5187263 0
10 C 0.6187501 2
11 B 1.3837516 0
12 C 0.8790544 0
14 B 0.8659361 2
15 B 0.9503166 2
17 B 1.0646814 2
19 C 0.9172171 2
20 B 0.7062629 3
Live Demo
> x2<-sample(c("India","China","France"),20,replace=TRUE)
> y2<-rexp(20,0.335)
> df2<-data.frame(x2,y2)
> df2
   x2      y2
1 India 2.91693551
2 India 5.86599500
3 China 3.41872121
4 India 6.82404548
5 France 4.26003369
6 China 6.31902445
7 China 2.67848516
8 France 3.20830803
9 India 0.01151151
10 India 2.04166415
11 China 1.72607765
12 China 2.31852068
13 India 1.59578792
14 France 1.06253867
15 China 1.44092496
16 China 2.89259111
17 China 0.16299576
18 France 3.37298728
19 India 0.94687404
20 France 1.26557174
Subsetting df2 by excluding France in x2:
> df2[!grepl("France",df2$x2),]
    x2     y2
1 India 2.91693551
2 India 5.86599500
3 China 3.41872121
4 India 6.82404548
6 China 6.31902445
7 China 2.67848516
9 India 0.01151151
10 India 2.04166415
11 China 1.72607765
12 China 2.31852068
13 India 1.59578792
15 China 1.44092496
16 China 2.89259111
17 China 0.16299576
19 India 0.94687404
Python MySQL - Limit

While fetching records if you want to limit them by a particular number, you can do so, using the LIMIT clause of MYSQL.
Assume we have created a table in MySQL with name EMPLOYEES as −
mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)
And if we have inserted 4 records in to it using INSERT statements as −
mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);
Following SQL statement retrieves first two records of the Employee table using the LIMIT clause.
SELECT * FROM EMPLOYEE LIMIT 2;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 19   | M    | 2000   |
| Raj        | Kandukuri | 20   | M    | 7000   |
+------------+-----------+------+------+--------+
2 rows in set (0.00 sec)

If you invoke the execute() method on the cursor object by passing the SELECT query along with the LIMIT clause, you can retrieve required number of records.
To drop a table from a MYSQL database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it.
Following python example creates and populates a table with name EMPLOYEE and, using the LIMIT clause it fetches the first two records of it.
import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2'''

#Executing the query
cursor.execute(sql)

#Fetching the data
result = cursor.fetchall();
print(result)

#Closing the connection
conn.close()
[('Krishna', 'Sharma', 26, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]

If you need to limit the records starting from nth record (not 1st), you can do so, using OFFSET along with LIMIT.
import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''

#Executing the query
cursor.execute(sql)

#Fetching the data
result = cursor.fetchall();
print(result)

#Closing the connection
conn.close()
[('Ramya', 'Ramapriya', 29, 'F', 5000.0), ('Mac', 'Mohan', 26, 'M', 2000.0)]


    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
How I can set the width and height of a JavaScript alert box?

To set the width and height of an alert box in JavaScript, you need to use the custom alert box. This alert box is styled with CSS.
Set the width and height of the alert box using the following code, which uses jQuery, a JavaScript library −
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         function functionAlert(msg, myYes)
         {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function()
            {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm
         {
            display: none;
            background-color: #F3F5F6;
            color: #000000;
            border: 1px solid #aaa;
            position: fixed;
            width: 300px;
            height: 100px;
            left: 50%;
            margin-left: -100px;
            padding: 10px 20px 10px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #FFFFFF;
            display: inline-block;
            border-radius: 12px;
            border: 4px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 60px;
            cursor: pointer;
         }
         #confirm .message
         {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class = "message">This is a warning message.</div><br>
         <button class="yes">OK</button>
      </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>
How to remove all style attributes using jQuery?

To remove an attribute from each tag using jQuery, use the removeAttr() method and use the Universal Selector. Let us see how to use the method to remove all style attribute. Use the universal selector also to select all the elements.
You can try to run the following code to learn how to remove all style attributes using jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("h1").removeAttr("style");
  });
});
</script>
</head>
<body>

<h1 style="color:blue">This is heading</h1>

<p>This is demo text.</p>

<h1 style="color:red">This is heading</h1>

<p>This is demo text.</p>
<button>Remove</button>
<p>Click above to remove style attribute from all h1 elements.</p>

</body>
</html>
Python & MySQL - Where Clause Example

Python uses c.execute(q) function to select a record(s) conditionally using Where Clause from a table where c is cursor and q is the select query to be executed.
# execute SQL query using execute() method.
cursor.execute(sql)

result = cursor.fetchall()

for record in result:
   print(record)

$sql
Required - SQL query to select record(s) from a table.
Try the following example to select records from a table −
Copy and paste the following example as mysql_example.ty −
#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "Select * from tutorials_tbl Where tutorial_id = 3"

# execute SQL query using execute() method.
cursor.execute(sql)

# fetch all records from cursor
result = cursor.fetchall()

# iterate result and print records
for record in result:
   print(record)

# disconnect from server
db.close()
Execute the mysql_example.py script using python and verify the output.
(3, 'JQuery', 'Julie', datetime.date(2020, 5, 10))


    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
Matplotlib - Setting Ticks and Tick Labels

Ticks are the markers denoting data points on axes. Matplotlib has so far - in all our previous examples - automatically taken over the task of spacing points on the axis.Matplotlib's default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks can be explicitly mentioned to suit specific requirements.
The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed.
ax.set_xticks([2,4,6,8,10])
This method will mark the data points at the given positions with ticks.
Similarly, labels corresponding to tick marks can be set by set_xlabels() and set_ylabels() functions respectively.
ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’])
This will display the text labels below the markers on the x axis.
Following example demonstrates the use of ticks and labels.
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = np.sin(x)
ax.plot(x, y)
ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])
plt.show()

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Updating Lists in Python

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method.
 Live Demo
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Note − append() method is discussed in subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001
Pygame - Flip the image - GeeksforGeeks

30 Jun, 2021
In this article, we are going to see how images can be flipped using Pygame.
To flip the image we need to use pygame.transform.flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs.
Syntax:
pygame.transform.flip(Surface, xbool, ybool)
In this, we have to flip the image in a vertical direction. We will use pygame.transform.flip() to display the image in vertical. Pass xbool as True and ybool as False, so that the image is flipped vertically.
Input used:
Python3
# import pygame and sysimport pygameimport sys  from pygame.locals import *  # pygame.init() will initialize all# imported modulepygame.init()pygame.display.set_caption('GeeksforGeeks')  # screen size will display on screenscreen = pygame.display.set_mode((600, 400), 0, 32)  # pygame.image.load() will return the# object that has imageimg = pygame.image.load('image.png')  while True:          # Background color    screen.fill((255, 255, 255))          # image copy    img_copy = img.copy()          # pygame.transform.flip() will flip the image    img_with_flip = pygame.transform.flip(img_copy, True, False)          # surface.blit() function draws a source     # Surface onto this Surface.    screen.blit(img_with_flip, (50 + 1 * 120, 100))          # event listener to quit screen    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()      # update the frame per second    pygame.display.update()
Output
In this we have to flip the image in horizontal direction. For this xbool is passed as False and ybool as True, to flip it horizontally.
Program:
Python3
# import pygame and sysimport pygameimport sys  from pygame.locals import *  # pygame.init() will initialize all # imported modulepygame.init()pygame.display.set_caption('GeeksforGeeks')  # screen size will display on screenscreen = pygame.display.set_mode((600, 400), 0, 32)  # pygame.image.load() will return the# object that has imageimg = pygame.image.load('image.png')  while True:          # Background color    screen.fill((255, 255, 255))          # image copy    img_copy = img.copy()          # pygame.transform.flip() will flip the image    img_with_flip = pygame.transform.flip(img_copy, False, True)          # surface.blit() function draws a source     # Surface onto this Surface.    screen.blit(img_with_flip, (50 + 1 * 120, 100))          # event listener to quit screen    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()      # update the frame per second    pygame.display.update()
Output
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Generating Basic Discrete Time Signals - GeeksforGeeks

02 Sep, 2020
Generating basic discrete-time signals for Discrete-Time Signal ProcessingUnit Step, Unit Impulse, Unit Ramp, exponential signals are very commonly used signals in signal processing to perform various operations.
Unit step signal is given by
Unit impulse signal is given by
Unit ramp signal is given by
Exponential signal is given by
Input :
Unit Step Signal u[n-2]
 
Output :


Input :
Unit Impulse Signal d(4)

Output :


Input :
Unit Ramp Signal

Output: 



Input:
Exponential signal for a=2

Output: 

Code: Python code implementation to generate the basic discrete time signals
# importing librariesimport numpy as npimport matplotlib.pyplot as plt  # function to generate unit step u[n-a]# LL and UL are lower and upper limits of discrete time linedef unit_step(a, n):    unit =[]    for sample in n:        if sample<a:            unit.append(0)        else:            unit.append(1)    return(unit)  # plot unit step function u[n-a]a = 2 # Enter delay or advanceUL = 10LL = -10n = np.arange(LL, UL, 1)unit = unit_step(a, n)plt.stem(n, unit)plt.xlabel('n')plt.xticks(np.arange(LL, UL, 1))plt.yticks([0, 1])plt.ylabel('u[n]')plt.title('Unit step u[n-a]')plt.savefig('UnitStep.png')  # Function to plot Impulse signal d(a)def unit_impulse(a, n):    delta =[]    for sample in n:        if sample == a:            delta.append(1)        else:            delta.append(0)                  return delta  a = 4 # Enter delay or advanceUL = 10LL = -10n = np.arange(LL, UL, 1)d = unit_impulse(a, n)plt.stem(n, d)plt.xlabel('n')plt.xticks(np.arange(LL, UL, 1))plt.yticks([0, 1])plt.ylabel('d[n]')plt.title('Unit Impulse d[4]')plt.savefig("UnitImpulse.png")    # Function to generate unit ramp signal r(n)# r(n)= n for n>= 0, r(n)= 0 otherwisedef unit_ramp(n):    ramp =[]    for sample in n:        if sample<0:            ramp.append(0)        else:            ramp.append(sample)    return ramp  UL = 10LL = -10n = np.arange(LL, UL, 1)r = unit_ramp(n)plt.stem(n, r)plt.xlabel('n')plt.xticks(np.arange(LL, UL, 1))plt.yticks([0, UL, 1])plt.ylabel('r[n]')plt.title('Unit Ramp r[n]')plt.savefig("UnitRamp.png")  # Function to generate exponential signals e**(at)def exponential(a, n):    expo =[]    for sample in n:        expo.append(np.exp(a * sample))    return (expo)         a = 2UL = 1LL = -1n = np.arange(LL, UL, 0.1)x = exponential(a, n)plt.stem(n, x)plt.xlabel('n')plt.xticks(np.arange(LL, UL, 0.2))# plt.yticks([0, UL, 1])plt.ylabel('x[n]')plt.title('Exponential Signal e**(an)')plt.savefig("Exponential.png")
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Snackbar in Android using Jetpack Compose - GeeksforGeeks

26 Apr, 2021
Prerequisites:
Snackbar Material Design Components in Android
Jetpack Compose in Android
Snackbar is a lightweight widget and they are used to show messages at the bottom of the application. It was introduced with the Material Design library as a replacement for a Toast.  In this article, we will explain how you can create a Snackbar using Jetpack Compose. Below is the sample picture to show what we are going to build. 
Step 1: Create a new project
To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose. 
Step 2: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
class MainActivity : ComponentActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContent {            JetpackComposePracticeTheme {                // A surface container using the 'background' color from the theme                Surface(color = Color.White) {                    Column(modifier = Modifier.padding(10.dp)) {                        // call the function which contains all the snackbars                        SnackBars()                    }                }            }        }    }}  // In order to use compose properties annotate with @Compose@Preview@Composablefun SnackBars() {    Text(text = "Snackbars", style = typography.h6, modifier = Modifier.padding(8.dp))    // Normal Snackbar    Snackbar(modifier = Modifier.padding(4.dp)) {        Text(text = "This is a basic snackbar")    }    // Snackbar with action item    Snackbar(        modifier = Modifier.padding(4.dp),        action = {            TextButton(onClick = {}) {                Text(text = "Remove")            }        }    ) {        Text(text = "This is a basic Snackbar with action item")    }     // Snackbar with action item below text    Snackbar(        modifier = Modifier.padding(4.dp),        actionOnNewLine = true,        action = {            TextButton(onClick = {}) {                Text(text = "Remove")            }        }    ) {        Text(text = "Snackbar with action item below text")    }}
Output:
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
Get Random Dog Images in Python - GeeksforGeeks

06 Jun, 2021
In this article, we will discuss how to get random dog images in Python.
It can be done using the random-dog module. It outputs random dogs images using a single LOC and fetches from data set provided by the dog-ceo API. 
This module does not come built-in with Python. To install this type the below command in the terminal.
pip install random-dog
Once the library is installed, dog module needs to be imported, and the getDoc() needs to be called with the required parameters and returns the desired random image of dog. 
Syntax:
getDog(directory=curr, filename=random_id)
Parameters:
directory : Directory to save image to.filename : Name of file image to be saved with. Defaults to randomly generated ID. 
Example 1: 
Python3
import dog  # saves filename as randog.jpg # in current directorydog.getDog(filename='randog')
Output :
Using from Command Line
From the command line as well, a similar task can be performed. The command required for it is.  
$ randomdog [file]file : Path to save image, defaults to current.
This saves the randomly generated dog image to the current or desired path if provided.
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to create equal height columns with CSS?

To create equal height columns with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .container {
      display: table;
      width: 100%;
   }
   .column {
      display: table-cell;
      padding: 16px;
      background-color: greenyellow;
   }
   .column:nth-of-type(2n-1) {
      color: red;
      background-color: yellow;
   }
</style>
</head>
<body>
<h1>Equal Height Columns Example</h1>
<div class="container">
<div class="column">
<h2>Column 1</h2>
<h2>Column 1</h2>
<h2>Column 1</h2>
</div>
<div class="column">
<h2>Column 2</h2>
<h2>Column 2</h2>
<h2>Column 2</h2>
</div>
<div class="column">
<h2>Column 3</h2>
<h2>Column 3</h2>
<h2>Column 3</h2>
</div>
</div>
</body>
</html>
The above code will produce the following output −
How to increase the width of the lines in the boxplot created by using ggplot2 in R?

When we create a boxplot using ggplot2, the default width of the lines in the boxplot is very thin and we might want to increase that width to make the visibility of the edges of the boxplot clearer. This will help viewers to understand the edges of the boxplot in just a single shot. We can do this by using lwd argument of geom_boxplot function of ggplto2 package.
Consider the below data frame −
 Live Demo
> ID<-rep(c("S1","S2","S3","S4"),times=100)
> Count<-sample(1:50,400,replace=TRUE)
> df<-data.frame(ID,Count)
> head(df,20)
 ID Count
1 S1 20
2 S2 14
3 S3 17
4 S4 30
5 S1 17
6 S2 23
7 S3 36
8 S4 10
9 S1 14
10 S2 28
11 S3 42
12 S4 10
13 S1 25
14 S2 12
15 S3 4
16 S4 38
17 S1 3
18 S2 45
19 S3 33
20 S4 43
Loading ggplot2 package and creating boxplot of Count for IDs −
> library(ggplot2)
> ggplot(df,aes(ID,Count))+geom_boxplot()
Creating the boxplot with different width of the lines −
> ggplot(df,aes(ID,Count))+geom_boxplot(lwd=2)
Lex program to check whether an year is a leap year or not - GeeksforGeeks

01 May, 2019
Problem: Write a Lex program to check whether an year is a leap year or not.
Explanation:Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Note: Leap years are the years that are divisible by 400 or are divisible by 4 and not divisible by 100. So 2016, 2020 etc are leap years while 2017 and 2019 are not.
Examples:
Input: 2016 
Output: leap year

Input: 2017
Output: not a leap year 
Implementation:
/*Lex program to check whether an year is a leap year or not*/  %{ void check(char *);%}  /*Rule Section*/ %%   [0-9]    ;[0-9][0-9]    ;[0-9][0-9][0-9]     ;[0-9][0-9][0-9][0-9]    { printf("%s", yytext);check(yytext); }[0-9][0-9][0-9][0-9][0-9]+ ; %%  // driver programint main(){    extern FILE *yyin;    yyin=fopen("num", "r");      // The function that starts the analysis     yylex();    return 0;  }  void check(char *a){    int x=0, i;      for(i=0;i<4;i++)        x=x*10+(a[i]-'0');      if(x%400==0)           printf("\tleap year\n");      else if(x%4==0&&x%100!=0)        printf("\tleap year\n");      else        printf("\tnot a leap year\n");}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SLR Parser (with Examples)
Introduction to Syntax Analysis in Compiler Design
Difference between Top down parsing and Bottom up parsing
Linker
Error detection and Recovery in Compiler
Problem on LR(0) parser
Differences between Synthesized and Inherited Attributes
Applications of Compiler Technology
BNF Notation in Compiler Design
Loop Optimization in Compiler Design
How to get symmetric difference between two arrays in JavaScript ? - GeeksforGeeks

06 Apr, 2021
In Mathematics the symmetric difference between two sets A and B is represented as A Δ B = (A – B) ∪ (B – A)
It is defined as a set of all elements that are present in either set A or set B but not in both.
In simple words, common elements are discarded from both sets.
A = { 1, 2, 3, 4, 5, 6}
B = { 4, 5, 6, 7 }

A - B = { 1, 2, 3, 4, 5, 6} - { 4, 5, 6, 7 }
      = { 1, 2, 3 }
B - A = { 4, 5, 6, 7 } - { 1, 2, 3, 4, 5, 6}
      = { 7, 1, 2, 3 }
      
A Δ B = ( A - B ) ∪ ( B - A )
      = { 1, 2, 3 } ∪ { 7, 1, 2, 3 }
A Δ B = { 1, 2, 3, 7 }
Javascript
<script>    /* Defining two arrays and a                 resultant array*/    const a = [1, 2, 3, 4, 5, 7, 9];    const b = [5, 6, 7, 8, 9];    const result = [];      /* Defining the function with two     arguments array inputs */    function difference(arr1, arr2) {        var i = 0,            j = 0;        var flag = false;          /* For array 1 */        for (i = 0; i < arr1.length; i++) {              /* Reseting the flag and the             other array iterator */            j = 0;            flag = false            while (j != arr2.length) {                if (arr1[i] == arr2[j]) {                    flag = true;                    break;                }                j++;            }              /* If value is not present in the             second array then push that value             to the resultant array */            if (!flag) {                result.push(arr1[i]);            }        }        flag = false;          /* For array 2 */        for (i = 0; i < arr2.length; i++) {              /* Reseting the flag and the             other array iterator */            j = 0;            flag = false            while (j != arr1.length) {                if (arr2[i] == arr1[j]) {                    flag = true;                    break;                }                j++;            }              /* If value is not present in the            first array then push that value             to the resultant array */            if (!flag) {                result.push(arr2[i]);            }        }        return result;    }    console.log(difference(a, b));</script>
[ 1, 2, 3, 4, 6, 8]
javascript-array
JavaScript-Methods
JavaScript-Properties
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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?
JS Full Form - GeeksforGeeks

06 Oct, 2020
JS stands for JavaScript. It is a lightweight, cross-platform, and interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set of language elements like operators, control structures, and statements. You can check the Introduction to JavaScript.JS version release year:  
JS Structure: 
Javascript
<script type="text/javascript">    // Your javaScript code</script>
Characteristics of JS: 
Dynamically typed languages: This language can receive different data types over time.
Case Sensitive Format: JavaScript is case sensitive so you have to aware of that.
Light Weight: It is so lightweight, and all the browsers are supported by JS.
Handling: Handling events is the main feature of JS, it can easily respond on the website when the user tries to perform any operation.
Interpreter Centered: JavaScript is built with interpreter centered that allows the user to get the output without the use of the compiler.
Advantages of JS: 
JavaScript executed on the user’s browsers not on the webserver so it saves bandwidth and load on the webserver.
The JavaScript language is easy to learn it offers syntax that is close to English language.
In JavaScript, if you ever need any certain feature then you can write it by yourself and use an add-on like Greasemonkey to implement it on the web page.
It does not require a compilation process so no compiler is needed user’s browsers do the task.
JavaScript is easy to debug, and there are lots of frameworks available that you can use and become master on that.
Disadvantages of JS: 
JavaScript codes are visible to the user so user can place some code into the site that compromises the security of data over the website. That will be security issue.
All browsers interpret JavaScript that is correct, but they interpret differently to each other.
It only supports single inheritance, so in few cases may require the object-oriented language characteristic.
A single error in code can totally stop the website’s code rendering on the website.
JavaScript stores number as a 64-bit floating-point number but operators operate on 32-bit bitwise operands.
 
sonalikamishra29
javascript-basics
Picked
JavaScript
Web Technologies
Write From Home
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
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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 ?
Difference between var, let and const keywords in JavaScript