code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Timestamp.to_period - GeeksforGeeks

27 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.to_period() function return a period object for which the given Timestamp is an observation.
Syntax :Timestamp.to_period()
Parameters :freq : time series frequency
Return : period object
Example #1: Use Timestamp.to_period() function to convert the given Timestamp to a period object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                   hour = 10, second = 49, tz = 'US/Central')   # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_period() function to convert the given Timestamp to period.
# convert to period# we have applied monthly frequencyts.to_period(freq ='M')
Output :
As we can see in the output, the Timestamp.to_period() function has converted the given Timestamp object into a period object. Example #2: Use Timestamp.to_period() function to convert the given Timestamp to a period object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                   hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_period() function to convert the given Timestamp to period.
# convert to period# we have applied minutely frequencyts.to_period(freq ='T')
Output :
As we can see in the output, the Timestamp.to_period() function has converted the given Timestamp object into a period object.
Python Pandas-Timestamp
Python-pandas
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
Design a TM that increments a binary number by 1

Turing’s machine is more powerful than both finite automata and pushdown automata. These machines are as powerful as any computer we have ever built.
A Turing machine can be formally described as seven tuples
(Q,X, Σ,δ,q0,B,F)
Where,
Q is a finite set of states.
Q is a finite set of states.
X is the tape alphabet
X is the tape alphabet
Σ is the input alphabet
Σ is the input alphabet
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
q0 is the initial state
q0 is the initial state
B is the blank symbol
B is the blank symbol
F is the final state.
F is the final state.
A Turing Machine (TM) is a mathematical model which consists of an infinite length tape divided into cells on which input is given. It consists of a head which reads the input tape. A state register stores the state of the Turing machine.
After reading an input symbol, it is replaced with another symbol, its internal state is changed, and it moves from one cell to the right or left. If the TM reaches the final state, the input string is accepted, otherwise the string is rejected.
The Turing machine has a read/write head. So, we can write on the tape.
Replace the trailing 1‟s to 0.
Replace the trailing 1‟s to 0.
Replace the first „0‟ from the right end by 1.
Replace the first „0‟ from the right end by 1.
Binary increment means adding 1 to the given input.
Input - 0111
Output - 1000
Input - 10000
Output - 10001
The Turing Machine that increments a binary number by 1 is as follows −
File getPath() method in Java with Examples

30 Jan, 2019
The getPath() method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object.
Function Signature:
public String getPath()
Function Syntax:
file.getPath()
Parameters: This function does not accept any parameters.
Return value: The function returns a String value which is the Path of the given File object.
Below programs will illustrate the use of the getPath() function:
Example 1: We are given a file object of a file, we have to get the path of the file object.
// Java program to demonstrate the// use of getPath() function  import java.io.*;  public class solution {    public static void main(String args[])    {          // try catch block to handle exceptions        try {              // Create a file object            File f                = new File("c:\\users\\program.txt");              // Get the path of the given file f            String path = f.getPath();              // Display the file path of the file object            System.out.println("File path : " + path);        }        catch (Exception e) {            System.err.println(e.getMessage());        }    }}
Output:
File path : c:\users\program.txt

Example 2: We are given a file object of a directory, we have to get the path of the file object.
// Java program to demonstrate the// use of getPath() function  import java.io.*;  public class solution {    public static void main(String args[])    {          // try catch block to handle exceptions        try {              // Create a file object            File f = new File("c:\\users\\program");              // Get the path of the given file f            String path = f.getPath();              // Display the file path of the file object            System.out.println("File path : " + path);        }        catch (Exception e) {            System.err.println(e.getMessage());        }    }}
Output:
File path : c:\users\program

The programs might not run in an online IDE. please use an offline IDE and set the path of the file
Java-File Class
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Weather app using Django | Python

25 May, 2022
In this tutorial, we will learn how to create a Weather app that uses Django as backend. Django provides a Python Web framework based web framework that allows rapid development and clean, pragmatic design.
Basic Setup –Change directory to weather –
cd weather
Start the server –
python manage.py runserver
To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL. Now, you can stop the server by pressing
ctrl-c
 python manage.py startapp main
Goto main/ folder by doing :
cd main 
and create a folder with index.html file: templates/main/index.html
Open the project folder using a text editor. The directory structure should look like this :
Now add main app in settings.py
Edit urls.py file in weather :
from django.contrib import adminfrom django.urls import path, include    urlpatterns = [    path('admin/', admin.site.urls),    path('', include('main.urls')),]
edit urls.py file in main :
from django.urls import pathfrom . import views  urlpatterns = [         path('', views.index),]
edit views.py in main :
from django.shortcuts import render# import json to load json data to python dictionaryimport json# urllib.request to make a request to apiimport urllib.request    def index(request):    if request.method == 'POST':        city = request.POST['city']        ''' api key might be expired use your own api_key            place api_key in place of appid ="your_api_key_here "  '''          # source contain JSON data from API          source = urllib.request.urlopen(            'http://api.openweathermap.org/data/2.5/weather?q ='                     + city + '&appid = your_api_key_here').read()          # converting JSON data to a dictionary        list_of_data = json.loads(source)          # data for variable list_of_data        data = {            "country_code": str(list_of_data['sys']['country']),            "coordinate": str(list_of_data['coord']['lon']) + ' '                        + str(list_of_data['coord']['lat']),            "temp": str(list_of_data['main']['temp']) + 'k',            "pressure": str(list_of_data['main']['pressure']),            "humidity": str(list_of_data['main']['humidity']),        }        print(data)    else:        data ={}    return render(request, "main/index.html", data)
You can get your own API key from : Weather API
Navigate to templates/main/index.html and edit it: link to index.html file
Make migrations and migrate it:
python manage.py makemigrations
python manage.py migrate

now let’s run the server to see your weather app.
python manage.py runserver
Django-Projects
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Hashtable toString() Method in Java

24 Jun, 2021
The java.util.Hashtable.toString() is an inbuilt method of Hashtable that is used to get a string representation of the objects of Hashtable in the form of a set of entries separated by “, “. So basically the toString() method is used to convert all the elements of Hashtable into String.Syntax: 
Hash_Table.toString()
Parameter: The method does not take any parameters.Return value: The method returns the set consisting of the string representation of the elements of the hash table.Below programs illustrate the working of java.util.Hashtable.toString() method: Program 1:  
Java
// Java code to illustrate the toString() methodimport java.util.*; public class Hash_Table_Demo {    public static void main(String[] args)    {         // Creating an empty Hashtable        Hashtable<Integer, String> hash_table =                            new Hashtable<Integer, String>();         // Inserting elements into the table        hash_table.put(10, "Geeks");        hash_table.put(15, "4");        hash_table.put(20, "Geeks");        hash_table.put(25, "Welcomes");        hash_table.put(30, "You");         // Displaying the Hashtable        System.out.println("Initial table is: " + hash_table);         // Displaying the string representation        System.out.println("The set is: " + hash_table.toString());    }}
Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The set is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
 
Program 2:  
Java
// Java code to illustrate the toString() methodimport java.util.*; public class Hash_Table_Demo {    public static void main(String[] args)    {         // Creating an empty Hashtable        Hashtable<String, Integer> hash_table =                           new Hashtable<String, Integer>();         // Inserting elements into the table        hash_table.put("Geeks", 10);        hash_table.put("4", 15);        hash_table.put("Geeks", 20);        hash_table.put("Welcomes", 25);        hash_table.put("You", 30);         // Displaying the Hashtable        System.out.println("Initial Table is: " + hash_table);         // Displaying the string representation        System.out.println("The set is: " + hash_table.toString());    }}
Initial Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The set is: {You=30, Welcomes=25, 4=15, Geeks=20}
 
rajeev0719singh
Java - util package
Java-Collections
Java-Functions
Java-HashTable
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
numpy.polyval() in Python

29 Nov, 2018
numpy.polyval(p, x) method evaluates a polynomial at specific values.
If ‘N’ is the length of polynomial ‘p’, then this function returns the value
Parameters :p : [array_like or poly1D] polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.For example : poly1d(3, 2, 6) = 3x2 + 2x + 6
x : [array_like or poly1D] A number, an array of numbers, for evaluating ‘p’.
Return: Evaluated value of polynomial.
Code : Python code explaining polyval()
# Python code explaining # numpy.polyval()    # importing librariesimport numpy as npimport pandas as pd    # Constructing polynomial p1 = np.poly1d([1, 2]) p2 = np.poly1d([4, 9, 5, 4])     print ("P1 : ", p1) print ("\n p2 : \n", p2) 
 
# Solve for x = 2 print ("\n\np1 at x = 2 : ", p1(2)) print ("p2 at x = 2 : ", p2(2)) 
 
a = np.polyval([1, 2], 2)b = np.polyval([4, 9, 5, 4], 2)  print ("\n\nUsing polyval")print ("p1 at x = 2 : ", a) print ("p2 at x = 2 : ", b)   c = np.polyval(np.poly1d([4, 9, 5, 4]), np.poly1d(2))print ("\nc : ", c)
Python numpy-polynomials
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | time.monotonic() method

08 Oct, 2021
Python time.monotonic() method is used to get the value of a monotonic clock. A monotonic clock is a clock that can not go backward.  As the reference point of the returned value of the monotonic clock is undefined, only the difference between the results of consecutive calls is valid.
Syntax: time.monotonic()
Parameter: No parameter is required.
Return type: This method returns a float value which represents the value of a monotonic clock in fractional seconds. 
Python3
# Python program to explain time.monotonic() method # importing time moduleimport time # Get the value of# a monotonic clock using# time.monotonic() methodvalue = time.monotonic() # print the value of# the monotonic clockprint("Value of the monotonic clock (in fractional seconds):", value)
Output:
Value of the monotonic clock (in fractional seconds): 216444.515
Python3
# Python program to explain time.monotonic() method # importing time moduleimport time # Get the value of# a monotonic clock at the# beginning of the process# using time.monotonic() methodstart = time.monotonic() # print the value of# the monotonic clockprint("At the beginning of the process")print("Value of the monotonic clock (in fractional seconds):", start) i = 0arr = [0] * 10while i < 10:    # Take input from the user    arr[i] = int(input())    i = i + 1 # Print the user inputprint(arr) # Get the value of# monotonic clock# using time.monotonic() methodend = time.monotonic() # print the value of# the monotonic clockprint("\nAt the end of the process")print("Value of the monotonic clock (in fractional seconds):", end)print("Time elapsed during the process:", end - start)
Output:
At the beginning of the process
Value of the monotonic clock (in fractional seconds): 216491.25
1
2
3
4
5
6
7
8
9
10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

At the end of the process
Value of the monotonic clock (in fractional seconds): 216516.875
Time elapsed during the process: 25.625
kumar_satyam
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Python | Reverse sign of each element in given list

01 May, 2019
Given a list of integers, write a Python program to reverse the sign of each element in given list.
Examples:
Input : [-1, 2, 3, -4, 5, -6, -7]
Output : [1, -2, -3, 4, -5, 6, 7]

Input : [-5, 9, -23, -2, 7]
Output : [5, -9, 23, 2, -7]

 
Methods #1 : List comprehension
# Python3 program to Convert positive # list integers to negative and vice-versadef Convert(lst):    return [ -i for i in lst ]  # Driver codelst = [-1, 2, 3, -4, 5, -6, -7]print(Convert(lst))
[1, -2, -3, 4, -5, 6, 7]

Methods #2 : Using numpyThe Python module, Numpy, can also be used which is the most pythonic way to solve the given problem. The list is first converted to numpy array and then, the negative of the array is returned, which is finally converted to list.
# Python3 program to Convert positive # list integers to negative and vice-versaimport numpy as np  def Convert(lst):    lst = np.array(lst)    return list(-lst)      # Driver codelst = [-1, 2, 3, -4, 5, -6, -7]print(Convert(lst))
[1, -2, -3, 4, -5, 6, 7]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MFC - Getting Started

In this chapter, we will look at a working MFC example. To create an MFC application, you can use wizards to customize your projects. You can also create an application from scratch.
Following are the steps to create a project using project templates available in Visual Studio.
Step 1 −  Open the Visual studio and click on the File → New → Project menu option.
Step 2 −  You can now see that the New Project dialog box is open.
Step 3 − From the left pane, select Templates → Visual C++ → MFC 
Step 4 −  In the middle pane, select MFC Application.
Step 5 − Enter the project name ‘MFCDemo’ in the Name field and click OK to continue. You will see the following dialog.
Step 6 − Click Next.
Step 7 − Select the options which are shown in the dialog box given above and click Next.
Step 8 − Uncheck all options and click Finish button.
You can now see that the MFC wizard creates this Dialog Box and the project files by default.
Step 9 − Run this application, you will see the following output.
You can also create an MFC application from scratch. To create an MFC application, you need to follow the following Steps.
Step 1 − Open the Visual studio and click on the File → New → Project menu option.
Step 2 − You can now see the New Project dialog box.
Step 3 − From the left pane, select Templates → Visual C++ → General.
Step 4 − In the middle pane, select Empty
Step 5 − Enter project name ‘MFCDemoFromScratch’ in the Name field and click OK to continue. You will see that an empty project is created.
Step 6 − To make it an MFC project, right-click on the project and select Properties.
Step 7 − In the left section, click Configuration Properties → General.
Step 8 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK.
Step 9 − As it is an empty project now; we need to add a C++ file. So, right-click on the project and select Add → New Item...
Step 10 − Select C++ File (.cpp) in the middle pane and enter file name in the Name field and click Add button.
Step 11 − You can now see the main.cpp file added under the Source Files folder.
Step 12 − Let us add the following code in this file.
#include <iostream> 
using namespace std;  

void main() { 
   cout << "***************************************\n"; 
   cout << "MFC Application Tutorial"; 
   cout << "\n***************************************"; 
   getchar(); 
}
Step 13 − When you run this application, you will see the following output on console.
*************************************** 
MFC Application Tutorial
React-Bootstrap Tooltip Component

30 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Tooltip component is used to display informative text when users hover over, focus on, or tap an element. We can use the following approach in ReactJS to use the react-bootstrap Tooltip Component.
Tooltip Props:
arrowProps: It is used to position the tooltip arrow.
id: It is just an HTML id attribute that is necessary for accessibility.
placement: It is used to set the positioned direction of the tooltip.
popper: It is of object type and indicates the popper property of the tooltip element.
show: It is used to indicate whether the tooltip is open or not.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap 
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap 
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Tooltip from 'react-bootstrap/Tooltip';import Button from 'react-bootstrap/Button';import OverlayTrigger from 'react-bootstrap/OverlayTrigger'  export default function App() {  return (    <div style={{ display: 'block', width: 700, padding: 30 }}>      <h4>React-Bootstrap Tooltip Component</h4>      <OverlayTrigger        delay={{ hide: 450, show: 300 }}        overlay={(props) => (          <Tooltip {...props}>            Hii, I am a simple tooltip information!!!          </Tooltip>        )}        placement="bottom"      ><Button variant="warning">Tooltip Button</Button>      </OverlayTrigger>,    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://react-bootstrap.github.io/components/overlays/#tooltips
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between the | and || or operators in C#?

| Operator
The | operator computes the logical OR of its operands. The result of x | y is true if either x or y evaluates to true. Otherwise, the result is false.
The | operator evaluates both operands even if the left-hand operand evaluates to true, so that the operation result is true regardless of the value of the right-hand operand.
|| Operator
The conditional logical OR operator ||, also known as the "short−circuiting" logical OR operator, computes the logical OR of its operands.
The result of x || y is true if either x or y evaluates to true. Otherwise, the result is false. If x evaluates to true, y is not evaluated.
class Program {
   static void Main(string[] args){
      int a = 4;
      int b = 3;
      int c = 0;
      c = a | b;
      Console.WriteLine("Line 1 - Value of c is {0}", c);
      Console.ReadLine();
   }
}
Value of c is 7
Here the values are converted to binary
4−−100
3−−011
Output 7 −−111
static void Main(string[] args){
   int a = 4;
   int b = 3;
   int c = 7;
   if (a > b || b > c){
      System.Console.WriteLine("a is largest");
   } else {
      System.Console.WriteLine("a is not largest");
   }
   Console.ReadLine();
}
a is largest
Here in the above example one of the condition return true so it never bothers to check the next condition.
SAMEPERIODLASTYEAR function

Returns a table that contains a column of dates shifted one year back in time from the dates in the specified dates column, in the current context.
SAMEPERIODLASTYEAR (<dates>) 

dates
A column that contains dates.
A single column table of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
Previous Year Sales: = CALCULATE ( 
   SUM (Sales [Sales Amount]),SAMEPERIODLASTYEAR (Sales [Date])
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Matplotlib.axes.Axes.set_xlim() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_xlim() function in axes module of matplotlib library is used to set the x-axis view limits.
Syntax: Axes.set_xlim(self, left=None, right=None, emit=True, auto=False, *, xmin=None, xmax=None)
Parameters: This method accepts the following parameters.
left : This parameter is the left xlim in data coordinates
right : This parameter is the right xlim in data coordinates
emit : This parameter is used to notify observers of limit change.
auto : This parameter is used to turn on autoscaling of the x-axis.
xmin, xmax: These parameter are equivalent to left and right and it is an error to pass both xmin and left or xmax and right.
Returns:This method returns the following
left, right :This returns the new x-axis limits in data coordinates.
Below examples illustrate the matplotlib.axes.Axes.set_xlim() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionfrom matplotlib.widgets import Cursorimport numpy as npimport matplotlib.pyplot as plt    np.random.seed(19680801)  fig, ax = plt.subplots(facecolor ='#A0F0CC')  x, y = 4*(np.random.rand(2, 100) - .5)ax.plot(x, y, 'g')ax.set_xlim(-3, 3)  cursor = Cursor(ax, useblit = True, color ='red',                 linewidth = 2)      ax.set_title('matplotlib.axes.Axes.set_xlim() \Example\n', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  fig1, ax1 = plt.subplots()fig2, ax2 = plt.subplots()ax1.set(xlim =(-1.0, 1.0),         ylim =(-1.0, 1.0),        autoscale_on = False)  ax2.set(xlim =(-0.5, 0.5),         ylim =(-0.5, 0.5),        autoscale_on = False)  x, y, s, c = np.random.rand(4, 200)s *= 200  ax1.scatter(x, y, s, c)ax2.scatter(x, y, s, c)    def GFG(event):          if event.button != 1:        return          x, y = event.xdata, event.ydata    ax2.set_xlim(x - 0.5, x + 0.5)    ax2.set_ylim(y - 0.5, y + 0.5)    fig2.canvas.draw()  fig1.canvas.mpl_connect('button_press_event',                        GFG)   ax1.set_title('matplotlib.axes.Axes.set_xlim() \Example\n Original Window ',             fontsize = 14, fontweight ='bold')  ax2.set_title('Zoomed Window',             fontsize = 14, fontweight ='bold')  plt.show()
Output:
Python-matplotlib
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
How to calculate the power exponent value using C#?

To calculate the power exponent value, use the Math.pow() method.
Here, n is the number and p is the power −
double res = Math.Pow(n, p);
The following is the complete code −
 Live Demo
using System;
class Program {
   static void Main() {
      double n, p;
      n = 7;
      p = 3;
      Console.WriteLine("Exponent Power= "+n);
      double res = Math.Pow(n, p);
      Console.WriteLine("Result= {0}", res);
      Console.ReadLine();
   }
}
Exponent Power= 7
Result= 343
How to concatenate all columns in MySQL?

First, you need to know how many columns are present in a table. Following is the syntax to know the column names −
show columns from yourTableName;
Following is the syntax to concatenate all columns −
select concat(yourColumnName1,yourColumnName2,yourColumnName3,........N) from yourTableName;
Let us first create a table −
mysql> create table DemoTable
   (
   CustomerId int,
   CustomerName varchar(20),
   CustomerAge int
   );
Query OK, 0 rows affected (0.66 sec)
Following is the query to know the exact column −
mysql> show columns from DemoTable;
This will produce the following output −
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| CustomerId   | int(11)     | YES  |     | NULL    |       |
| CustomerName | varchar(20) | YES  |     | NULL    |       |
| CustomerAge  | int(11)     | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(101,'Chris',26);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(102,'Robert',27);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+------------+--------------+-------------+
| CustomerId | CustomerName | CustomerAge |
+------------+--------------+-------------+
| 101        | Chris        | 26          |
| 102        | Robert       | 27          |
+------------+--------------+-------------+
2 rows in set (0.00 sec)
Following is the query to concat all columns −
mysql> select concat(CustomerId,CustomerName,CustomerAge) from DemoTable;
This will produce the following output −
+---------------------------------------------+
| concat(CustomerId,CustomerName,CustomerAge) |
+---------------------------------------------+
| 101Chris26                                  |
| 102Robert27                                 |
+---------------------------------------------+
2 rows in set (0.00 sec)
Reverse an Integer in Java

To reverse an integer in Java, try the following code −
 Live Demo
import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      int i = 239, rev = 0;
      System.out.println("Original: " + i);
      while(i != 0) {
         int digit = i % 10;
         rev = rev * 10 + digit;
         i /= 10;
      }
      System.out.println("Reversed: " + rev);
   }
}
Original: 239
Reversed: 932
In the above program, we have the following int value, which we will reverse.
int i = 239;
Now, loop through until the value is 0. Find the remainder and perform the following operations to get the reverse of the given integer 239.
while(i != 0) {
   int digit = i % 10;
   rev = rev * 10 + digit;
   i /= 10;
}
How to use MySQL VIEW with WHERE clause?

For MySQL VIEW with WHERE clause, the syntax is as follows −
select * from yourViewName where yourColumnName='yourValue';
Let us first create a −
mysql> create table DemoTable1432
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentBranchName varchar(20)
   -> );
Query OK, 0 rows affected (1.26 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1432(StudentName,StudentBranchName) values('Chris','CS');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1432(StudentName,StudentBranchName) values('David','CE');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1432(StudentName,StudentBranchName) values('Mike','ME');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select −
mysql> select * from DemoTable1432;
This will produce the following output −
+-----------+-------------+-------------------+
| StudentId | StudentName | StudentBranchName |
+-----------+-------------+-------------------+
|         1 | Chris       | CS                |
|         2 | David       | CE                |
|         3 | Mike        | ME                |
+-----------+-------------+-------------------+
3 rows in set (0.00 sec)
Following is the query to create view −
mysql> create view DemoTable1432_View as select * from DemoTable1432;
Query OK, 0 rows affected (0.17 sec)
Following is the query to use MySQL view with where clause −
mysql> select * from DemoTable1432_View where StudentBranchName='CS';
This will produce the following output −
+-----------+-------------+-------------------+
| StudentId | StudentName | StudentBranchName |
+-----------+-------------+-------------------+
|         1 | Chris       | CS                |
+-----------+-------------+-------------------+
1 row in set (0.03 sec)
Validate IP Address in Python

Suppose we have a string; we have to check whether the given input is a valid IPv4 address or IPv6 address or neither.
The IPv4 addresses are canonically represented in dotted-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), For example, 192.168.254.1; Besides, leading zeros in the IPv4 address is invalid. For example, the address 192.168.254.01 is invalid.
The IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, suppose the address is 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid address. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 this address is also a valid
However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. So for example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. Besides, extra leading zeros in the IPv6 is also invalid. The address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.
To solve this, we will follow these steps −
Define a method checkv4(x), this will check whether x is in range 0 to 255, then true, otherwise false
Define a method checkv4(x), this will check whether x is in range 0 to 255, then true, otherwise false
Define a method checkv6(x), this will work as follows −if size of x > 4, then return falseif decimal equivalent of x >= 0 and x[0] is not ‘-’, then return true, otherwise false
Define a method checkv6(x), this will work as follows −
if size of x > 4, then return false
if size of x > 4, then return false
if decimal equivalent of x >= 0 and x[0] is not ‘-’, then return true, otherwise false
if decimal equivalent of x >= 0 and x[0] is not ‘-’, then return true, otherwise false
From the main method
From the main method
If the input has three dots, and for each part I checkv4(i) is true, then return “IPv4”
If the input has three dots, and for each part I checkv4(i) is true, then return “IPv4”
If the input has seven colons, and for each part I checkv6(i) is true, then return “IPv6”
If the input has seven colons, and for each part I checkv6(i) is true, then return “IPv6”
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def validIPAddress(self, IP):
      """
      :type IP: str
      :rtype: str
      """
      def isIPv4(s):
         try: return str(int(s)) == s and 0 <= int(s) <= 255
         except: return False
      def isIPv6(s):
         if len(s) > 4:
            return False
         try : return int(s, 16) >= 0 and s[0] != '-'
         except:
            return False
      if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
         return "IPv4"
      if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")):
         return "IPv6"
      return "Neither"
ob = Solution()
print(ob.validIPAddress("172.16.254.1"))
"172.16.254.1"
"IPv4"
How to use PowerShell Break statement with the While Loop?

You can use the break statement with both the While loop and the Do-While loop.
To use the Break with a while loop, see the example below.
$i = 1
While($i -ne 10){
   Write-Output $i
   if($i -eq 5){break}
   $i++
}
1
2
3
4
5
In the above example, the loop terminates when the value of the variable $i reaches 5 because the Break statement is executed.
You can also use the break in the nested While loop, here we will take two examples of the nested loop. First when the break is placed outer loop and second when the break is placed in the inner loop.
Break statement in the Outer While loop −
$i=1
$j=1
While($i -ne 10){
   while($j -ne 5){
      Write-Output "i = $i"
      Write-Output "j = $j`n"
      $j++
   }
   if($i -eq 5){Break}
   $i++
}
i = 1
j = 1
i = 1
j = 2
i = 1
j = 3
i = 1
j = 4
The above example is of the outer loop break. When the value of $i becomes the 5, it terminates both the while loop.
Break statement in the Inner While loop −
$i=1
$j=1
While($i -ne 5){
   while($j -ne 5){
      Write-Output "i = $i"
      Write-Output "j = $j`n"
      if($j -eq 3){Break}
      $j++
   }
   $i++
}
i = 1
j = 1
i = 1
j = 2
i = 1
j = 3
i = 2
j = 3
i = 3
j = 3
i = 4
j = 3
When the value of $j becomes 3 in the above example, it terminates the child while loop and the execution move to the parent While loop and executes it.
Similarly, you can use the break statement with the Do-While loop as well as mentioned in the below example.
Break statement in the Do-While loop −
$i = 1
do {
   Write-Output "i = $i"
   if($i -eq 3){Break}
   $i++
} while ($i -ne 5)
i = 1
i = 2
i = 3
List size() method in Java with Examples - GeeksforGeeks

06 Oct, 2021
The size() method of the List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.
Syntax: 
public int size()
Parameters: This method does not take any parameters.
Return Value: This method returns the number of elements in this list.
Illustration: Assume it to be an integer list 
Input  : {3,2,1,5,7} 
Output : 5
Example 1:
Java
// Java program to Illustrate size() method// of List class for Integer value // Importing required classesimport java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] arg)    {        // Creating object of ArrayList class        List<Integer> list = new ArrayList<Integer>();         // Populating List by adding integer elements        // using add() method        list.add(1);        list.add(2);        list.add(3);        list.add(4);        list.add(5);         // Printing elements of List        System.out.println("Before operation: " + list);         // Getting total size of list        // using size() method        int size = list.size();         // Printing the size of List        System.out.println("Size of list = " + size);    }}
Before operation: [1, 2, 3, 4, 5]
Size of list = 5
Example 2:
Java
// Java program to Illustrate size() method// of List class for Integer value // Importing required classesimport java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty string list by        // declaring elements of string type        List<String> list = new ArrayList<String>();         // Populating List by adding string elements        // using add() method        list.add("Geeks");        list.add("for");        list.add("Geeks");         // Printing the List        System.out.println("Before operation: " + list);         // Getting total size of list        // using size() method        int size = list.size();         // Printing the size of list        System.out.println("Size of list = " + size);    }}
Before operation: [Geeks, for, Geeks]
Size of list = 3
kumar_satyam
solankimayank
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Multidimensional Arrays in Java
Exceptions in Java
Algorithms | Analysis of Algorithms | Question 8 - GeeksforGeeks

12 Feb, 2013
What is the time complexity of the below function?
void fun(int n, int arr[]){    int i = 0, j = 0;    for(; i < n; ++i)        while(j < n && arr[i] < arr[j])            j++;}
(A) O(n)(B) O(n^2)(C) O(nlogn)(D) O(n(logn)^2)Answer: (A)Explanation: In the first look, the time complexity seems to be O(n^2) due to two loops. But, please note that the variable j is not initialized for each value of variable i. So, the inner loop runs at most n times. Please observe the difference between the function given in question and the below function:
void fun(int n, int arr[]){    int i = 0, j = 0;    for(; i < n; ++i)    {        j = 0;        while(j < n && arr[i] < arr[j])            j++;    }}
Algorithms-Analysis of Algorithms
Analysis of Algorithms
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Graph Traversals | Question 2
Algorithms | Graph Traversals | Question 12
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Sorting | Question 5
Algorithms | Recursion | Question 2
Algorithms | Sorting | Question 7
Algorithms | Recursion | Question 5
Algorithms | Recursion | Question 9
How to Install ntopng in Linux? - GeeksforGeeks

22 Nov, 2021
ntopng is an Open Source Tool to monitor the network. It is a security network monitoring tool, also monitors web activities passively. It is also used for packet capturing, Traffic Recording, and Network Probing. A huge number of companies like Google, HP, Cisco, IBM, and many more uses ntop. It acts as a central network monitoring console. Packet capturing capacity of ntop is 10 Gbit. It supports major OS including Unix, Windows, and macOS X.
All the flows are stored in SQL Databases. REST API Integration is quite easy to achieve. Ntopng is a product of Ntop team having many more products like ntopng edge for high availability. 
Open Source
Easy to manage
Multiple kinds of analysis possible using filters
Realtime analysis
Supports third-party plugins
Easy to use WebUI
Customizable
Step 1: Enter in root user and run these commands:
sudo su -
apt-get update
apt-get upgrade
apt-get install software-properties-common wget
Step 2: Now, We will add the repository which contains the ntopng program
add-apt-repository universe
Step 3: Next, we have to install the package
apt install ntopng
During Installation, it will look like
After Installation, 
To check whether it is installed or not:
systemctl status ntopng
systemctl is a command used to check installed services in linux.
If it is running, then the output will be as below
If it is not running, then the output will be as below
To start it, use the command
systemctl start ntopng
To view the configuration file, 
cat /etc/ntopng/ntopng.conf
To choose the port use “–http-port” or “-w” option as
--http-port=:3000
Other options are also there like
--max-num-flows=200000
--max-num-hosts=250000
These are used to set the maximum number of flows and hosts respectively.
To run ntopng as daemon use option in config file “-e|–daemon” as
-e=<path_to_run>
 Or use the below command
systemctl enable ntopng
To run ntopng or to start the ntopng
ntopng 
This will run ntopng and view it use the URL in your browser
http://<ntopng IP Address>:<port>/
Example:
http://192.168.53.98:3000/
Enter the username as admin and password as admin, then you can view the ntopng
Here you can see we choose the http-port = 3000, and it is running on that port.
kk9826225
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
Matlab-Matrix - Subtraction

To subtract two matrices, both the operand matrices must have the same number of rows and columns.
Here is an example −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a - b
On execution in MATLAB the result is as follows −
>> a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a - b

c =

   -6  -3  -3
    2   5  -2
    2   1   8
   
>>

You can also make use of the minus() built-in function to subtract two matrices.
Consider the following example for use of minus() function for subtraction of two matrices −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = minus(a , b)
You will get the following result −
>> a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = minus(a , b)

c =

   -6  -3  -3
    2   5  -2
    2   1   8
 
>>


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Moment.js moment().millisecond() Method

19 May, 2022
The moment().millisecond()Method is used to get the milliseconds from the time or to set the milliseconds.
Syntax:
moment().millisecond();
// or
moment().milliseconds();
Parameters: This method accepts single parameter number that is used to set milliseconds then you will require an additional parameter:
Number: It ranges from 0 to 1000 and used to set milliseconds in a variable.
Return Value: This function returns the current time in milliseconds.
Note: This will not work in the normal Node.js program because it requires the moment.js library to be installed. 
Moment.js can be installed using the following command:
npm install moment
Example 1: Getting current time in milliseconds.
Javascript
// Acquiring the plugin const moment = require('moment');   var mili = moment().millisecond();   console.log("Current Milliseconds Time:", mili);
Output:
Current Milliseconds Time: 274
Example 2: Setting milliseconds time in a variable.
Javascript
// Acquiring the plugin const moment = require('moment');   var mili = moment(199).millisecond();   console.log("Milliseconds Time:", mili);
Output:
Milliseconds Time: 199
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React