code-rag-bench/online-tutorials huggingface dataset:
PyQt5 – Setting different toolTip to different item of ComboBox

04 May, 2020
In this article we will see how we can set different tooltip to the different items of the combo box. We can set tooltip to the combo box with the help of setToolTip method and for setting tooltip to the view part we have to use view object with this method. Below is the representation of how individual item tool tip look like.
In order to do we have to use the following method
combo_box.setItemData(index, tool_tip_text, QtCore.Qt.ToolTipRole)

Here index is the index of the item
tool_tip_text is the string which show as tool tip

Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys  class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box object        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # geek list        geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # setting tool tip to each item        self.combo_box.setItemData(0, "This is a tooltip for item[0]", QtCore.Qt.ToolTipRole)        self.combo_box.setItemData(1, "This is a tooltip for item[1]", QtCore.Qt.ToolTipRole)        self.combo_box.setItemData(2, "This is a tooltip for item[2]", QtCore.Qt.ToolTipRole)        self.combo_box.setItemData(3, "This is a tooltip for item[3]", QtCore.Qt.ToolTipRole)      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  window.show()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python PyQt5-ComboBox-stylesheet
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find common elements from multiple vectors in R ?

21 Apr, 2021
In this article, we will discuss how to find the common elements from multiple vectors in R Programming Language.
To do this intersect() method is used. It is used to return the common elements from two objects.
Syntax: intersect(vector1,vector2)
where, vector is the input data.
If there are more than two vectors then we can combine all these vectors into one except one vector. Those combined vectors are passed as one argument and that remaining vector is passed as second argument.
Syntax: intersect(c(vector1,vector2,...,vector n),vector_m)
Example 1: R program to create two vectors and find the common elements.
So we are going to create a vector with elements.
R
# create vector bb = c(2, 3, 4, 5, 6, 7)  # create vector aa = c(1, 2, 3, 4)  # combine both the vectorsprint(intersect(b, a))
Output:
[1] 2 3 4 
Example 2: R program to find common elements in two-character data.
We are taking two vectors which contain names and find the common elements.
R
# create vector bb = c("sravan", "gajji", "gnanesh")  # create vector aa = c("sravan", "ojaswi", "gnanesh")  # combine both the vectorsprint(intersect(b, a))
Output:
[1] "sravan" "gnanesh"
Example 3: Find common elements from multiple vectors in R.
So we are combining b and a first, and they are passed as the first argument in intersect function and then pass the d vector as the second argument.
R
# create vector bb = c(1, 2, 3, 4, 5)  # create vector aa = c(3, 4, 5, 6, 7)  # create vector dd = c(5, 6, 7, 8, 9)  # combine both the vectors b and a as 1 # then combine with dprint(intersect(c(b, a), d))
Output:
[1] 5 6 7
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.quiver() in Python - GeeksforGeeks

12 Apr, 2020
Matplotlib is a library of Python bindings which provides the user with a MATLAB-like plotting framework. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
matplotlib.pyplot.quiver method is used to plot a 2D field of arrows.
Syntax: matplotlib.pyplot.quiver(x_coordinate, y_coordinate, x_direction, y_direction)
Parameters:x_coordinate : x-coordinate of the arrow locationy_coordinate : y-coordinate of the arrow locationx_direction : x-component of the direction of the arrowy_direction : y-component of the direction of the arrow
Optional Parameters:scale: used to set the scale of the graphscale_units: used to set the units of the plane with respect to x and yangle: used to determine the angle of the arrow vectors plotted
Return Value : Returns a 2D graph with arrows plotted
Example #1
#Python program to explain# matplotlib.pyplot.quiver method    import matplotlib.pyplot as pltimport numpy as np   #defining necessary arraysx = np.linspace(0,2,8)y = np.linspace(2,0,8)x_dir = y_dir = np.zeros((8,8))y_dir[5,5] = 0.2   #plotting the 2D graphplt.quiver(x, y, x_dir, y_dir, scale=1)
Output:
Example #2Plotting multiple arrows on a graph using quiver method
# Python program to explain # matplotlib.pyplot.quiver method  # importing necessary librariesimport matplotlib.pyplot as plt  # defining necessary arraysx_coordinate = [0, 1.5]y_coordinate = [0.5, 1.5]x_direction = [1, -0.5]y_direction = [1, -1]  # plotting the graphplt.quiver(x_coordinate, y_coordinate,           x_direction, y_direction,           scale_units ='xy', scale = 1.)
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Write a C program to display the size and offset of structure members

Write a C program to define the structure and display the size and offsets of member variables
Structure − It is a collection of different datatype variables, grouped together under a single name.
datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};
Here, struct  - keyword
tagname - specifies name of structure
member1, member2 - specifies the data items that make up structure.
struct book{
   int pages;
   char author [30];
   float price;
};
There are three ways of declaring structure variables −
struct book{
   int pages;
   char author[30];
   float price;
}b;
struct{
   int pages;
   char author[30];
   float price;
}b;
struct book{
   int pages;
   char author[30];
   float price;
};
struct book b;
The link between a member and a structure variable is established using the member operator (or) dot operator.
Initialization can be done in the following ways −
struct book{
   int pages;
   char author[30];
   float price;
} b = {100, "balu", 325.75};
struct book{
   int pages;
   char author[30];
   float price;
};
struct book b = {100, "balu", 325.75};
struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, "balu");
b.price = 325.75;
struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
   scanf ("%d", &b.pages);
   scanf ("%s", b.author);
   scanf ("%f", &b. price);
Declare the structure with data members and try to print their offset values as well as size of the structure.
 Live Demo
#include<stdio.h>
#include<stddef.h>
struct tutorial{
   int a;
   int b;
   char c[4];
   float d;
   double e;
};
int main(){
   struct tutorial t1;
   printf("the size 'a' is :%d\n",sizeof(t1.a));
   printf("the size 'b' is :%d\n",sizeof(t1.b));
   printf("the size 'c' is :%d\n",sizeof(t1.c));
   printf("the size 'd' is :%d\n",sizeof(t1.d));
   printf("the size 'e' is :%d\n",sizeof(t1.e));
   printf("the offset 'a' is :%d\n",offsetof(struct tutorial,a));
   printf("the offset 'b' is :%d\n",offsetof(struct tutorial,b));
   printf("the offset 'c' is :%d\n",offsetof(struct tutorial,c));
   printf("the offset 'd' is :%d\n",offsetof(struct tutorial,d));
   printf("the offset 'e' is :%d\n\n",offsetof(struct tutorial,e));
   printf("size of the structure tutorial is :%d",sizeof(t1));
   return 0;
}
the size 'a' is :4
the size 'b' is :4
the size 'c' is :4
the size 'd' is :4
the size 'e' is :8
the offset 'a' is :0
the offset 'b' is :4
the offset 'c' is :8
the offset 'd' is :12
the offset 'e' is :16

size of the structure tutorial is :24
Java - String length() Method

This method returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.
Here is the syntax  of this method −
public int length()

Here is the detail of parameters −
NA
NA
This method returns the the length of the sequence of characters represented by this object.
This method returns the the length of the sequence of characters represented by this object.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialspoint.com");
      String Str2 = new String("Tutorials" );

      System.out.print("String Length :" );
      System.out.println(Str1.length());

      System.out.print("String Length :" );
      System.out.println(Str2.length());
   }
}
This will produce the following result −
String Length :29
String Length :9


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to use JavaScript variables in jQuery selectors?

It’s quite easy to use JavaScript variables in jQuery selectors.
Let’s seen an example to use JavaScript variables in jQuery to hide an element:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("input").click(function(){
        var name = this.name;
      $("input[name=" + name + "]").hide();
    } );    
});
</script>
</head>
<body>

<h1>Heading 1</h1>
<input type="text" id="bx"/>
<input type="button" name="bx" value="one"/><br>
<input type="text" id="by"/>
<input type="button" name="by" value="two"/>
<p>To hide the buttons, click on it.</p>

</body>
</html>
Time Series Decomposition In Python | by Billy Bonaros | Towards Data Science

Time series decomposition is a technique that splits a time series into several components, each representing an underlying pattern category, trend, seasonality, and noise. In this tutorial, we will show you how to automatically decompose a time series with Python.
To begin with, let's talk a bit about the components of a time series:
Seasonality: describes the periodic signal in your time series.Trend: describes whether the time series is decreasing, constant, or increasing over time.Noise: describes what remains behind the separation of seasonality and trend from the time series. In other words, it’s the variability in the data that cannot be explained by the model.
For this example, we will use the Air Passengers Data from Kaggle.
import pandas as pdimport numpy as npfrom statsmodels.tsa.seasonal import seasonal_decompose #https://www.kaggle.com/rakannimer/air-passengersdf=pd.read_csv(‘AirPassengers.csv’) df.head()
Firstly, we need to set as index the Month column and convert it into Datetime Object.
df.set_index('Month',inplace=True)df.index=pd.to_datetime(df.index)#drop null valuesdf.dropna(inplace=True)df.plot()
We will use Pythons statsmodels function seasonal_decompose.
result=seasonal_decompose(df['#Passengers'], model='multiplicable', period=12)
In seasonal_decompose we have to set the model. We can either set the model to be Additive or Multiplicative. A rule of thumb for selecting the right model is to see in our plot if the trend and seasonal variation are relatively constant over time, in other words, linear. If yes, then we will select the Additive model. Otherwise, if the trend and seasonal variation increase or decrease over time then we use the Multiplicative model.
Our data here are aggregated by month. The period we want to analyze is by year so that's why we set the period to 12.
We can get each component as follows:
result.seasonal.plot()
result.trend.plot()
Also, we can plot every component at once
result.plot()
Frequently, when looking at time series data it’s difficult to manually extract the trend or identify the seasonality. Fortunately, we can automatically decompose a time series and helps us have a clearer view of the components as It’s easier to analyze the trend if we remove the seasonality from our data and vise versa.
Originally published at https://predictivehacks.com.
Python | Pandas Panel.shape

30 Jun, 2021
In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data.In Pandas Panel.shape can be used to get a tuple of axis dimensions. 
Syntax: Panel.shapeParameters: NoneReturns: Return a tuple of axis dimensions 
Code #1:  
Python3
# importing pandas module import pandas as pd import numpy as np   df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'],                     'b': [11, 1.025, 333, 114.48, 1333]})                       data = {'item1':df1, 'item2':df1}   # creating Panel panel = pd.Panel.from_dict(data, orient ='minor')   print("panel['b'] is - \n\n", panel['b'], '\n')   print("\nSize of panel['b'] is - ", panel['b'].shape)  
Output:  
 Code #2:  
Python3
# importing pandas module import pandas as pd import numpy as np   df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'],                     'b': [11, 1.025, 333, 114.48, 1333]}) # Create a 5 * 5 dataframedf2 = pd.DataFrame(np.random.rand(10, 2), columns =['a', 'b'])   data = {'item1':df1, 'item2':df2}   # creating Panel panel = pd.Panel.from_dict(data, orient ='minor')print("panel['b'] is - \n\n", panel['b'], '\n')  print("\nShape of Panel is - ", panel['b'].shape)
Output:  
 Code #3:  
Python3
# importing pandas moduleimport pandas as pdimport numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'real'],                    'b': [-11, +1.025, -114.48, 1333]}) df2 = pd.DataFrame({'a': ['I', 'am', 'dataframe', 'two'],                    'b': [100, 100, 100, 100]})                     data = {'item1':df1, 'item2':df2} # creating Panelpanel = pd.Panel.from_dict(data, orient ='minor')print("panel['b'] is - \n\n", panel['b']) print("\nShape of panel['b'] is - ",  panel['b'].shape)
Output:  
Note: The panel has been removed from Pandas module 0.25.0 onwards.
Python3
#To check the version of pandas libraryimport pandasprint(pandas.__version__)
naveenkumarkharwal
Python pandas-panel
Python pandas-panel-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
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
How to create a new object from the specified object, where all the keys are in lowercase in JavaScript?

21 May, 2021
In this article, we will learn how to make a new object from the specified object where all the keys are in lowercase using JavaScript.
Example: 
Input: {RollNo : 1, Mark : 78}
Output: {rollno : 1, mark : 78}
Explanation: here, we have converted upper case to lower case keys values.
Approach 1: 
A simple approach is to Extract keys from Object and LowerCase to all keys and make Object with them. For this purpose we use Object.keys( ) to extract keys from object. And use String.toLowerCase() method to lower case keys and Array.reduce() method to make an object with lower-case strings. 
Example 1: 
HTML
<script>  // Test Object  const Student = { RollNo : 1, Mark: 78 };    // Function to lowercase keys   function Conv( obj , key )  {    obj[key.toLowerCase()] = Student[key];    return Student;  }    // Function to  create object from lowercase keys   function ObjKeys( obj) {    let arr1 = Object.keys(obj);    let ans = {};    for(let i of arr1)    {    Conv(ans,i);      }    return ans;  }    a = ObjKeys(Student);  console.log(a);  </script>
Output:
{ rollno : 1, mark : 78}
Approach 2:
The simplest approach is to convert Object to array and make keys to lower-case and make objects from a new array. For this purpose, we use Object.entries() to make an array from Object. And we use Array.map() to apply String.toLowerCase() method to all keys. To convert a new array to an Object we use Object.fromEntries().
Example:
HTML
<script>  // Test Object  const employ = { EmpId: 101, Batch: 56 };    // Converting Object to array   let k = Object.entries(employ);    //  Apply toLowerCase function to all keys   let l = k.map(function(t){    t[0] = t[0].toLowerCase()    return t;    }  );    // Converting back array to Object  const a  = Object.fromEntries(l)  console.log(a)</script>
Output:
{ empid : 101, batch : 56 } 
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.combine_first()

17 Oct, 2018
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 combine_first() method is used to combine two series into one. The result is union of the two series that is in case of Null value in caller series, the value from passed series is taken. In case of both null values at the same index, null is returned at that index.
Note: This method is different from Series.combine() which takes a function as parameter to decide output value.
Syntax: Series.combine_first(other)
Parameters:other: Other series to be combined with caller series.
Return type: Pandas series
Example:In this example, two series are created from list using Pandas Series() method. Some Null values are also passed to each list using Numpy np.nan. Both series are then combined using .combine_first() method. At first, the method is called by series1 and result is stored in result1 and then similarly it is called by series2 and stored in result2. Both of the returned series are then printed to compare outputs.
# importing pandas module  import pandas as pd      # importing numpy module import numpy as np     # creating series 1 series1 = pd.Series([70, 5, 0, 225, 1, 16, np.nan, 10, np.nan])     # creating series 2 series2 = pd.Series([27, np.nan, 2, 23, 1, 95, 53, 10, 5])   # combining and returning results to variable# calling on series1result1 = series1.combine_first(series2)  # calling on series2result2 = series2.combine_first(series1)  # printing resultprint('Result 1:\n', result1, '\n\nResult 2:\n', result2)
Output:As shown in the output, even though the same series were combined, but the outputs are different. This is because of combine_first() method prioritize first series ( Caller series ) before. If there is null value at that position, it takes value at same index from second series.
Result 1:
 0     70.0
1      5.0
2      0.0
3    225.0
4      1.0
5     16.0
6     53.0
7     10.0
8      5.0
dtype: float64 

Result 2:
 0    27.0
1     5.0
2     2.0
3    23.0
4     1.0
5    95.0
6    53.0
7    10.0
8     5.0
dtype: float64


Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Python Program to Print a given matrix in reverse spiral form

10 Jan, 2022
Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples.  
Input:
        1    2   3   4
        5    6   7   8
        9   10  11  12
        13  14  15  16
Output: 
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1
Input:
        1   2   3   4  5   6
        7   8   9  10  11  12
        13  14  15 16  17  18
Output: 
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
 
 
Python3
# Python3 Code to Print a given  # matrix in reverse spiral form  # This is a modified code of# https:#www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/R, C = 3, 6  def ReversespiralPrint(m, n, a):      # Large array to initialize it    # with elements of matrix    b = [0 for i in range(100)]      #/* k - starting row index    #l - starting column index*/    i, k, l = 0, 0, 0      # Counter for single dimension array    # in which elements will be stored    z = 0      # Total elements in matrix    size = m * n      while (k < m and l < n):                  # Variable to store value of matrix.        val = 0          # Print the first row         # from the remaining rows         for i in range(l, n):                          # printf("%d ", a[k][i])            val = a[k][i]            b[z] = val            z += 1        k += 1          # Print the last column        # from the remaining columns        for i in range(k, m):              # printf("%d ", a[i][n-1])            val = a[i][n - 1]            b[z] = val            z += 1          n -= 1          # Print the last row         # from the remaining rows        if (k < m):            for i in range(n - 1, l - 1, -1):                                  # printf("%d ", a[m-1][i])                val = a[m - 1][i]                b[z] = val                z += 1          m -= 1          # Print the first column         # from the remaining columns         if (l < n):            for i in range(m - 1, k - 1, -1):                                  # printf("%d ", a[i][l])                val = a[i][l]                b[z] = val                z += 1            l += 1      for i in range(size - 1, -1, -1):        print(b[i], end = " ")  # Driver Codea = [[1, 2, 3, 4, 5, 6],     [7, 8, 9, 10, 11, 12],     [13, 14, 15, 16, 17, 18]]  ReversespiralPrint(R, C, a)  # This code is contributed by mohit kumar
Output: 
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
Please refer complete article on Print a given matrix in reverse spiral form for more details!
pattern-printing
spiral
Matrix
Python
Python Programs
School Programming
pattern-printing
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Find the longest path in a matrix with given constraints
Find median in row wise sorted matrix
Zigzag (or diagonal) traversal of Matrix
Traverse a given Matrix using Recursion
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
How to check if an application is open in Python?

24 Feb, 2021
This article is about How to check if an application is open in a system using Python. You can also refer to the article Python – Get list of running processes for further information.
In the below approaches, we will be checking if chrome.exe is open in our system or not.
The psutil is a system monitoring and system utilization module of python. It is useful mainly for system monitoring, profiling and limiting process resources, and management of running processes. Usage of resources like CPU, memory, disks, network, sensors can be monitored. It is supported in Python versions 2.6, 2.7, and 3.4+. You can install psutil module by using the following command
pip install psutil
We will use the psutil.process_iter() method, it returns an iterator yielding a process class instance for all running processes on the local machine.
Python3
# import moduleimport psutil  # check if chrome is open"chrome.exe" in (i.name() for i in psutil.process_iter())
Output:
True
We import the psutil module. Then we search for chrome.exe in all running processes on the local machine using psutil.process_iter(). If found it will return output as TRUE, else FALSE.
The wmi module can be used to gain system information of a Windows machine and can be installed using the below command: 
pip install wmi
Its working is similar to psutil. Here, we check if a particular process name is present in the list of running processes.
Python3
# Import moduleimport wmi  # Initializing the wmi constructorf = wmi.WMI()  flag = 0  # Iterating through all the running processesfor process in f.Win32_Process():    if "chrome.exe" == process.Name:        print("Application is Running")        flag = 1        break  if flag == 0:    print("Application is not Running")
Output:
Application is Running
We import the wmi module. Then we search for chrome.exe in all running processes on the local machine by iterating through the process names. If it matches with the process. Name, it will print Application is Running, else Application is not Running.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Python | Pandas DatetimeIndex.quarter

24 Dec, 2018
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 DatetimeIndex.quarter attribute outputs the quarter of the date for each entries in the DatetimeIndex object.
Syntax: DatetimeIndex.quarter
Return: Index object
Example #1: Use DatetimeIndex.quarter attribute to find the quarter of the date for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'M' represents Monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M',                               periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find quarter of the date for each entries in the DatetimeIndex object.
# find the quarter of datedidx.quarter
Output :As we can see in the output, the function has returned an Index object containing the quarter value of the date for each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.quarter attribute to find the quarter of the date for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'Q' represents Quarterly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='Q',                           periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :Now we want to find quarter of the date for each entries in the DatetimeIndex object.
# find the quarter of datedidx.quarter
Output :As we can see in the output, the function has returned an Index object containing the quarter value of the date for each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Running Extra scripts in Django

16 Mar, 2021
Running extra scripts or processes is always needed when you have some new idea that works with web development and in Python!!! it is always.
It can be any script that may include a loading of data, processing, and cleaning of data, or any ML phase when making an application providing business logic directly in views or models is not always best. As django conventions refer to ‘thin views’, we must try to trim out the logic and try to embed it in some other files.
Django extensions in a package that enables you to run the extra scripts you need to install it using pip, use terminal and type
pip install django-extensions        
add the django-extensions in installed apps found in setting.py file
INSTALLED_APPS = [
    ...
    ...
    'django_extensions',
]
Now create a folder named scripts in your project that will contain all the python files which you can execute add an empty python file named ‘__init__.py’ this specifies that scripts in also part of Django projects
create new files that will contain the code that you need to execute, name anything you like
example: To load data from CSV files to the database before running the server
load.py
import csv
from site.models import Destination

def run():
    # All data in run method only will be executed 
    fhand = open('location.csv')
    reader = csv.reader(fhand)
    next(reader)
    
    for row in reader:
        latitude = row[0]
        longitude = row[1]
        name = row[2]
        item = Destination.objects.create(name=name,latitude=latitude,longitude=longitude)
        item.save()
        
    print("Data Added")
Now to run the script simply fire the command as below where ‘load’ is a file name
python manage.py runscript load
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between SCTP and TCP

09 May, 2022
1. Stream Control Transmission Protocol (SCTP) : SCTP is connection- oriented protocol in computer networks which provides full-duplex association i.e., transmitting multiple streams of data between two end points at the same time that have established connection in network. 
2. Transmission Control Protocol (TCP) : TCP is connection oriented reliable protocol which supports guaranteed data transmission. TCP provides reliable data transmission from the connection establishment itself. 
Difference between SCTP and TCP :
navinpatnacitynav
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
GSM in Wireless Communication
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
What are C++ Integer Constants?

Integer constants are constant data elements that have no fractional parts or exponents. They always begin with a digit. You can specify integer constants in decimal, octal, or hexadecimal form. They can specify signed or unsigned types and long or short types.
In C++ you can use the following code to create an integer constant −
#include<iostream>
using namespace std;
int main() {
   const int x = 15; // 15 is decimal integer constant while x is a constant int.
   int y = 015; // 15 is octal integer constant while y is an int.
   return 0;
}
You can find the complete grammar to specify integer constants on https://msdn.microsoft.com/en-us/library/00a1awxf.aspx.
C++ "Hello, World!" Program

C++ is a general purpose programming language that supports procedural, object-oriented and generic programming. C++ is a superset of C and all valid C programs are valid in C++ as well.
C++ supports object oriented programming with features such as data hiding, encapsulation, inheritance, polymorphism etc.
Let us see the first C++ program that prints Hello, World!.
#include <iostream>
using namespace std;
int main() {
   cout << "Hello, World!" << endl; // This prints Hello, World!
   return 0;
}
The output of the above program is as follows −
Hello, World!
The different parts of the above program are explained as follows.
There are different headers in C++, each of which contain information that is necessary in the program. The header  is used in this program which provides basic input and output services for C++ programs.
Namespaces are a relatively recent addition to C++. The following line we saw above informs the compiler to use the std namespace −
using namespace std;
The program execution begins with the following line as the main() function is the entry point of any C++ program.
int main()
The message “Hello, World!” is displayed on the screen using the following statement −
cout << "Hello, World!" << endl;
Here, cout is an object of the class ostream and is associated with the standard C output stream stdout.
Single line comments in C++ begin with //. They are used to make the program easier to understand and are ignored by the compiler. The following comment in the above program is to clarify the purpose of the cout statement to the programmers.
// This prints Hello, World!
The termination of the main() function is signalled by the return(0); statement. After this, the value 0 is returned to the calling process.
DataTransfer object in HTML5

The event listener methods for all the drag and drop events accept Event object that has a readonly attribute called dataTransfer. The event.dataTransfer returns DataTransfer object associated with the event as follows:
function EnterHandler(event) {
   DataTransfer dt = event.dataTransfer;
   ...
}
You can try to run the following code to implement DataTransfer object:
<!DOCTYPE HTML>
<html>
   <head>
      <style>
         #boxA, #boxB { float:left;padding:10px;margin:10px; -moz-user-select:none; }
         #boxA { background-color: #6633FF; width:75px; height:75px; }
         #boxB { background-color: #FF6699; width:150px; height:150px; }
      </style>

      <script>
         function dragStart(ev) {
            ev.dataTransfer.effectAllowed='move';
            ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
            ev.dataTransfer.setDragImage(ev.target,0,0);
         return true;
         }
      </script>
   </head>

   <body>
      <center>
         <h2>Drag and drop HTML5 demo</h2>
         <div>Try to drag the purple box around.</div>
         <div id = "boxA" draggable = "true" ondragstart = "return dragStart(ev)">
            <p>Drag Me</p>
         </div>
         <div id = "boxB">Dustbin</div>
      </center>
   </body>
</html>
How to Use SELECT In Order BY Specific Ids in SQL? - GeeksforGeeks

28 Oct, 2021
The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending). In this article, we will be doing order by on a database with some specified values of the column only.
So let’s start by creating a Database first.
Step 1: Create a database
Query:
CREATE DATABASE GFG
Step 2: Use database
Query:
USE GFG
Step 3: Create a table
Query:
CREATE TABLE s_marks 
(
studentid int PRIMARY KEY, 
subjectid VARCHAR(10), 
professorid int
)
Step 4: Insert some data in the table
Query:
INSERT INTO [dbo].[s_marks]
           ([studentid]
           ,[subjectid]
           ,[professorid])
     VALUES(1, 'DSA', 6)
GO 

INSERT INTO [dbo].[s_marks]
           ([studentid]
           ,[subjectid]
           ,[professorid])
     VALUES(2, 'Compiler', 7)
GO

INSERT INTO [dbo].[s_marks]
           ([studentid]
           ,[subjectid]
           ,[professorid])
     VALUES(3, 'ML', 8)
GO 

INSERT INTO [dbo].[s_marks]
           ([studentid]
           ,[subjectid]
           ,[professorid])
     VALUES(4, 'AI', 9)
GO 
Step 5: Get the table data according to student id and order by using some ids.
Query:
SELECT studentid, subjectid FROM s_marks 
    WHERE studentid 
    IN
    (1,4)
    ORDER BY studentid DESC
Output:
So we can see that data is printed successfully with the order by as well as the respective ids.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | DROP, TRUNCATE
How to Select Data Between Two Dates and Times in SQL Server?
SQL vs NoSQL: Which one is better to use?
Advanced SQL Interview Questions
SQL | OFFSET-FETCH Clause
Insert multiple values into multiple tables using a single statement in SQL Server
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Comments
SQL | CREATE
Adding multiple constraints in a single table
DynamoDB - Delete Table

In this chapter, we will discuss regarding how we can delete a table and also the different ways of deleting a table.
Table deletion is a simple operation requiring little more than the table name. Utilize the GUI console, Java, or any other option to perform this task.
Perform a delete operation by first accessing the console at −
https://console.aws.amazon.com/dynamodb.
Choose Tables from the navigation pane, and choose the table desired for deletion from the table list as shown in the following screeenshot.
Finally, select Delete Table. After choosing Delete Table, a confirmation appears. Your table is then deleted.
Use the delete method to remove a table. An example is given below to explain the concept better.
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; 
import com.amazonaws.services.dynamodbv2.document.DynamoDB; 
import com.amazonaws.services.dynamodbv2.document.Table;  

public class ProductsDeleteTable {  
   public static void main(String[] args) throws Exception {  
      AmazonDynamoDBClient client = new AmazonDynamoDBClient() 
         .withEndpoint("http://localhost:8000"); 
      
      DynamoDB dynamoDB = new DynamoDB(client);  
      Table table = dynamoDB.getTable("Products");  
      try { 
         System.out.println("Performing table delete, wait..."); 
         table.delete(); 
         table.waitForDelete(); 
         System.out.print("Table successfully deleted.");  
      } catch (Exception e) { 
         System.err.println("Cannot perform table delete: "); 
         System.err.println(e.getMessage()); 
      } 
   } 
}   

    16 Lectures 
     1.5 hours 

 Harshit Srivastava

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    48 Lectures 
     3 hours 

 Niyazi Erdogan

    13 Lectures 
     1 hours 

 Harshit Srivastava

    45 Lectures 
     4 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Position of the K-th set bit in a number in C++

In this problem, we are given two integers N and K. Our task is to find the index of Kth set a bit of the number N, counted from right.
Set bits are checked from the binary representation of the number. The indexing in binary representation starts from index 0 from the right direction and propagates towards left.
Example − in the binary number ‘011101’, at index 0 from right we have 1, at index 1 from right we have 0, and so on.
Now, let’s take an example to understand the problem
Input − N = 6, K = 2
Output − 2
Explanation − The binary representation of 6 is 0110. The 2nd set bit from the right will be at index 2.
To solve this problem, we will have to check if the current bit is set, if it is then we will decrease the value of K. After every check, we will shift the number bt 1, this will give the next bit, also we will maintain the number of shifts done. Once the value of K becomes 0, we will print the count of shifts done.
Program to show the implementation of our logic
 Live Demo
#include <iostream>
using namespace std;
int FindIndexKthBit(int N, int K) {
   int index=0;
   while (N) {
      if (N & 1)
         K--;
      if (!K)
         return index;
      index++;
      N = N >> 1;
   }
   return -1;
}
int main() {
   int N = 12, K = 2;
   cout<<"The "<<K<<"th set bit of the number "<<N<<" is at index : \t";
   int index = FindIndexKthBit(N, K);
   if (index!=-1)
      cout<<index;
   else
      cout<<"\nsorry no index found";
   return 0;
}
The 2th set bit of the number 12 is at index : 3
MongoDB query to fetch array values

Use find() along with $elemMatch to fetch array values. Let us first create a collection with documents −
> db.fetchingArrayValuesDemo.insertOne(
... {
...    "StudentName": "David",
...    "StudentDetails": [
...       {
...          "FatherName": "Bob",
...          "CountryName": "US",
...
...          "Favourite": [
...             {
...                "Teacher": "DAVID",
...                "Subject": [
...                   "MySQL",
...                   "MongoDB",
...                   "Java"
...                ],
...                "Marks": [
...                   50,
...                   60,
...                   65
...                ]
...             }
...          ]
...
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06fc3425ddae1f53b621fa")
}
> db.fetchingArrayValuesDemo.insertOne(
...    {
...       "StudentName": "Robert",
...       "StudentDetails": [
...          {
...             "FatherName": "Sam",
...             "CountryName": "AUS",
...
...             "Favourite": [
...                {
...                   "Teacher": "MIKE",
...                   "Subject": [
...                      "Python",
...                      "C",
...                      "C++"
...                   ],
...                   "Marks": [
...                      76,
...                      89,
...                      91
...                   ]
...                }
...             ]
...
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06fc6825ddae1f53b621fb")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.fetchingArrayValuesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] }
{ "_id" : ObjectId("5e06fc6825ddae1f53b621fb"), "StudentName" : "Robert", "StudentDetails" : [ { "FatherName" : "Sam", "CountryName" : "AUS", "Favourite" : [ { "Teacher" : "MIKE", "Subject" : [ "Python", "C", "C++" ], "Marks" : [ 76, 89, 91 ] } ] } ] }
Here is the query to fetch array values −
> db.fetchingArrayValuesDemo.find({
...    StudentDetails:{
...       $elemMatch: {
...          Favourite: {
...             $elemMatch: {
...                Teacher: "DAVID"
...             }
...          }
...       }
...    }
... });
This will produce the following output −
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] }
How are arguments passed by value or by reference in Python?

Python uses a mechanism, which is known as "Call-by-Object", sometimes also called "Call by Object Reference" or "Call by Sharing"
If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like Call-by-value. It's different, if we pass mutable arguments.
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
student={'Archana':28,'krishna':25,'Ramesh':32,'vineeth':25}
def test(student):
   new={'alok':30,'Nevadan':28}
   student.update(new)
   print("Inside the function",student)
   return
test(student)
print("outside the function:",student)
Inside the function {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}
outside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}
cPanel - Logging into cPanel Dashboard

In this chapter, we will learn to login into the cPanel Dashboard. For logging into the dashboard, you will need your login credentials. This information is sent to you, when you have signed up for cPanel hosting or you may have created during purchase of hosting.
cPanel Dashboard is accessible by two ports – 2082 for unsecured connections and 2083 for secured connection, many hosting providers support unsecured connections, but it is always recommended that you should use a secured connection only.
There are many ways to find the login screen of a cPanel. Recommended is that you may use the IP address of your cPanel, you may find the cPanel using IP address by typing the following in address bar −
https://<your_IP_address>:2083 
https://<your_IP_address>/cpanel

If you have already updated your Nameservers for your domain, then you may use your domain for directly accessing cPanel by your domain. You may find cPanel login screen using your domain by typing the following into the address bar −
https://<your_domain>:2083 
https://<your_domain>/cpanel

Once you are redirected to your login screen, you will find the login screen like shown below.
You can enter the Username and Password and press the Log in button to login into the cPanel Dashboard.

    10 Lectures 
     47 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Barnsley Fern in Python

In this tutorial, we are going to learn about the Barnsley Fern, which is created by Michael Barnsley. The features of Barnsley Fern is similar to the fern shape. It is created by iterating over the four mathematical equations known as Iterated Function System(IFS). The transformation has the following formula.
f(x,y)=[abcd][xy]+[ef]
Source − Wikipedia
The values of the variables are −
Source − Wikipedia
The four equation that Barnsley Fern proposed are −
Source − Wikipedia
Now, we will see code to create the fern shape in Python.
# importing matplotlib module for the plot
import matplotlib.pyplot as plot
# importing random module to generate random integers for the plot
import random
# initialising the lists
x = [0]
y = [0]
# initialising a variable to zero to track position
current = 0
for i in range(1, 1000):
   # generating a random integer between 1 and 100
   z = random.randint(1, 100)
   # checking the z range and appending corresponding values to x and y
   # appending values to the x and y
   if z == 1:
      x.append(0)
      y.append(0.16 * y[current])
   if z >= 2 and z <= 86:
      x.append(0.85 * x[current] + 0.04 * y[current])
      y.append(-0.04 * x[current] + 0.85 * y[current] +1.6)
   if z>= 87 and z<= 93:
      x.append(0.2 * x[current] - 0.26 * y[current])
      y.append(0.23 * x[current] + 0.22*(y[current])+1.6)
   if z >= 94 and z <= 100:
      x.append(-0.15 * x[current] + 0.28 * y[current])
      y.append(0.26 * x[current] + 0.24 * y[current] + 0.44)
   # incrementing the current value
   current += 1
# plotting the graph using x and y
plot.scatter(x, y, s = 0.2, edgecolor = 'green')
plot.show()
If you run the above code, you will get the following result.
If you have any doubts in the tutorial, mention them in the comment section.
Reference −Wikipedia