code-rag-bench/online-tutorials huggingface dataset:
jQuery Mobile - Textinput Datetime

datetime type attribute in input defines the date and time control. A date and time (year, month, day, hour, minute, second, fractions of a second) is encoded according to ISO 8601 with the time zone set to UTC.
Following example demonstrates the use of datetime input in the jQuery Mobile.
<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
      <script src = "https://code.jquery.com/jquery-1.11.3.min.js"></script>
      <script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
   </head>
   
   <body>
      <form>
         <h2>Datetime Input Example</h2>
         <label for = "src">Datetime Input</label>
         <input type = "datetime" id = "src" data-clear-btn = "false">

         <label for = "src1">Clear the Datetime Field</label>
         <input type = "datetime" data-clear-btn = "true" id = "src1">

         <label for = "src2">Datetime Local Input</label>
         <input type = "datetime-local" id = "src2" data-clear-btn = "false">

         <label for = "src3">Clear the Datetime Local Field</label>
         <input type = "datetime-local" data-clear-btn = "true" id = "src3">
      </form>
   </body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above html code as textinput_datetime.html file in your server root folder.
Save the above html code as textinput_datetime.html file in your server root folder.
Open this HTML file as http://localhost/textinput_datetime.html and the following output will be displayed.
Open this HTML file as http://localhost/textinput_datetime.html and the following output will be displayed.

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
JavaScript Array copyWithin() Method - GeeksforGeeks

01 Feb, 2021
Below is the example of the Array copyWithin() method. 
Example: 
Javascript
<script>    // Input array    var array = [1, 2, 3, 4, 5, 6, 7];     // placing at index position 0 the element    // between index 3 and 6    document.write("Array " + array.copyWithin(0, 3, 6));</script>
Output: 
Array 4, 5, 6, 4, 5, 6, 7
The arr.copyWithin() method copies part of an array to the same array and returns it, without modifying its size i.e, copies array element of an array within the same array.
Syntax: 
array.copyWithin(target, start, end)
Parameters: This method accepts three parameters as mentioned above and described below:  
target: The index position to copy the elements to(Required).
start: It is optional. The index position to start copying elements from (default is 0).
end: It is optional. The index position to stop copying elements from (default is array.length).
Return value: It returns the modified array.
More example codes for the above method are as follows:
Program 1:  
Javascript
<script>    // Input array    var array = [1, 2, 3, 4, 5, 6, 7];     // Placing from index position 0 the    // Element from index 4    document.write("Array " + array.copyWithin(0, 4));</script>
Output: 
Array 5, 6, 7, 4, 5, 6, 7
Program 2: 
Javascript
<script>    // Input array    var array = [1, 2, 3, 4, 5, 6, 7];     // Placing from index position 3    // The element from index 0    document.write("Array " + array.copyWithin(3));</script>
Output: 
Array 1, 2, 3, 1, 2, 3, 4
Application: Whenever we need to copy the content of any array to the same array that time we use arr.copyWithin() element in JavaScript.
Javascript
<script>    // Input array    var array = [1, 2, 3, 4, 5, 6, 7];     // Placing at index position 0 the    // Element between index 4 and 5    document.write("Array " + array.copyWithin(0, 4, 5));</script>
Output: 
Array 5, 2, 3, 4, 5, 6, 7
Supported Browsers: The browsers supported by JavaScript Array copyWithin() method are listed below: 
Google Chrome 45.0
Microsoft Edge 12.0
Mozilla Firefox 32.0
Opera 32.0
Safari 9
 
arorakashish0911
javascript-array
JavaScript-Methods
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Python | pandas.map() - GeeksforGeeks

04 Jul, 2018
pandas.map() is used to map values from two series having one column same. For mapping two series, the last column of the first series should be same as index column of the second series, also the values should be unique.
Syntax:
Series.map(arg, na_action=None)
Parameters:
arg : function, dict, or Series
na_action : {None, ‘ignore’} If ‘ignore’, propagate NA values, without passing them to the mapping correspondence. na_action checks the NA value and ignores it while mapping in case of ‘ignore’
Return type:
Pandas Series with same as index as caller
Example #1:In the following example, two series are made from same data. pokemon_names column and pokemon_types index column are same and hence Pandas.map() matches the rest of two columns and returns a new series.
Note:-> 2nd column of caller of map function must be same as index column of passed series.-> The values of common column must be unique too.
import pandas as pd  #reading csv filespokemon_names = pd.read_csv("pokemon.csv", usecols = ["Pokemon"],                                                  squeeze = True)  #usecol is used to use selected columns#index_col is used to make passed column as indexpokemon_types = pd.read_csv("pokemon.csv", index_col = "Pokemon",                                                  squeeze = True)  #using pandas map functionnew=pokemon_names.map(pokemon_types)  print (new)
Output:
Example #2:
This function works only with Series. Passing a data frame would give an Attribute error. Passing series with different length will give the output series of length same as the caller.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
atan2() function in Python - GeeksforGeeks

14 Mar, 2018
atan2(y, x) returns value of atan(y/x) in radians. The atan2() method returns a numeric value between – and  representing the angle  of a (x, y) point and positive x-axis.
Syntax :
atan2(y, x)
Parameter :
(y, x) - Both must be a numeric value.
Returns :
Returns atan(y / x), in radians.
The double value is  from polar coordinate (r, theta). 
TypeError :
Returns a TypeError if anything other than float is passed. 
 
Code #1 :
# Python3 program to demonstrate# the atan2() method   # imports math import math  # prints the theta value of# two negative co-ordinates theta1 = math.atan2(-0.9, -0.9) print("atan2(-0.9, -0.9) : ", theta1)   # prints the theta value of# two positive co-ordinates theta2 = math.atan2(1.2, 1.5) print("atan2(1.2, 1.5) : ", theta2)   # prints the theta value of one# positive and one negative co-ordinates theta3 = math.atan2(1.2, -1.5) print("atan2(1.2, -1.5):", theta3)
Output :
atan2(-0.5, -0.5): -2.356194490192345
atan2(1.2, 1.5): 0.6747409422235526
atan2(1.2, -1.5): 2.4668517113662407

 Code #2 :
# Python3 program to demonstrate the atan() method   # imports math import math  # list containing x and y coordinates y = [1, 2, 3, 4] x = [6, 3, 7, 8]   # traversing in range to get theta # for all y and x co-ordinates for i in range(len(x)):    theta = math.atan2(y[i], x[i])     print(theta) 
Output :
0.16514867741462683
0.5880026035475675
0.40489178628508343
0.4636476090008061

 Code #3 : Program demonstrating the error
# Python3 program to demonstrate the  # TypeError in atan() method   # importing math import math  y, x = 3, 6  # when integer values are passed # it returns a TypeErrortheta = math.atan2([y], [x]) print(theta)
Output :
Traceback (most recent call last):
  File "/home/622586ab389561bcdbfff258aca01e65.py", line 9, in 
    theta = math.atan2([y],[x]) 
TypeError: a float is required

 Practical Application :This function is used to find the slope in radians when Y and X co-ordinates are given.
Code #4 :
# Let's find the slope when X# and Y co-ordinates are given   # imports math import math  # X and Y are co-ordinatesX = 2; Y = 2   # slope in radians theta1 = math.atan2(Y, X)   # print the Slope in radiansprint(theta1)
Output :
0.7853981633974483

Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Python script that is executed every 5 minutes - GeeksforGeeks

13 Jul, 2021
In this article, we will discuss how to execute a Python script after every 5 minutes. Let’s discuss some methods for doing this.
Method 1: Using Time Module
We can create a Python script that will be executed at every particular time. We will pass the given interval in the time.sleep() function and make while loop is true. The function will sleep for the given time interval. After that, it will start executing.
Code:
Python3
import time    while(True):    print('hello geek!')    time.sleep(300)
Output:
Method 2: Using Schedule Module
With the help of the Schedule module, we can make a python script that will be executed in every given particular time interval.with this function schedule.every(5).minutes.do(func) function will call every 5 minutes. And with the help schedule.run_pending() we will check whether the scheduler has a pending function to run or not.
Code:
Python3
import scheduleimport time  def func():    print("Geeksforgeeks")  schedule.every(1).minutes.do(func)  while True:    schedule.run_pending()    time.sleep(1)
Output:
Method 3: Using crontab
The Cron job utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. Once can schedule scripts to be executed periodically.
Below is the sample program for demonstration:
Python3
#! /usr/bin/python3  def main():    print("Hello Geeks")  if __name__ == '__main__':    main()
The crontab scheduling expression has the following parts:
To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:
crontab -e
You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:
*/5 * * * * /home/$(USER)/my_script.py
After running the scripts our python scripts executed in every 5 minutes.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Encrypting a string using Caesar Cipher in JavaScript

The Caesar Cipher algorithm is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet.
For example
With a left shift of 3, D would be replaced by A, E would become B, and so on. We are required to write a JavaScript function that takes in a string to be encrypted as the first argument and a shift amount as the second argument.
The shift amount can be a positive or negative integer (a positive shift signifies a shift to right whereas negative to left).
Following is the code −
const str = 'thisIsAString';
const getMap = (legend, shift) => {
   return legend.reduce((charsMap, currentChar, charIndex) => {
      const copy = { ...charsMap };
      let ind = (charIndex + shift) % legend.length;
      if (ind < 0) {
         ind += legend.length;
      };
      copy[currentChar] = legend[ind];
      return copy;
   }, {});
};
const encrypt = (str, shift = 0) => {
   const legend = 'abcdefghijklmnopqrstuvwxyz'.split('');
   const map = getMap(legend, shift);
   return str
   .toLowerCase()
   .split('')
   .map(char => map[char] || char)
   .join('');
};
console.log(encrypt(str, 6));
Following is the output on console −
znoyoygyzxotm
PHP - Conditional Operator Example

Try following example to understand the conditional operator. Copy and paste following PHP program in test.php file and keep it in your PHP Server's document root and browse it using any browser.
<html>
   
   <head>
      <title>Arithmetical Operators</title>
   </head>
   
   <body>
   
      <?php
         $a = 10;
         $b = 20;
         
         /* If condition is true then assign a to result otheriwse b */
         $result = ($a > $b ) ? $a :$b;
         
         echo "TEST1 : Value of result is $result<br/>";
         
         /* If condition is true then assign a to result otheriwse b */
         $result = ($a < $b ) ? $a :$b;
         
         echo "TEST2 : Value of result is $result<br/>";
      ?>
   
   </body>
</html>
This will produce the following result −
TEST1 : Value of result is 20
TEST2 : Value of result is 10


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to select last row in MySQL?

To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1. Let us first create a table and insert some records with the help of insert command.
The query is as follows.
mysql> create table getLastRecord
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.61 sec)
After creating the above table, we will insert records with the help of insert command.
mysql> insert into getLastRecord values(1,'John');
Query OK, 1 row affected (0.13 sec)

mysql> insert into getLastRecord values(2,'Ramit');
Query OK, 1 row affected (0.22 sec)

mysql> insert into getLastRecord values(3,'Johnson');
Query OK, 1 row affected (0.13 sec)

mysql> insert into getLastRecord values(4,'Carol');
Query OK, 1 row affected (0.79 sec)
Display all records with the help of select statement.
mysql> select *from getLastRecord;
The following is the output.
+------+---------+
| Id   | Name    |
+------+---------+
|    1 | John    |
|    2 | Ramit   |
|    3 | Johnson |
|    4 | Carol   |
+------+---------+
4 rows in set (0.00 sec)

Our lats record is with id 4 and Name ‘Carol’. To get the last record, the following is the query.
mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1;
The following is the output.
 
+------+-------+
| Id   | Name  |
+------+-------+
|    4 | Carol |
+------+-------+
1 row in set (0.00 sec)

The above output shows that we have fetched the last record, with Id 4 and Name Carol.
How to convert a matrix to binary matrix in R?

To convert a matrix to binary matrix, we can use as.matrix function and converting the matrix to logical matrix then adding 0 to the values greater than 0. For example, if we have a matrix called M then it can be converted to a binary matrix using the command −
as.matrix((M<0)+0)
Check out the below examples and try to do it in breaks to understand how it works.
 Live Demo
M1<-matrix(rpois(40,1),ncol=2)
M1
    [,1] [,2]
[1,]  0   1
[2,]  1   1
[3,]  4   1
[4,]  1   0
[5,]  1   1
[6,]  3   3
[7,]  3   0
[8,]  2   2
[9,]  1   1
[10,] 2   0
[11,] 2   0
[12,] 0   0
[13,] 1   0
[14,] 0   2
[15,] 2   1
[16,] 3   2
[17,] 2   1
[18,] 0   1
[19,] 1   2
[20,] 3   0
as.matrix((M1>0)+0)
    [,1] [,2]
[1,]  0   1
[2,]  1   1
[3,]  1   1
[4,]  1   0
[5,]  1   1
[6,]  1   1
[7,]  1   0
[8,]  1   1
[9,]  1   1
[10,] 1   0
[11,] 1   0
[12,] 0   0
[13,] 1   0
[14,] 0   1
[15,] 1   1
[16,] 1   1
[17,] 1   1
[18,] 0   1
[19,] 1   1
[20,] 1   0
 Live Demo
M2<-matrix(rpois(80,2),ncol=4)
M2
    [,1] [,2] [,3] [,4]
[1,]  2   2    2    4
[2,]  4   5    1    0
[3,]  1   2    2    4
[4,]  2   0    1    2
[5,]  4   1    2    3
[6,]  3   0    1    0
[7,]  0   2    3    0
[8,]  2   1    2    0
[9,]  2   0    2    1
[10,] 2   3    1    2
[11,] 2   4    1    3
[12,] 1   3    0    2
[13,] 2   2    3    2
[14,] 0   2    1    1
[15,] 4   2    1    5
[16,] 1   3    1    1
[17,] 4   0    0    1
[18,] 3   3    3    1
[19,] 1   0    0    3
[20,] 3   0    0    0
as.matrix((M2>0)+0)
    [,1] [,2] [,3] [,4]
[1,]  1   1    1    1
[2,]  1   1    1    0
[3,]  1   1    1    1
[4,]  1   0    1    1
[5,]  1   1    1    1
[6,]  1   0    1    0
[7,]  0   1    1    0
[8,]  1   1    1    0
[9,]  1   0    1    1
[10,] 1   1    1    1
[11,] 1   1    1    1
[12,] 1   1    0    1
[13,] 1   1    1    1
[14,] 0   1    1    1
[15,] 1   1    1    1
[16,] 1   1    1    1
[17,] 1   0    0    1
[18,] 1   1    1    1
[19,] 1   0    0    1
[20,] 1   0    0    0
How to disable JCheckBox if not checked in Java

The following is an example to disable JCheckBox if not checked in Java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(String[] args) {
      JCheckBox checkBox = new JCheckBox("Demo", true);
      checkBox.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (checkBox.isEnabled())
               checkBox.setEnabled(false);
            else
               checkBox.setEnabled(true);
         }
      });
      JOptionPane.showMessageDialog(null, checkBox);
   }
}
Now, when you will uncheck the above checkbox, it will get disabled:
How to set Google Chrome in WebDriver?

We can set Google Chrome in Selenium. Java JDK, Eclipse and Selenium
webdriver should be configured in the system before setting up the Chrome
browser.
Steps to set Google Chrome are −
Navigate to the link: https://chromedriver.chromium.org/downloads.
Navigate to the link: https://chromedriver.chromium.org/downloads.
Select the Chrome driver link which matches with the Chrome browser in the local system.
Select the Chrome driver link which matches with the Chrome browser in the local system.
Then, we have to select the Chrome driver link which is compatible with the operating system we are using.
Then, we have to select the Chrome driver link which is compatible with the operating system we are using.
A zip file gets downloaded. Extract and save the chromedriver.exe file in a location.
A zip file gets downloaded. Extract and save the chromedriver.exe file in a location.
We can configure the chromedriver.exe file in the following ways −
By setting the System Properties in the Environment Variables. Go to the Start and type System and click on it. Select the Advanced System Settings. Then click on the Environment Variables from the Advanced. From the System Variables, select Path and click on Edit. Then click on New. Add the chromedriver.exe path and proceed.
By setting the System Properties in the Environment Variables. Go to the Start and type System and click on it. Select the Advanced System Settings. Then click on the Environment Variables from the Advanced. From the System Variables, select Path and click on Edit. Then click on New. Add the chromedriver.exe path and proceed.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeSetup{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
   }
}
By setting the System Properties in the script. By adding the browser type and chromedriver.exe path as parameters to the System.setProperty method in the code.
By setting the System Properties in the script. By adding the browser type and chromedriver.exe path as parameters to the System.setProperty method in the code.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SetChromeBrw{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      // browser type and chromedrover.exe path as parameters
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      driver.get("https://www.tutorialspoint.com/index.htm");
   }
}
Translating HTML5 canvas

Use the translate() method to translate canvas. HTML5 canvas provides a translate(x, y) method which is used to move the canvas and its origin to a different point in the grid.
Here argument x is the amount the canvas is moved to the left or right, and y is the amount it's moved up or down
<!DOCTYPE HTML>
<html>
   <head>
      <style>
         #test {
            width:100px;
            height:100px;
            margin:0px auto;
         }
      </style>
     
      <script>
         function drawShape(){
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
           
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext){
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               ctx.fillRect(0,0,300,300);
               for (i = 0; i < 3; i++) {
                  for (j = 0; j < 3; j++) {
                     ctx.save();
                     ctx.strokeStyle = "#FF0066";
                     ctx.translate(50+j*100,50+i*100);
                     drawSpirograph(ctx,10*(j+3)/(j+2),-2*(i+3)/(i+1),10);
                     ctx.restore();
                  }
               }
            } else {
              alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
         
         function drawSpirograph(ctx,R,r,O){
            var x1 = R-O;
            var y1 = 0;
            var i = 1;
            ctx.beginPath();
            ctx.moveTo(x1,y1);
            do {
            if (i>20000) break;
            var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72));
            var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72));
            ctx.lineTo(x2,y2);
            x1 = x2;
            y1 = y2;
            i++;
            } while (x2 != R-O && y2 != 0 );
            ctx.stroke();
         }
      </script>
   </head>

   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas" width = "400" height = "400"></canvas>
   </body>
</html>
How to retrieve cookies in  Python CGI Programming?

It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form −
key1 = value1;key2 = value2;key3 = value3....
Here is an example of how to retrieve cookies.
#!/usr/bin/python
# Import modules for CGI handling
from os import environ
import cgi, cgitb
if environ.has_key('HTTP_COOKIE'):
   for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
      (key, value ) = split(cookie, '=');
      if key == "UserID":
         user_id = value
      if key == "Password":
         password = value
print "User ID  = %s" % user_id
print "Password = %s" % password
This produces the following result for the cookies set by above script −
User ID = XYZ
Password = XYZ123
Matplotlib.axes.Axes.get_images() in Python - GeeksforGeeks

27 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.get_images() function in axes module of matplotlib library is used to return a list of Axes images contained by the Axes
Syntax: Axes.get_images(self)
Parameters: This method does not accept any parameters.
Returns: This method return a list of Axes images contained by the Axes.
Below examples illustrate the matplotlib.axes.Axes.get_images() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport matplotlib.cbook as cbook         # image used is # https://media.geeksforgeeks.org/# wp-content/uploads/20200402214740/geek.jpgwith cbook.get_sample_data('geek.jpg') as image_file:    image = plt.imread(image_file)  fig, ax = plt.subplots()im = ax.imshow(image)  patch = patches.Rectangle((0, 0), 260, 200,                          transform = ax.transData)im.set_clip_path(patch)  print("List of the child Artists of this Artist \n",      *list(ax.get_images()), sep ="\n")  fig.suptitle('matplotlib.axes.Axes.get_images() \function Example', fontweight ="bold")  plt.show()
Output: 
List of the Axes images contained by the Axes

AxesImage(80, 52.8;496x369.6)

Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm      dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y)   extent = np.min(x), np.max(x), np.min(y), np.max(y)    fig, ax = plt.subplots()   Z1 = np.add.outer(range(8), range(8)) % 2ax.imshow(Z1, cmap ="binary_r",          interpolation ='nearest',          extent = extent, alpha = 1)   def geeks(x, y):    return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))   Z2 = geeks(X, Y)   ax.imshow(Z2, cmap ="Greens", alpha = 0.7,          interpolation ='bilinear',          extent = extent)  print("List of the Axes images contained by the Axes \n",      *list(ax.get_images()), sep ="\n")  fig.suptitle('matplotlib.axes.Axes.get_images() function\ Example', fontweight ="bold")plt.show()
Output:
 
List of the Axes images contained by the Axes 

AxesImage(80, 52.8;496x369.6)
AxesImage(80, 52.8;496x369.6)
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
C program to create a Rocket using Graphics - GeeksforGeeks

01 Apr, 2021
In this article, we will discuss how to draw the Rocket using Graphics.
Approach:
Draw a straight line using the line() function that will act as the Ground Outline.
Below the above line drawn, fill it with the color green using two functions setfillstyle() and floodfill().
Create a rectangle using the rectangle() function and color it brown that will act as the rocket Body.
Create the total four triangles by using the line() function which will act as the wing of the rocket to make it appear more attractive.Among them, two will be situated at the two sides of the upper part of the rocket & the lower part of the rocket.Color all the wings with blue color.
Among them, two will be situated at the two sides of the upper part of the rocket & the lower part of the rocket.
Color all the wings with blue color.
Create a triangle using the line() that will act as the head of the rocket. and color it white.
Below is the implementation of the above approach:
C
// C program for the above approach  #include <conio.h>#include <graphics.h>#include <stdio.h>  // Driver Codevoid main(){    // Initialize of gdriver with    // DETECT macros    initgraph(&gd, &gm, "C:\\turboc3\\bgi");      setfillstyle(SOLID_FILL, BROWN);    rectangle(650, 450, 700, 650);      // Rocket body    floodfill(652, 648, 15);    line(0, 650, 1500, 650);      // Land outline    setfillstyle(SOLID_FILL, WHITE);    line(650, 450, 700, 450);    line(650, 450, 675, 350);    line(675, 350, 700, 450);      // Rocket head    floodfill(652, 448, 15);    setfillstyle(SOLID_FILL, BLUE);    line(650, 500, 650, 450);    line(625, 500, 650, 500);    line(625, 500, 650, 450);      // Rocket left up wing    floodfill(648, 498, 15);    setfillstyle(SOLID_FILL, BLUE);    line(700, 450, 700, 500);    line(725, 500, 700, 500);    line(700, 450, 725, 500);      // Rocket right up wing    floodfill(702, 498, 15);    setfillstyle(SOLID_FILL, BLUE);    line(625, 650, 650, 650);    line(650, 575, 650, 650);    line(625, 650, 650, 575);      // Rocket left down wing    floodfill(627, 648, 15);    setfillstyle(SOLID_FILL, GREEN);    floodfill(627, 698, 15);      setfillstyle(SOLID_FILL, BLUE);    line(725, 650, 700, 650);    line(700, 575, 700, 650);    line(725, 650, 700, 575);      // Rocket right down wing    floodfill(702, 648, 15);    line(0, 650, 1500, 650);      // Draw the land with green color    setfillstyle(SOLID_FILL, GREEN);    floodfill(627, 698, 15);    getch();      // Close the initialized gdriver    closegraph();}
Output:
c-graphics
computer-graphics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
Header files in C/C++ and its uses
C Program to read contents of Whole File
Basics of File Handling in C
mapfile Command in Linux With Examples - GeeksforGeeks

09 Apr, 2021

mapfile also called (read array) is a command of the Bash shell used to read arrays. It reads lines from the standard input into an array variable. Also, mapfile must read from substitution (< <) and not from a pipe. Also, mapfile is faster and more convenient when compared to a read loop. It returns 1 or 0 depending on whether the command was successful or not. If no array name is not specified, the default variable MAPFILE is used as the target array variable.
Syntax: mapfile [array]
Alternatively, we can use read array [arrayname] instead of mapfile.
Example 1. Reading an array from a file:
$ mapfile MYFILE < example.txt
$ echo ${MYFILE[@]}
$ echo ${MYFILE[0]}
Output:
Example 2. Capture the output into an array:
$ mapfile GEEKSFORGEEKS < <(printf "Item 1\nItem 2\nItem 3\n")
$ echo  ${GEEKSFORGEEKS[@]}
Here, Item1, Item2, and Item 3 have been stored in the array GEEKSFORGEEKS.
Output:
Example 3. Strip newlines and store item using -t:
$ mapfile -t GEEKSFORGEEKS< <(printf "Item 1\nItem 2\nItem 3\n")
$ printf "%s\n" "${GEEKSFORGEEKS[@]}"
Output:
Example 4. Read the specified number of lines using -n:
$ mapfile -n 2 GEEKSFORGEEKS < example.txt
$ echo  ${GEEKSFORGEEKS[@]}
It reads at most 2 lines. If 0 is specified then all lines are considered.
Output:

linux-command


Shell


Linux-Unix

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
lockfile - Unix, Linux Command

If the number of
retries expires before all files have been created, lockfile returns failure and
removes all the files it created up till that point.


Using lockfile as the condition of a loop in a shell script can be done
easily by using the
-! flag to invert the exit status.  To prevent infinite loops, failures
for any reason other than the lockfile already existing are not
inverted to success but rather are still returned as failures.


All flags can be specified anywhere on the command line, they will be
processed when encountered.  The command line is simply parsed from
left to right.


All files created by lockfile will be read-only, and therefore
will have to be removed with
rm -f. 

If you specify a
locktimeout then a lockfile will be removed by force after locktimeout seconds have
passed since the lockfile was last modified/created (most likely by some
other program that unexpectedly died a long time ago, and hence could not clean
up any leftover lockfiles).  Lockfile is clock skew immune.  After a lockfile
has been removed by force, a suspension of
suspend seconds (defaults to 16) is taken into account, in order to prevent
the inadvertent immediate removal of any newly created lockfile by another
program (compare
SUSPEND in
procmail(1)).


...
lockfile important.lock
...
access_"important"_to_your_hearts_content
...
rm -f important.lock
...


Multiple
-! flags will toggle the return status.


Since flags can occur anywhere on the command line, any filename starting
with a ’-’ has to be preceded by ’./’.


The number of
retries will not be reset when any following file is being created (i.e., they are
simply used up).  It can, however, be reset by specifying
-rnewretries after every file on the command line.


Although files with any name can be used as lockfiles, it is common practice
to use the extension ‘.lock’ to lock mailfolders (it is appended to the
mailfolder name).  In case one does not want to have to worry about too long
filenames and does not have to conform to any other lockfilename convention,
then an excellent way to generate a lockfilename corresponding to some already
existing file is by taking the prefix ‘lock.’ and appending the i-node number
of the file which is to be locked.

<procmail-users@procmail.org>

for submitting questions/answers.

for subscription requests.



If you would like to stay informed about new versions and official patches send
a subscription request to


procmail-announce-request@procmail.org

<srb@cuci.nl>

<guenther@sendmail.com>


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to display negative labels below bars in barplot using ggplot2 in R?

Be default, the labels on the plot are represented without sign in a barplot that is created by using ggplot2 but we might want to display the sign of the labels especially in cases where we have some negative values. This can be done with the help of geom_text function of ggplot2 package as shown in the below example.
Consider the below data frame −
 Live Demo
x<-c("A","B","C","D")
y<-c(21,-5,-20,10)
df<-data.frame(x,y)
df
   x   y
1  A   21
2  B  -5
3  C  -20
4  D   10
Loading ggplot2 package and creating bar chart for data in df −
library(ggplot2)
ggplot(df,aes(x,y))+geom_bar(stat="identity")
Creating bar chart for data in df with negative labels displayed with negative sign −
ggplot(df,aes(x,y))+geom_bar(stat="identity")+geom_text(aes(y=y+sign(y),label=y))
What is the best data type to use for currency in C#?

The best datatype to use for currency in C# is decimal. The decimal type is a 128-bit data type suitable for financial and monetary calculations. The decimal type can represent values ranging from 1.0 * 10^-28 to approximately 7.9 * 10^28 with 28-29 significant digits. To initialize a decimal variable, use the suffix m or M.
decimal b = 2.1m;
The below example shows the min and max value of decimal.
 Live Demo
using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         Console.WriteLine($"Deciaml Min Value: {decimal.MinValue}");
         Console.WriteLine($"Deciaml Max Value: {decimal.MaxValue}");
         Console.ReadLine();
      }
   }
}
Deciaml Min Value: -79228162514264337593543950335 Deciaml Max Value: 79228162514264337593543950335
Deciaml Max Value: 79228162514264337593543950335
The finite set of values of type decimal are of the form (-1)^s * c * 10^-e, where the sign s is 0 or 1, the coefficient c is given by 0 <= *c* < 2^96, and the scale e is such that 0 <= e <= 28.The decimal type does not support signed zeros, infinities, or NaN's. A decimal is represented as a 96-bit integer scaled by a power of ten. For decimals with an absolute value less than 1.0m, the value is exact to the 28th decimal place, but no further.
For decimals with an absolute value greater than or equal to 1.0m, the value is exact to 28 or 29 digits. Contrary to the float and double data types, decimal fractional numbers such as 0.1 can be represented exactly in the decimal representation. In the float and double representations, such numbers are often infinite fractions, making those representations more prone to round-off errors.
Decimal type is preferred over float and double because it has more precision and a smaller range than both float and double.
Let us consider an example where US dollar is converted to Indian Rupee.
 Live Demo
using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         decimal usd = 2.5m;
         Console.WriteLine($"USD: {usd}");
         decimal inrOfOneUSD = 75.04m;
         Console.WriteLine($"INR value of one USD: {inrOfOneUSD}");
         decimal inr = usd * inrOfOneUSD;
         Console.WriteLine($"INR value: {inr}");
         Console.ReadLine();
      }
   }
}
The output of the above code is
USD: 2.5
INR value of one USD: 75.04
INR value: 187.600
Highcharts - Pie Chart with Legends

Following is an example of a Pie Chart with Legends.
We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter.
An example of a Pie Chart with Legends is given below.
Let us now see the additional configurations/steps taken.
Configure the series type to be pie based. series.type decides the series type for the chart. Here, the default value is "line".
var series = {
   type: 'pie'
};
Configure the plotOptions to have legends in pie chart using plotOptions.pie.showInLegend attribute.
var plotOptions = {
   pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      
      dataLabels: {
         enabled: false           
      },
      
      showInLegend: true
   }
};
highcharts_pie_legends.htm
<html>
   <head>
      <title>Highcharts Tutorial</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
      <script src = "https://code.highcharts.com/highcharts.js"></script>  
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
      <script language = "JavaScript">
         $(document).ready(function() {
            var chart = {
               plotBackgroundColor: null,
               plotBorderWidth: null,
               plotShadow: false
            };
            var title = {
               text: 'Browser market shares at a specific website, 2014'   
            };      
            var tooltip = {
               pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            };
            var plotOptions = {
               pie: {
                  allowPointSelect: true,
                  cursor: 'pointer',
                  
                  dataLabels: {
                     enabled: false           
                  },
                  
                  showInLegend: true
               }
            };
            var series = [{
               type: 'pie',
               name: 'Browser share',
               data: [
                  ['Firefox',   45.0],
                  ['IE',       26.8],
                  {
                     name: 'Chrome',
                     y: 12.8,
                     sliced: true,
                     selected: true
                  },
                  ['Safari',    8.5],
                  ['Opera',     6.2],
                  ['Others',   0.7]
               ]
            }];     
            var json = {};   
            json.chart = chart; 
            json.title = title;     
            json.tooltip = tooltip;  
            json.series = series;
            json.plotOptions = plotOptions;
            $('#container').highcharts(json);  
         });
      </script>
   </body>
   
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Python VLC MediaPlayer - Getting Current media time - GeeksforGeeks

18 Aug, 2020
In this article we will see how we can get current media time of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. We can get the length of the current media with the help of get_length method.
In order to do this we will use get_time method with the MediaPlayer object
Syntax : media_player.get_time()
Argument : It takes no argument
Return : It returns integer (milleseconds)
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time    # creating vlc media player objectmedia_player = vlc.MediaPlayer()  # media objectmedia = vlc.Media("death_note.mkv")  # setting media to the media playermedia_player.set_media(media)    # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)    # getting current media timevalue = media_player.get_time()  # printing valueprint("Current Media time : ")print(value)
Output :
Current Media time : 
611

Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating vlc media player objectmedia_player = vlc.MediaPlayer()  # media objectmedia = vlc.Media("1mp4.mkv")  # setting media to the media playermedia_player.set_media(media)      # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)    # getting current media timevalue = media_player.get_time()  # printing valueprint("Current Media time : ")print(value)
Output :
Current Media time : 
402

Python vlc-library
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 drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
DoubleStream sum() in Java - GeeksforGeeks

06 Dec, 2018
DoubleStream sum() returns the sum of elements in this stream. This is a special case of a reduction. DoubleStream sum() is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Note : A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers.
Syntax :
double sum()

Return Value : The function returns the sum of elements in this stream.
Note :
If any stream element is a NaN or the sum is at any point a NaN then the sum will be NaN.Elements sorted by increasing absolute magnitude tend to yield more accurate result.
If any stream element is a NaN or the sum is at any point a NaN then the sum will be NaN.
Elements sorted by increasing absolute magnitude tend to yield more accurate result.
Example 1 :
// Java code for DoubleStream.sum() to// find the sum of elements in DoubleStreamimport java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an DoubleStream        DoubleStream stream = DoubleStream.of(2.2, 4.3, 6.4,                                              -2.5, -4.6);          // Using DoubleStream.sum() to find        // sum of elements in DoubleStream        double sumOfElements = stream.sum();          // Displaying the calculated sum        System.out.println(sumOfElements);    }}
5.800000000000001

Example 2 :
// Java code for DoubleStream.sum() to// find the sum of elements// greater than 2.5import java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an DoubleStream        // Using DoubleStream.sum() to find        // sum of elements greater than 2.5        double sumOfElements = DoubleStream.of(2.2, 4.2, 6.4,                                               -2.5, -4.5)                                   .filter(num -> num > 2.5)                                   .sum();          // Displaying the calculated sum        System.out.println(sumOfElements);    }}
10.600000000000001

Java - util package
java-DoubleStream
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
Commonly Asked Java Programming Interview Questions | Set 2
HashMap get() Method in Java
Strings in Java
Determining a pangram string in JavaScript

A pangram is a string that contains every letter of the English alphabet.
We are required to write a JavaScript function that takes in a string as the first and the only argument and determines whether that string is a pangram or not. For the purpose of this problem, we will take only lowercase alphabets into consideration.
The code for this will be −
 Live Demo
const str = 'We promptly judged antique ivory buckles for the next prize';
const isPangram = (str = '') => {
   str = str.toLowerCase();
   const { length } = str;
   const alphabets = 'abcdefghijklmnopqrstuvwxyz';
   const alphaArr = alphabets.split('');
   for(let i = 0; i < length; i++){
      const el = str[i];
      const index = alphaArr.indexOf(el);
      if(index !== -1){
         alphaArr.splice(index, 1);
      };
   };
   return !alphaArr.length;
};
console.log(isPangram(str));
And the output in the console will be −
true