code-rag-bench/online-tutorials huggingface dataset:
Batch Script - Using the SHIFT Operator

One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation.
@echo off
echo %1
echo %2
echo %3
echo %4
echo %5
echo %6
echo %7
echo %8
echo %9
echo %10
If the above code is stored in a file called test.bat and the file is run as
test.bat a b c d e f g h i j

Then following will be the output.
a 
b
c
d
e
f
h
i
a0

As you can see from the above output, the final value which should be shown as ‘j’ is being shown as a0. This is because there is no parameter known as %10.
This limitation can be avoided by using the SHIFT operator. After your batch file handled its first parameter(s) it could SHIFT them (just insert a line with only the command SHIFT), resulting in %1 getting the value B, %2 getting the value C, etcetera, till %9, which now gets the value J. Continue this process until at least %9 is empty.
Let’s look at an example of how to use the SHIFT operator to overcome the limitation of command line arguments.
@ECHO OFF
:Loop

IF "%1"=="" GOTO Continue
   echo %1%
SHIFT
GOTO Loop
:Continue
If the above code is stored in a file called test.bat and the file is run as
test.bat a b c d e f g h i j

Then following will be the output.
a 
b
c
d
e
f
h
i
j

Some characters in the command line are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line −
Commas (",") are replaced by spaces, unless they are part of a string in doublequotes.
Commas (",") are replaced by spaces, unless they are part of a string in doublequotes.
Semicolons (";") are replaced by spaces, unless they are part of a string in doublequotes.
Semicolons (";") are replaced by spaces, unless they are part of a string in doublequotes.
"=" characters are sometimes replaced by spaces, not if they are part of a string in doublequotes.
"=" characters are sometimes replaced by spaces, not if they are part of a string in doublequotes.
The first forward slash ("/") is replaced by a space only if it immediately follows the command, without a leading space.
The first forward slash ("/") is replaced by a space only if it immediately follows the command, without a leading space.
Multiple spaces are replaced by a single space, unless they are part of a string in doublequotes.
Multiple spaces are replaced by a single space, unless they are part of a string in doublequotes.
Tabs are replaced by a single space.
Tabs are replaced by a single space.
Leading spaces before the first command line argument are ignored.
Leading spaces before the first command line argument are ignored.
Trailing spaces after the last command line argument are trimmed.
Trailing spaces after the last command line argument are trimmed.
 Print
 Add Notes
 Bookmark this page
How to access a JavaScript object using its own prototype?

We can able to access the existing object by creating its own prototype using a javascript method called "Object.create()". Using this method we can inherit the properties from the existing properties to the newly created prototype. Let's discuss it in a nutshell.
Object.create(existing obj);
This method takes the existing object and creates its own prototype so that the properties will be inherited from the existing object to the newly created prototype.
In the following example, Initially, an object named "person" is created and the using "Object.create" its own prototype is created and assigned to a variable "newper". Later on, using the prototype the objects of the existing object have been changed and the new properties were displayed as shown in the output.
 Live Demo
<html>
<body>
<script>
   var person = {
      name: "Karthee",
      profession : "Actor",
      industry: "Tamil"
   };
   document.write(person.name);
   document.write("</br>");
   document.write(person.profession);
   document.write("</br>");
   document.write(person.industry);
   document.write("</br>");
   document.write("Using a prototype the properties of the existing object have been 
   changed to the following");
   document.write("</br>");
   var newper = Object.create(person); /// creating prototype
   newper.name = "sachin";
   newper.profession = "crickter";
   newper.industry = "sports";
   document.write(newper.name);
   document.write("</br>");
   document.write(newper.profession);
   document.write("</br>");
   document.write(newper.industry);
</script>
</body>
</html>
Karthee
Actor
Tamil
Using a prototype the properties of the existing object have been changed to the following
sachin
crickter
sports
How to sum the values in the table by month with MySQL?

For this, use EXTRACT(), that would allow you to extract specific month records. For example, to add all the prices in January (irrespective of the year).
Let us first create a −
mysql> create table DemoTable1415
   -> (
   -> ProductPurchaseDate date,
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1415 values('2019-01-12',560);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1415 values('2018-01-14',1060);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1415 values('2017-03-21',780);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1415 values('2016-09-01',800);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1415 values('2019-01-14',100);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select −
mysql> select * from DemoTable1415;
This will produce the following output −
+---------------------+--------------+
| ProductPurchaseDate | ProductPrice |
+---------------------+--------------+
| 2019-01-12          |          560 |
| 2018-01-14          |         1060 |
| 2017-03-21          |          780 |
| 2016-09-01          |          800 |
| 2019-01-14          |          100 |
+---------------------+--------------+
5 rows in set (0.00 sec)
Following is the query to sum the values in the table by month −
mysql> select extract(MONTH from ProductPurchaseDate) as month,sum(ProductPrice) as total_value from DemoTable1415
   -> group by month;
This will produce the following output −
+-------+-------------+
| month | total_value |
+-------+-------------+
|     1 |        1720 |
|     3 |         780 |
|     9 |         800 |
+-------+-------------+
3 rows in set (0.00 sec)
Python Pandas - Timedelta

Timedeltas are differences in times, expressed in difference units, for example, days, hours, minutes, seconds. They can be both positive and negative.
We can create Timedelta objects using various arguments as shown below −
By passing a string literal, we can create a timedelta object.
import pandas as pd

print pd.Timedelta('2 days 2 hours 15 minutes 30 seconds')
Its output is as follows −
2 days 02:15:30

By passing an integer value with the unit, an argument creates a Timedelta object.
import pandas as pd

print pd.Timedelta(6,unit='h')
Its output is as follows −
0 days 06:00:00

Data offsets such as - weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds can also be used in construction.
import pandas as pd

print pd.Timedelta(days=2)
Its output is as follows −
2 days 00:00:00

Using the top-level pd.to_timedelta, you can convert a scalar, array, list, or series from a recognized timedelta format/ value into a Timedelta type. It will construct Series if the input is a Series, a scalar if the input is scalar-like, otherwise will output a TimedeltaIndex.
import pandas as pd

print pd.Timedelta(days=2)
Its output is as follows −
2 days 00:00:00

You can operate on Series/ DataFrames and construct timedelta64[ns] Series through subtraction operations on datetime64[ns] Series, or Timestamps.
Let us now create a DataFrame with Timedelta and datetime objects and perform some arithmetic operations on it −
import pandas as pd

s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D'))
td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ])
df = pd.DataFrame(dict(A = s, B = td))

print df
Its output is as follows −
            A      B
0  2012-01-01 0 days
1  2012-01-02 1 days
2  2012-01-03 2 days

import pandas as pd

s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D'))
td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ])
df = pd.DataFrame(dict(A = s, B = td))
df['C']=df['A']+df['B']

print df
Its output is as follows −
           A      B          C
0 2012-01-01 0 days 2012-01-01
1 2012-01-02 1 days 2012-01-03
2 2012-01-03 2 days 2012-01-05

import pandas as pd

s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D'))
td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ])
df = pd.DataFrame(dict(A = s, B = td))
df['C']=df['A']+df['B']
df['D']=df['C']+df['B']

print df
Its output is as follows −
           A      B          C          D
0 2012-01-01 0 days 2012-01-01 2012-01-01
1 2012-01-02 1 days 2012-01-03 2012-01-04
2 2012-01-03 2 days 2012-01-05 2012-01-07


    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
Calculate the Cumulative Maxima of a Vector in R Programming - cummax() Function - GeeksforGeeks

12 Apr, 2022
The cumulative maxima is the max value of elements 1 through l for an element l of the given variables.
cummax() function in R Language is used to calculate the cumulative maxima of the values of vector passed as arguments.
Syntax: cummax(x) 
Parameters: 
x: numeric object
Example 1: 
Python3
# R program to cumulative maxima # Calling cummax() functioncummax(6:2)cummax(-2:-6)cummax(3.8:1.2)
Output:
[1] 6 6 6 6 6
[1] -2 -2 -2 -2 -2
[1] 3.8 3.8 3.8
Example 2: 
Python3
# R program to cumulative maxima # Creating vectorsx1 <- c(5, 3, 2, 6, 3, 4)x2 <- c(-4, 6, 3) # Calling cummax() functioncummax(x1)cummax(x2)
Output:
[1] 5 5 5 6 6 6
[1] -4  6  6
Since, the maxima is calculated for the values in decreasing order and hence the above code shows two cumulative values for vectors.
aarushirohitkumar
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
Opening and Closing Tabs Using Selenium - GeeksforGeeks

24 Jan, 2021
Selenium is a tool which is used to automate browser instructions. It is utilitarian for all programs, deals with all significant OS and its contents are written in different languages i.e Python, Java, C# etc. 
In this article, we are using Python as the language and Chrome as the WebDriver.
Python selenium module can be installed using the below command:
pip install selenium
Chrome Driver can be downloaded from Chrome Driver (version == 87.0.4).
In order to open a tab, a web driver is needed. In this, we are using Chrome Webdriver. After providing the driver path, use .get(URL) method to open a tab.
Python3
# Import modulefrom selenium import webdriver  # Create objectdriver = webdriver.Chrome()  # Assign URLurl = "https://www.geeksforgeeks.org/"  # Fetching the Urldriver.get(url)
Output:
In order to open a new tab, a javascript function to open a tab in a new window can be used. In order to use the functionality of javascript .executescript() method of selenium can be used. After executing the script we can switch to the window using .switch_to_window() method.
Python3
# import modulefrom selenium import webdriver  # Create objectdriver = webdriver.Chrome()  # Assign URLurl = "https://www.geeksforgeeks.org/"  # New Urlnew_url = "https://www.facebook.com/"  # Opening first urldriver.get(url)  # Open a new windowdriver.execute_script("window.open('');")  # Switch to the new window and open new URLdriver.switch_to.window(driver.window_handles[1])driver.get(new_url)
Output:
In order to close the tab, .close() method is used.
Python3
# Import modulefrom selenium import webdriver  # Create objectdriver = webdriver.Chrome()  # Fetching the Urlurl = "https://www.geeksforgeeks.org/"  # Opening first urldriver.get(url)  # Closing the tabdriver.close()
Output:
In the case of multiple tabs, after closing the tab using .close() method we can switch to the tab which is not closed using .switch_to_window() method.
Python3
# Import modulefrom selenium import webdriver  # Create objectdriver = webdriver.Chrome()  # Fetching the Urlurl = "https://www.geeksforgeeks.org/"  # New Urlnew_url = "https://www.facebook.com/"  # Opening first urldriver.get(url)  # Open a new windowdriver.execute_script("window.open('');")  # Switch to the new window and open new URLdriver.switch_to.window(driver.window_handles[1])driver.get(new_url)  # Closing new_url tabdriver.close()  # Switching to old tabdriver.switch_to.window(driver.window_handles[0])
Output:
Picked
Python-selenium
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Importing Kaggle dataset into google colaboratory - GeeksforGeeks

16 Jul, 2020
While building a Deep Learning model, the first task is to import datasets online and this task proves to be very hectic sometimes.We can easily import Kaggle datasets in just a few steps:Code: Importing CIFAR 10 dataset
!pip install kaggle
Now go to your Kaggle account and create new API token from my account section, a kaggle.json file will be downloaded in your PC.Code:
from google.colab import filesfiles.upload()
Code: Uploading the kaggle.json file
!mkdir -p ~/.kaggle!cp kaggle.json ~/.kaggle/!chmod 600 ~/.kaggle/kaggle.json
Copy the URL of your dataset and paste it in another cell.
Code: To unzip the uploaded dataset.
from zipfile import Zipfilefile_name=("cifar10-preprocessed.zip")with Zipfile(file_name,'r') as zip:             zip.extractall()             print("done")
Code:
'./get_CIFAR-10.sh'import tensorflow as tf  (x_train,y_train),(x_test,y_test) = tf.keras.cifar10.load_data()
Now your training and test set is ready to be used.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
LocalDate isBefore() method in Java with Examples - GeeksforGeeks

19 Nov, 2020
The isBefore() method of LocalDate class in Java checks if this date is before the specified date.
Syntax: 
public boolean isBefore(ChronoLocalDate date2)

Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null. 
Return Value: The function returns true if this date is before the specified date.
Below programs illustrate the isBefore() method of LocalDate in Java:
Program 1:  
Java
// Program to illustrate the isBefore() method import java.util.*;import java.time.*; public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");        // Parses the second date        LocalDate dt2 = LocalDate.parse("2017-11-27");         // Checks        System.out.println(dt1.isBefore(dt2));    }}
false







 
Program 2: 
Java
// Program to illustrate the isBefore() method import java.util.*;import java.time.*; public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");        // Parses the second date        LocalDate dt2 = LocalDate.parse("2019-11-27");         // Checks        System.out.println(dt1.isBefore(dt2));    }}
true







 
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#isBefore(java.time.chrono.ChronoLocalDate) 
arorakashish0911
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Initializing a List in Java
Loc and iLoc Functions in Pandas. How to access a slice of a dataframe in... | by Sohail Hosseini | Towards Data Science

The Loc and iLoc functions in Pandas are used to slice a dataset. In order to apply these functions, I used the titanic dataset available here. This is Titanic ML completion from Kaggle and it is mainly used for beginners to create a model that predicts which passengers survived during the Titanic shipwreck. First, lets briefly look at the dataset to see how many observations and columns it has.
titanic.head()titanic.info()
This function is primarily label based, but also is used with a boolean array when we create statements. If we want to look at only rows for male customers here I would be able to use pandas.DataFrame.loc used for locating with labels.
titanic.loc[titanic[‘Sex’]==’male’]
It provides me with a list of all male Passengers. We can do the same process for using every customer.
pandas.DataFrame.loc is used for accessing multiple columns. For instance, if I want to locate all male Passengers and ‘S’ (“Southampton”) for Embarked, I can create two conditions to give me a slice of the dataframe.
titanic.loc[(titanic['Sex']=='male') & (titanic['Embarked']=='S')].head()
It is important to use .loc function with labels when we are using columns. It is also possible if they are integer index to use.
The .iloc function is integer position based but it could also be used with a boolean array. If I want to locate a cell of the dataset, I can write down:
titanic.iloc[0,0]
This command gives the element at row = 0, and column =0. I can also extract a slice of the dataset.
titanic.iloc[0:4,2:5]
In this case, it provides us rows zero to three and columns two to four.
The main purpose of using .loc and iloc is slicing of dataframe in Pandas. Function .loc is primarily used for label indexing and .iloc function is mainly applied for integer indexing.
I have also talked about another built-in function in Pandas named .merge() in here if you are interested.
All the codes used in this article can be accessed from my GitHub. I look forward to hearing feedback or questions.
How to Convert Octal to Binary?


Octal number is one of the number systems which has value of base is 8, that means there only 8 symbols − 0, 1, 2, 3, 4, 5, 6, and 7. Whereas Binary number is most familiar number system to the digital systems, networking, and computer professionals. It is base 2 which has only 2 symbols − 0 and 1, these digits can be represented by off and on respectively.
There are various direct or indirect methods to convert a octal number into binary number. In an indirect method, you need to convert an octal number into other number system (e.g., decimal or hexadecimal), then you can convert into binary number by converting each digit into binary number from hexadecimal system and using conversion system from decimal to binary number.
Example − Convert octal number 205 into binary number.
First convert it into decimal or hexadecimal number,
= (205)8
= (2x82+0x81+5x80)8
or (010 000 101)2
Because base of octal and hexadecimal are 8 and 16 respectively.
= (133)10
or (0 1000 0101)2
= (133)10 or (85)16
Then convert it into binary number by converting each digit.
= (1x27+0x26+0x25+0x24+0x23+1x22+0x21+1x20)2
or (1000 0101)2
= (10000101)2
However, there is a simple direct method to convert an octal number to binary number. Since there are only 8 symbols (i.e., 0, 1, 2, 3, 4, 5, 6, and 7) in octal representation system and its base (i.e., 8) is equivalent of 23=8. So, you can represent each digit of octal in group of 3 bits in binary number.
This method is simple and also works as reverse of Binary to Octal Conversion. The algorithm is explained as following below.
Take Octal number as input
Convert each digit of octal into binary.
That will be output as binary number.
Example-1 Convert octal number 540 into binary number.
According to above algorithm, equivalent binary number will be,
= (540)8
= (101 100 000)2
= (101100000)2
This is very simple conversion, you can use for mixed (integer with fractional) octal number as well.
Example-2 − Convert octal number 352.563 into binary number.
According to above algorithm, equivalent binary number will be,
= (352.563)8
= (011 101 010 . 101 110 011)2
= (011101010.101110011)2
numpy.cbrt() in Python - GeeksforGeeks

18 Nov, 2020
This mathematical function helps user to calculate cube root of x for all x being the array elements.Syntax:
numpy.cbrt(arr, out = None, ufunc ‘cbrt’) : 
Parameters :
arr  : [array_like] Input array or object
        whose elements, we need to square.

Return :
An array with cube root of x for all x i.e. array elements 

 Code #1 : Working
# Python program explaining# cbrt () function   import numpy as np   arr1 = [1, 27000, 64, -1000]print ("cbrt Value of arr1 : \n", np.cbrt(arr1))   arr2 = [1024 ,-128]print ("\ncbrt Value of arr2 : ", np.cbrt(arr2))
Output :
cbrt Value of arr1 : 
 [  1.  30.   4. -10.]

cbrt Value of arr2 :  [ 10.0793684  -5.0396842]

 Code #2 : Working with complex numbers
# Python program explaining# cbrt () function   import numpy as np   a = 4 + 3jprint("cbrt(4 + 3j) : ", np.cbrt(a))   b = 16 + 13jprint("\ncbrt value(16 + 13j) : ", np.cbrt(b))
Output :
TypeError: ufunc 'cbrt' not supported for the input types,
and the inputs could not be safely coerced to any supported
types according to the casting rule ''safe''
 Code #3 : Graphical representation
# Python program explaining# cbrt () function   import numpy as npimport matplotlib.pyplot as plt   a = np.linspace(start = -5, stop = 150,                num = 10, endpoint = True)                   print("Graphical Representation : \n", np.cbrt(a))   plt.title("blue : with cbrt\nred : without cbrt")plt.plot(a, np.cbrt(a))   plt.scatter(a, a, color = 'red')plt.show()
Output :
Graphical Representation : 
 [-1.70997595  2.30347441  3.08793243  3.60027433  3.99768384  4.3287262
  4.61565763  4.87076238  5.10162421  5.31329285]
References :https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.cbrt.html.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
Tryit Editor v3.7

Tryit: Styling form buttons
Python Pandas - Fill NaN with Polynomial Interpolation

To fill NaN with Polynomial Interpolation, use the interpolate() method on the Pandas series. With that, set the “method” parameter to “polynomial”.
At first, import the required libraries −
import pandas as pd
import numpy as np
Create a Pandas series with some NaN values. We have set the NaN using the numpy np.nan −
d = pd.Series([10, 20, np.nan, 65, 75, 85, np.nan, 100])

Find polynomial interpolation using the method parameter of the interpolate() method −
d.interpolate(method='polynomial', order=2)
Following is the code −
import pandas as pd
import numpy as np

# pandas series
d = pd.Series([10, 20, np.nan, 65, 75, 85, np.nan, 100])

print"Series...\n",d

# interpolate
print"\nPolynomial Interpolation...\n",d.interpolate(method='polynomial', order=2)
This will produce the following output −
Series...
0   10.0
1   20.0
2    NaN
3   65.0
4   75.0
5   85.0
6    NaN
7  100.0
dtype: float64

Polynomial Interpolation...
0   10.000000
1   20.000000
2   42.854015
3   65.000000
4   75.000000
5   85.000000
6   93.532847
7  100.000000
dtype: float64
How to make GET call to an API using Axios in JavaScript? - GeeksforGeeks

21 Jul, 2021
Axios is a promise-based HTTP client designed for Node.js and browser. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly. The following script src will include axios.js in the head section of your HTML code  
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
When we send a request to the API using axios, it returns a response. The response object consists of:  
data: the data returned from the server.
status: the HTTP code returned from the server.
statusText: the HTTP status returned by the server.
headers: headers obtained from the server.
config: the original request configuration.
request: the request object.
For the purpose of demonstration, we will be hosting an API on the localhost: 
http://127.0.0.1:5000
Python Script: You will be requiring the following packages to run the API, flask, requests, jsonify, flask_cors. The code for the Python API is as follows:  
Program:  
Python3
from flask import Flask, jsonify, requestfrom flask_cors import CORS app = Flask(__name__)CORS(app) @app.route('/test', methods =['GET'])def test():   return jsonify({"Result": "Welcome to GeeksForGeeks"}) if __name__ == '__main__':    app.run(debug = True)
Note: You can host this API by simply running the above python code.JS Script: Include axios.js and the corresponding JS file in the HTML file. In the JS file, write the following code which makes a GET request using Axios to the API. A GET request to the API requires the path to the API method.  
Program:  
javascript
function makeGetRequest(path) {    axios.get(path).then(        (response) => {            var result = response.data;            console.log(result);        },        (error) => {            console.log(error);        }    );}makeGetRequest('http://127.0.0.1:5000/test');
Output: It will call the API with a GET request. The response will be obtained on the console window.  
 
varshagumber28
JavaScript-Misc
HTML
JavaScript
Node.js
Web Technologies
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
HTML5 figure Tag - GeeksforGeeks

17 Mar, 2022
The <figure> tag in HTML is used to add self-contained content like illustrations, diagrams, photos, or codes listing in a document. It is related to main flow, but it can be used in any position of a document and the figure goes with the flow of the document and if remove it then it should not affect the flow of the document. This tag is new in HTML5. 
Syntax: 
<figure> Image content... </figure>
Attributes: It contains mostly two tags which are listed below:  
img src: This tag is used to add an image source in the document.
figcaption: This tag is used to set the caption to the image.
Example:  
HTML
<!DOCTYPE html> <html>     <body>         <h1>GeeksforGeeks</h1>        <h2><figure> Tag</h2>        <!--HTML figure tag starts here-->        <figure>            <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeks-25.png"            alt="The Pulpit Rock" width="304" height="228">            <figcaption>Geeks logo</figcaption>        </figure>        <!--HTML figure tag ends here-->           </body> </html>                   
Output:  
Supported Browsers:  
Google Chrome 6.0
Edge 9.0
Firefox 4.0
Safari 5.0
Opera 11.1
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubhamyadav4
ysachin2314
HTML-Tags
HTML5
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
How command line arguments are passed in main method in C#?

The Main() method is the entry point −
static void Main(string[] args)
The arguments array args is used to set arguments −
string[] args)
It will set the following if you add two arguments −
var args = new string[] {"arg1","arg2”}
Here is the demo code −
using System;

namespace Demo {
   class HelloWorld {

      // args for command line
      static void Main(string[] args) {
         Console.WriteLine("Welcome here!");
         Console.ReadKey();
      }
   }
}
To compile a C# program by using the command-line instead of the Visual Studio IDE −
Open a text editor and add the above-mentioned code.
Open a text editor and add the above-mentioned code.
Save the file as helloworld.cs
Save the file as helloworld.cs
Open the command prompt tool and go to the directory where you saved the file.
Open the command prompt tool and go to the directory where you saved the file.
Type csc helloworld.cs and press enter to compile your code.
Type csc helloworld.cs and press enter to compile your code.
If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file.
If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file.
Type helloworld to execute your program.
Type helloworld to execute your program.
You can see the output Hello World printed on the screen.
You can see the output Hello World printed on the screen.
How to use Boto3 to start a workflow in AWS Glue Data Catalog

In this article, we will see how a user can start a workflow in AWS Glue Data Catlog.
Problem Statement: Use boto3 library in Python to start a workflow.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2:
workflow_name is parameter in this function.
Step 2:
workflow_name is parameter in this function.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4: Create an AWS client for glue.
Step 4: Create an AWS client for glue.
Step 5: Now use start_workflow_run function and pass the parameter workflow_name as Name.
Step 5: Now use start_workflow_run function and pass the parameter workflow_name as Name.
Step 6: It returns the RunId and response metadata and starts the workflow.
Step 6: It returns the RunId and response metadata and starts the workflow.
Step 7: Handle the generic exception if something went wrong while starting a workflow.
Step 7: Handle the generic exception if something went wrong while starting a workflow.
The following code starts a workflow −
import boto3
from botocore.exceptions import ClientError

def start_a_workflow(workflow_name)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.start_workflow_run(Name=workflow_name)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in start_a_workflow: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in start_a_workflow: " + e.__str__())
print(start_a_workflow("test-daily"))
{'RunId': 'wr_64e880240692fddd5e1b19aed587f856bc20a96f54bc', 'ResponseMetadata': {'RequestId': '782e953b-8ee3-4876-9b2c-cd35e147b513', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 08:11:02 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '79', 'connection': 'keep-alive', 'x-amzn-requestid': '782e953b-********************************13'}, 'RetryAttempts': 0}}
VBA - Timer Function

The Timer Function returns the number of seconds and milliseconds since 12:00 AM.
Timer() 

Add a button and add the following function.
Private Sub Constant_demo_Click()
   msgbox("Time is : " & Now())
   msgbox("Timer is: " & Timer())
End Sub
When you execute the above function, it produces the following output.
Time is : 19/07/2013 3:45:53 PM
Timer is: 56753.4 


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Add the border to the table with Bootstrap

To add border to a table, use the table-bordered class. You can try to run the following code to implement the table-bordered class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</title>
      <meta name = "viewport" content = "width=device-width, initial-scale=1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <table class = "table table-bordered table-striped">
         <caption>Footballer Rank</caption>
         <thead>
            <tr>
               <th>Footballer</th>
               <th>Rank</th>
               <th>Country</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>Messi</td>
               <td>1</td>
               <td>Argentina</td>
            </tr>
            <tr>
               <td>Neymar</td>
               <td>2</td>
               <td>Brazil</td>
            </tr>
            <tr>
               <td>Ronaldo</td>
               <td>3</td>
               <td>Portugal</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
Change date format (in DB or output) to dd/mm/yyyy in PHP MySQL?

You can change the date format in PHP using date() fucntion. The syntax is as follows −
date(d/m/Y,yourDateTimeVariable);
In PHP, convert string to date using strtodate(). Here is the PHP code used to format the datetime −
$LogintDate = strtotime('2019-01-12');
echo date('d/m/Y', $LogintDate);
The snapshot of code is as follows −
The following is the output −
12/01/2019
You can achieve in MySQL with the help of date_format() function. The syntax is as follows −
SELECT DATE_FORMAT(yourColumnName,’%d/%m/%Y’) as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table −
mysql> create table Date_FormatDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> LoginDate datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into Date_FormatDemo(LoginDate) values(curdate());
Query OK, 1 row affected (0.17 sec)

mysql> insert into Date_FormatDemo(LoginDate) values(now());
Query OK, 1 row affected (0.27 sec)

mysql> insert into Date_FormatDemo(LoginDate) values('2019-11-12');
Query OK, 1 row affected (0.11 sec)

mysql> insert into
Date_FormatDemo(LoginDate) values(date_add(now(),interval 2 day));
Query OK, 1 row affected (0.13 sec)

mysql> insert into Date_FormatDemo(LoginDate) values(date_add(curdate(),interval -2 day));
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from Date_FormatDemo;
The following is the output −
+----+---------------------+
| Id | LoginDate           |
+----+---------------------+
| 1 | 2019-01-12 00:00:00 |
| 2 | 2019-01-12 22:53:53 |
| 3 | 2019-11-12 00:00:00 |
| 4 | 2019-01-14 22:54:27 |
| 5 | 2019-01-10 00:00:00 |
+----+---------------------+
5 rows in set (0.00 sec)
Let us now change the date format in dd/mm/yyyy. The query is as follows −
mysql> select date_format(LoginDate,'%d/%m/%Y') as DateFormat from Date_FormatDemo;
The following is the output −
+------------+
| DateFormat |
+------------+
| 12/01/2019 |
| 12/01/2019 |
| 12/11/2019 |
| 14/01/2019 |
| 10/01/2019 |
+------------+
5 rows in set (0.00 sec)
ReactJS – componentWillReceiveProps() Method

In this article, we are going to see how to execute a function if the props passed to the component is updated in the DOM tree.
This method is used during the updating phase of the React lifecycle. This function is generally called if the props passed to the component change. It is used to update the state in response with the new received props. setState() method doesn’t generally call this method again.
Note: This method is now deprecated.
UNSAFE_componentWillReceiveProps(nextProps)
In this example, we will build a color-changing React application which will call the componentWillReceiveProps method when the props of the component are updated.
Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.
App.jsx
import React from 'react';

class App extends React.Component {
   state = { color: 'green' };
   render() {
      setTimeout(() => {
         this.setState({ color: 'wheat' });
      }, 4000);
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <ChangeName color={this.state.color} />
         </div>
      );
   }
}
class ChangeName extends React.Component {
   UNSAFE_componentWillReceiveProps(nextProps) {
      console.log('Component received new props', nextProps);
   }
   render() {
      console.log('ChangeName component is called');
      return (
         <div>
            <h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
This will produce the following result.
How to fix error “You have an error in your syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near... ”?

This kind of errors arise when you have used incorrect syntax. Let us see an example wherein we have created a table and the same error “1054” arise.
Here’s the table −
mysql> create table DemoTable689(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(100),
   UserLoginDate date(100) NOT NULL
);
This will produce the following output i.e. an error for incorrect syntax usage −
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(100) NOT NULL
)' at line 5
Let us now fix the error 1054. For that, you need to use only DATE NOT NULL. Let us first create a table −
mysql> create table DemoTable689(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(100),
   UserLoginDate date NOT NULL
);
Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable689(UserName,UserLoginDate) values('John',DATE(NOW()));
Query OK, 1 row affected (0.40 sec)
mysql> insert into DemoTable689(UserName,UserLoginDate) values('Chris','2018-01-21');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable689(UserName,UserLoginDate) values('Robert',CURDATE());
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable689;
This will produce the following output. Now, we have fixed the error −
+--------+----------+---------------+
| UserId | UserName | UserLoginDate |
+--------+----------+---------------+
|      1 | John     | 2019-07-21    |
|      2 | Chris    | 2018-01-21    |
|      3 | Robert   | 2019-07-21    |
+--------+----------+---------------+
3 rows in set (0.00 sec)
How to sort an ArrayList in Java in descending order?

To sort the contents of an ArrayList in descending order
Create an ArrayList.Sort the contents of the ArrayList using the sort() method of the Collections class.Then, reverse array list using the reverse() method of the Collections class.
Create an ArrayList.
Sort the contents of the ArrayList using the sort() method of the Collections class.
Then, reverse array list using the reverse() method of the Collections class.
Example:
import java.util.ArrayList;
import java.util.Collections;

public class ArrayListSample {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      Collections.sort(list);
      System.out.println(list);
      Collections.reverse(list);
      System.out.println(list);
   }
}
Output:
[Java, JavaFx, OpenCV, WebGL]
[WebGL, OpenCV, JavaFx, Java]
Add a new value to a column of data type enum in MySQL?

You can add a new value to a column of data type enum using ALTER MODIFY command.
If you want the existing value of enum, then you need to manually write the existing enum value at the time of adding a new value to column of data type enum.
The syntax is as follows −
ALTER TABLE yourTableName MODIFY COLUMN yourEnumColumnName
ENUM('yourExistingValue1','yourExistingValue2',........N,'yourNewValue1',’yourNewValue2’,.....N);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table AddingNewValueToEnumColumn
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Colors ENUM('RED','GREEN','BLUE'),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.64 sec)
To check the DDL of the above table, use the show create command. The query is as follows −
mysql> show create table AddingNewValueToEnumColumn\G
The following is the output −
*************************** 1. row ***************************
Table − AddingNewValueToEnumColumn
Create Table − CREATE TABLE `addingnewvaluetoenumcolumn` (
   `Id` int(11) NOT NULL AUTO_INCREMENT,
   `Colors` enum('RED','GREEN','BLUE') DEFAULT NULL,
   PRIMARY KEY (`Id`)
   ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
Look at the enum column ‘Colors’ with the value 'RED','GREEN','BLUE' and if you want another value, then use the ALTER command as discussed above.
Now, let us add new values i.e. 'YELLOW','ORANGE','PINK'. The following is the query to add a new value to enum column ‘Colors’ −
mysql> ALTER TABLE addingnewvaluetoenumcolumn MODIFY COLUMN Colors
   -> ENUM('RED','GREEN','BLUE','YELLOW','ORANGE','PINK');
Query OK, 0 rows affected (0.17 sec)
Records − 0 Duplicates − 0 Warnings − 0
Check the description of the table to ensure that the values are added or not. The syntax is as follows −
DESC yourTableName;
Check the description of the table ‘addingnewvaluetoenumcolumn’ using DESC −
mysql> desc AddingNewValueToEnumColumn;
The following is the output −
+--------+-----------------------------------------------------+------+-----+---------+----------------+
| Field  | Type                                                | Null | Key | Default | Extra          |
+--------+-----------------------------------------------------+------+-----+---------+----------------+
| Id     | int(11)                                             | NO   | PRI | NULL    | auto_increment |
| Colors | enum('RED','GREEN','BLUE','YELLOW','ORANGE','PINK') | YES  |     | NULL    |                |
+--------+-----------------------------------------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
CSS overflow: scroll

In the CSS overflow property with value scroll, the overflow is clipped and a scrollbar gets added. This allows the user to read the entire content.
You can try to run the following code to implement CSS overflow: scroll property −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            background-color: orange;
            width: 250px;
            height: 45px;
            border: 2px solid blue;
            overflow: scroll;
         }
      </style>
   </head>
   <body>
      <h1>Heading</h1>
      <div>Overflow property used here. This is a demo text to show the working of CSS overflow: scroll. This won't hide the content. Now a scrollbar will be visible.</div>
   </body>
</html>
Matplotlib.axis.Axis.set_smart_bounds() function in Python - GeeksforGeeks

08 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_smart_bounds() function in axis module of matplotlib library is used to set the axis to have smart bounds.  
Syntax: Axis.set_smart_bounds(self, value)  
Parameters: This method accepts the following parameters. 
value: This parameter is the bool value.
Return value: This method does not return any value. 
Below examples illustrate the matplotlib.axis.Axis.set_smart_bounds() function in matplotlib.axis: 
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport numpy as npimport matplotlib.pyplot as plt    fig = plt.figure()x = np.linspace(-np.pi, np.pi, 100)y = 2*np.sin(x)  ax = fig.add_subplot()ax.set_title('centered spines')ax.plot(x, y)  ax.spines['left'].set_position('center')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('center')ax.spines['top'].set_color('none')ax.spines['left'].set_smart_bounds(True)ax.spines['bottom'].set_smart_bounds(True)  ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')  ax.grid()   fig.suptitle("""matplotlib.axis.Axis.set_smart_bounds()function Example\n""", fontweight ="bold")      plt.show()
Output:  
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport numpy as npimport matplotlib.pyplot as plt    fig = plt.figure()x = np.linspace(-np.pi, np.pi, 100)y = 2*np.sin(x)  ax = fig.add_subplot()ax.set_title('Spines at data (3, 2)')ax.plot(x, y)  ax.spines['left'].set_position(('data', 3))ax.spines['right'].set_color('none')ax.spines['bottom'].set_position(('data', 2))ax.spines['top'].set_color('none')ax.spines['left'].set_smart_bounds(True)ax.spines['bottom'].set_smart_bounds(True)  ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')  ax.grid()   fig.suptitle("""matplotlib.axis.Axis.set_smart_bounds()function Example\n""", fontweight ="bold")      plt.show()
Output: 
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
sum() function in Python
Stack in Python
Reading and Writing to text files in Python