code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Period.month

06 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 Period.month attribute return an integer value. The returned value represents the value of month in the given period object. January being 1 to December being 12.
Syntax : Period.month
Parameters : None
Return : month
Example #1: Use Period.month attribute to find the value of month in the given Period object.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2,                 day = 21, hour = 8, minute = 21)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.month attribute to find out value of month in prd object.
# return value of monthprd.month
Output :
As we can see in the output, the Period.month attribute has returned 2 indicating that the given period object has ‘February’ as a month.
Example #2: Use Period.month attribute to find the value of month in the given Period object.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.month attribute to find out value of month in prd object.
# return value of monthprd.month
Output :
As we can see in the output, the Period.month attribute has returned 10 indicating that the given period object has ‘October’ as a month.
Pandas scalar-period
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
Convert integer to string in Python
Python program to print even numbers in a list

23 Jun, 2022
Given a list of numbers, write a Python program to print all even numbers in the given list.
Example: 
Input: list1 = [2, 7, 5, 64, 14]
Output: [2, 64, 14]

Input: list2 = [12, 14, 95, 3]
Output: [12, 14]
Iterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then only print the number. 
Python3
# Python program to print Even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1:     # checking condition    if num % 2 == 0:        print(num, end=" ")
Output: 
10, 4, 66
Python3
# Python program to print Even Numbers in a List # list of numberslist1 = [10, 24, 4, 45, 66, 93]num = 0 # using while loopwhile(num < len(list1)):     # checking condition    if list1[num] % 2 == 0:        print(list1[num], end=" ")     # increment num    num += 1
Output: 
10, 4, 66
Python3
# Python program to print even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # using list comprehensioneven_nos = [num for num in list1 if num % 2 == 0] print("Even numbers in the list: ", even_nos)
Output: 
Even numbers in the list:  [10, 4, 66]
Python3
# Python program to print Even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11]  # we can also print even no's using lambda exp.even_nos = list(filter(lambda x: (x % 2 == 0), list1)) print("Even numbers in the list: ", even_nos)
Output: 
Even numbers in the list:  [10, 4, 66]
Method 5: Using Recursion
Python3
#Python program to print#even numbers in a list using recursiondef evennumbers(list, n=0):    #base case    if n==len(list):        exit()    if list[n]%2==0:        print(list[n], end=" ")    #calling function recursively    evennumbers(list, n+1)list1 = [10, 21, 4, 45, 66, 93]print("Even numbers in the list:", end=" ")evennumbers(list1)#this code is contributed by Shivesh Kumar Dwivedi
Even numbers in the list: 10 4 66 
aveekdas1
cpdwivedi916
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Ethical Hacking - Exploitation

Exploitation is a piece of programmed software or script which can allow hackers to take control over a system, exploiting its vulnerabilities. Hackers normally use vulnerability scanners like Nessus, Nexpose, OpenVAS, etc. to find these vulnerabilities.
Metasploit is a powerful tool to locate vulnerabilities in a system.
Based on the vulnerabilities, we find exploits. Here, we will discuss some of the best vulnerability search engines that you can use.
www.exploit-db.com is the place where you can find all the exploits related to a vulnerability.
Common Vulnerabilities and Exposures (CVE) is the standard for information security vulnerability names. CVE is a dictionary of publicly known information security vulnerabilities and exposures. It’s free for public use. https://cve.mitre.org
National Vulnerability Database (NVD) is the U.S. government repository of standards based vulnerability management data. This data enables automation of vulnerability management, security measurement, and compliance. You can locate this database at − https://nvd.nist.gov
NVD includes databases of security checklists, security-related software flaws, misconfigurations, product names, and impact metrics.
In general, you will see that there are two types of exploits −
Remote Exploits − These are the type of exploits where you don’t have access to a remote system or network. Hackers use remote exploits to gain access to systems that are located at remote places.
Remote Exploits − These are the type of exploits where you don’t have access to a remote system or network. Hackers use remote exploits to gain access to systems that are located at remote places.
Local Exploits − Local exploits are generally used by a system user having access to a local system, but who wants to overpass his rights.
Local Exploits − Local exploits are generally used by a system user having access to a local system, but who wants to overpass his rights.
Vulnerabilities generally arise due to missing updates, so it is recommended that you update your system on a regular basis, for example, once a week.
In Windows environment, you can activate automatic updates by using the options available in the Control Panel → System and Security → Windows Updates.
In Linux Centos, you can use the following command to install automatic update package.
yum -y install yum-cron


    36 Lectures 
     5 hours 

 Sharad Kumar

    31 Lectures 
     3.5 hours 

 Abhilash Nelson

    22 Lectures 
     3 hours 

 Blair Cook

    74 Lectures 
     4.5 hours 

 199courses

    75 Lectures 
     4.5 hours 

 199courses

    148 Lectures 
     28.5 hours 

 Joseph Delgadillo
 Print
 Add Notes
 Bookmark this page
How to check whether a form or a control is valid or not in Angular 10 ? - GeeksforGeeks

03 Jun, 2021

In this article, we are going to check whether a form is touched or not in Angular 10. The valid property is used to report that the control or the form is valid or not.
Syntax:
form.valid
Return Value:
boolean: the boolean value to check whether a form is valid or not.
NgModule: Module used by the valid property is:
FormsModule
 
Approach: 
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using the valid property.
Serve the angular app using ng serve to see the output.
Example:
Javascript
 

 
 










import { Component } from '@angular/core'; 
import { FormGroup, FormControl,  
    FormArray, Validators } from '@angular/forms'
  
@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html'
}) 
  
export class AppComponent { 
    form = new FormGroup({ 
        name: new FormControl( 
  
        ), 
        rollno: new FormControl() 
    }); 
  
    get name(): any { 
        return this.form.get('name'); 
    } 
  
    onSubmit(): void { 
        console.log("Form is valid : ", this.form.valid); 
    } 
} 






app.component.html
 

 
 










<form [formGroup]="form" (ngSubmit)="onSubmit()"> 
    <input formControlName="name" placeholder="Name"> 
    <br> 
      
    <button type='submit'>Submit</button> 
    <br><br> 
</form> 






Output:
Reference: >https://angular.io/api/forms/AbstractControlDirective#valid

Angular10


AngularJS-Questions


AngularJS


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
divisibleBy() function over array in JavaScript

We are required to write a JavaScript function that takes in an array of numbers and a single number as two arguments.
Our function should filter the array to contain only those numbers that are divisible by the number provided as second argument and return the filtered array.
Following is the code −
 Live Demo
const arr = [56, 33, 2, 4, 9, 78, 12, 18];
const num = 3;
const divisibleBy = (arr = [], num = 1) => {
   const canDivide = (a, b) => a % b === 0;
   const res = arr.filter(el => {
      return canDivide(el, num);
   });
   return res;
};
console.log(divisibleBy(arr, num));
[ 33, 9, 78, 12, 18 ]
Convert.ToInt16 Method in C#

Convert a specified value to a 16-bit signed integer using the Convert.ToInt16 method in C#.
We have a double variable with a value initialized to it.
double doubleNum = 3.456;
Now, let us convert it to Int16 i.e. short.
short shortNum;
shortNum = Convert.ToInt16(doubleNum);
Here is the complete example −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      double doubleNum = 3.456;
      short shortNum;
      shortNum = Convert.ToInt16(doubleNum);
      Console.WriteLine("Converted {0} to {1}", doubleNum, shortNum);
   }
}
Converted 3.456 to 3
How to write your own header file in C?


Here we will see how to create own header file using C. To make a header file, we have to create one file with a name, and extension should be (*.h). In that function there will be no main() function. In that file, we can put some variables, some functions etc.
To use that header file, it should be present at the same directory, where the program is located. Now using #include we have to put the header file name. The name will be inside double quotes. Include syntax will be look like this.
#include”header_file.h”
Let us see one program to get the idea.
int MY_VAR = 10;
int add(int x, int y){
   return x + y;
}
int sub(int x, int y){
   return x - y;
}
int mul(int x, int y){
   return x * y;
}
int negate(int x){
   return -x;
}
#include <stdio.h>
#include "my_header.h"
main(void) {
   printf("The value of My_VAR: %d\n", MY_VAR);
   printf("The value of (50 + 84): %d\n", add(50, 84));
   printf("The value of (65 - 23): %d\n", sub(65, 23));
   printf("The value of (3 * 15): %d\n", mul(3, 15));
   printf("The negative of 15: %d\n", negate(15));
}
The value of My_VAR: 10
The value of (50 + 84): 134
The value of (65 - 23): 42
The value of (3 * 15): 45
The negative of 15: -15
Set a linear gradient as the background image with CSS

Set a linear gradient as the background image, with linear-gradient() CSS function. You can try to run the following code to implement linear-gradient() function in CSS
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #demo {
            height: 200px;
            background: linear-gradient(green, orange, maroon);
         }
      </style>
   </head>
   <body>
      <p>Setting background as linear gradient.</p>
      <div id = "demo"></div>
   </body>
</html>
Pascal - goto Statement

A goto statement in Pascal provides an unconditional jump from the goto to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto. 
The syntax for a goto statement in Pascal is as follows −
goto label;
   ...
   ...
label: statement;

Here, label must be an unsigned integer label, whose value can be from 1 to 9999. 
The following program illustrates the concept.
program exGoto;
label 1; 
var
   a : integer;

begin
   a := 10;
   (* repeat until loop execution *)
   1: repeat
      if( a = 15) then
      
      begin
         (* skip the iteration *)
         a := a + 1;
         goto 1;
      end;
      
      writeln('value of a: ', a);
      a:= a +1;
   until a = 20;
end.
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Please note that −
In Pascal, all labels must be declared before constant and variable declarations. 
In Pascal, all labels must be declared before constant and variable declarations. 
The if and goto statements may be used in the compound statement to transfer control out of the compound statement, but it is illegal to transfer control into a compound statement. 
The if and goto statements may be used in the compound statement to transfer control out of the compound statement, but it is illegal to transfer control into a compound statement. 

    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python 3 - String startswith() Method

The startswith() method checks whether the string starts with str, optionally restricting the matching with the given indices start and end.
Following is the syntax for startswith() method −
str.startswith(str, beg = 0,end = len(string));

str − This is the string to be checked.
str − This is the string to be checked.
beg − This is the optional parameter to set start index of the matching boundary.
beg − This is the optional parameter to set start index of the matching boundary.
end − This is the optional parameter to set start index of the matching boundary.
end − This is the optional parameter to set start index of the matching boundary.
This method returns true if found matching string otherwise false.
The following example shows the usage of startswith() method.
#!/usr/bin/python3

str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))
When we run above program, it produces the following result −
True
True
False


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
stack empty() and stack size() in C++ STL

In this article we will be discussing the working, syntax and examples of stack::empty() and stack::size() function in C++ STL.
Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do
insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack we then also remove it from the top.
stack::empty() function is an inbuilt function in C++ STL, which is defined in <stack>header file. empty() is used to check whether the associated container is empty or not and return true or false accordingly.
The function checks the container should be empty means the size of the container should be 0.
stack_name.empty();
The function accepts no parameter(s).
This function returns true if the container is empty, else false.
Input 
std::stack<int> stack1;
stack1.emplace(1);
stack1.emplace(2);
stack1.emplace(3);
stack1.empty();
Output 
false
Input 
std::stack<int> stack2;
stack2.empty();
Output 
true
 Live Demo
#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   int Product = 1;
   stck.push(1);
   stck.push(2);
   stck.push(3);
   stck.push(4);
   stck.push(5);
   stck.push(6);
   while (!stck.empty()){
      Product = Product * stck.top();
      stck.pop();
   }
   cout<<"\nProduct of elements in stack are: "<<Product;
   return 0;
}
If we run the above code it will generate the following output −
Product of elements in stack are: 720
stack::size() function is an inbuilt function in C++ STL, which is defined in <stack>header file. size() is used to check the associated container’s size and return the result in an integer value, which is the number of elements in the container.
If the container is empty the size() returns 0
stack_name.size();
The function accepts no parameter(s).
This function returns the size of the container
Input 
std::stack<int> stack1;
stack1.emplace(1);
stack1.emplace(2);
stack1.emplace(3);
stack1.size();
Output 
3
Input
std::stack<int> stack2;
stack2.size();
Output 
0
 Live Demo
#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   int Product = 1;
   stck.push(1);
   stck.push(2);
   stck.push(3);
   stck.push(4);
   stck.push(5);
   stck.push(6);
   cout<<"size of stack is: "<<stck.size();
   while (stck.size()>0){
      Product = Product * stck.top();
      stck.pop();
   }
   cout<<"\nProduct of elements in stack are: "<<Product;
   return 0;
}
If we run the above code it will generate the following output −
size of stack is: 6
Product of elements in stack are: 720
How to list the directory content in PowerShell?

To display the directory content, Get-ChildItem cmdlet is used. You need to provide the path of the directory or if you are in the same directory, you need to use only Get-ChildItem directly. In the below example, we need to display the contents of the D:\temp directory.
When Get-ChildItem command is run outside of this directory then the path of the directory should be provided. This is called the absolute path.
PS C:\> Get-ChildItem D:\Temp\
When this command is run directly within the directory then simply run this command. This is called a relative path.
PS D:\Temp> Get-ChildItem

Directory: D:\Temp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       13-12-2019     09:52                GPO_backup
d-----       24-11-2018     11:31                LGPO
-a----       07-05-2018     23:00            301 cars.xml
-a----       29-12-2017     15:16           4526 healthcheck.html
-a----       29-12-2017     15:16           4526 healthcheck1.html
-a----       08-12-2017     10:24          48362 servicereport.html
-a----       08-12-2017     10:24          48362 servicereport1.html
-a----       08-12-2017     10:16            393 style.css
-a----       08-12-2017     11:29           7974 Test.xlsx
-a----       25-10-2017     08:13            104 testcsv.csv
-a----       12-12-2017     23:04           1034 testhtmoutput.html
Please note − Get-ChildItem command only displays the folders and files but not the content of the subfolders. To display the subfolders and their files, you need to use –Recursive parameter.
Print the matrix diagonally downwards in C Program.

Given with an array of size n x n and the task is to print the matrix elements of integer type diagonally downwards.
Diagonally downwards means printing the array of any size of n x n in diagonally moving downward like in the figure given below −
Firstly it will print 1 and then move to 2 print it and moves down to 4 diagonally and print it and so on.
Input: Matrix [3][3] = {
   { 1, 2, 3 },
   { 4, 5, 6 },
   { 7, 8, 9 }}
Output: 1 2 4 3 5 7 6 8 9
int diagonally_down(int mat[n][n])
START
STEP 1: DECLARE i, j, row, col AS INT
STEP 2: LOOP FOR i = 0 AND i < n AND i++
   SET row = 0
   SET col = i
   LOOP WHILE col >= 0
      PRINT mat[row][col]
      INCREMENT row BY 1 AND DECREMENT col BY 1
   END WHILE
END FOR
STEP 3: LOOP FOR j = 1 AND j < n AND j++
   SET row = j
   SET col = n-1
   LOOP WHILE row < n
      PRINT mat[row][col]
      INCREMENT row BY 1 AND DECREMENT col BY 1
   END WHILE
END FOR
STOP
#include <stdio.h>
#define n 3
int diagonally_down(int mat[n][n]){
   int i, j, row, col;
   //printing above elements
   for (i = 0; i < n; i++){
      row = 0;
      col = i;
      while(col >= 0) //Moving downwards from the first row{
         printf("%d ", mat[row++][col--]);
      }
   }
   //printing below elements
   for (j = 1; j < n; j++){
      row = j;
      col = n-1;
      while(row<n) //Moving from the last column{
         printf("%d ", mat[row++][col--]);
      }
   }
}
int main(int argc, char const *argv[]){
   int mat[][n] = {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
   };
   diagonally_down(mat);
   return 0;
}
If we run above program then it will generate following output −
1 2 4 3 5 7 6 8 9
Firebase - Write List Data

In our last chapter, we showed you how to write data in Firebase. Sometimes you need to have a unique identifier for your data. When you want to create unique identifiers for your data, you need to use the push method instead of the set method.
The push() method will create a unique id when the data is pushed. If we want to create our players from the previous chapters with a unique id, we could use the code snippet given below.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');

var playersRef = ref.child("players");
playersRef.push ({
   name: "John",
   number: 1,
   age: 30
});

playersRef.push ({
   name: "Amanda",
   number: 2,
   age: 20
});
Now our data will look differently. The name will just be a name/value pair like the rest of the properties.
We can get any key from Firebase by using the key() method. For example, if we want to get our collection name, we could use the following snippet.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');

var playersRef = ref.child("players");

var playersKey = playersRef.key();
console.log(playersKey);
The console will log our collection name (players).
More on this in our next chapters.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Reversing a List in Python - GeeksforGeeks

19 Feb, 2022
Python provides us with various ways of reversing a list. We will go through few of the many techniques on how a list in python can be reversed. Examples:  
Input : list = [10, 11, 12, 13, 14, 15]
Output : [15, 14, 13, 12, 11, 10]

Input : list = [4, 5, 6, 7, 8, 9]
Output : [9, 8, 7, 6, 5, 4]
 
Method 1: Using the reversed() built-in function. In this method, we neither reverse a list in-place(modify the original list), nor we create any copy of the list. Instead, we get a reverse iterator which we use to cycle through the list.  
Python3
# Reversing a list using reversed()def Reverse(lst):    return [ele for ele in reversed(lst)]     # Driver Codelst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))
Output:  
[15, 14, 13, 12, 11, 10]
Method 2: Using the reverse() built-in function. Using the reverse() method we can reverse the contents of the list object in-place i.e., we don’t need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list.  
Python3
# Reversing a list using reverse()def Reverse(lst):    lst.reverse()    return lst     lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))
Output:  
[15, 14, 13, 12, 11, 10]
Method 3: Using the slicing technique. In this technique, a copy of the list is made and the list is not sorted in-place. Creating a copy requires more space to hold all of the existing elements. This exhausts more memory.  
Python3
# Reversing a list using slicing techniquedef Reverse(lst):    new_lst = lst[::-1]    return new_lst     lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))
Output:  
[15, 14, 13, 12, 11, 10]
To get a better understanding on the slicing technique refer Slicing Techniques in Python. 
aminitindas
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Biopython - Machine Learning

Bioinformatics is an excellent area to apply machine learning algorithms. Here, we have genetic information of large number of organisms and it is not possible to manually analyze all this information. If proper machine learning algorithm is used, we can extract lot of useful information from these data. Biopython provides useful set of algorithm to do supervised machine learning.
Supervised learning is based on input variable (X) and output variable (Y). It uses an algorithm to learn the mapping function from the input to the output. It is defined below −
Y = f(X)

The main objective of this approach is to approximate the mapping function and when you have new input data (x), you can predict the output variables (Y) for that data.
Logistic regression is a supervised machine Learning algorithm. It is used to find out the difference between K classes using weighted sum of predictor variables. It computes the probability of an event occurrence and can be used for cancer detection.
Biopython provides Bio.LogisticRegression module to predict variables based on Logistic regression algorithm. Currently, Biopython implements logistic regression algorithm for two classes only (K = 2).
k-Nearest neighbors is also a supervised machine learning algorithm. It works by categorizing the data based on nearest neighbors. Biopython provides Bio.KNN module to predict variables based on k-nearest neighbors algorithm.
Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other. Biopython provides Bio.NaiveBayes module to work with Naive Bayes algorithm.
A Markov model is a mathematical system defined as a collection of random variables, that experiences transition from one state to another according to certain probabilistic rules. Biopython provides Bio.MarkovModel and Bio.HMM.MarkovModel modules to work with Markov models.
 Print
 Add Notes
 Bookmark this page
Python - Random Numbers Summation - GeeksforGeeks

19 Feb, 2020
Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers and perform its summation. This task has to performed in general using loop and appending the random numbers one by one and then performing sum. But there is always requirement to perform this in most concise manner. Lets discuss certain ways in which this can be done.
Method #1 : Using list comprehension + randrange() + sum()The naive method to perform this particular task can be shortened using the list comprehension. randrange function is used to perform the task of generating the random numbers. The task of performing sum is done using sum().
# Python3 code to demonstrate # Random Numbers Summation# using list comprehension + randrange() + sum()import random  # using list comprehension + randrange() + sum()# Random Numbers Summationres = sum([random.randrange(1, 50, 1) for i in range(7)])  # printing resultprint ("Random number summation list is : " + str(res))
Random number summation list is : 187

 
Method #2 : Using random.sample() + sum()This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list. The task of performing sum is done using sum().
# Python3 code to demonstrate # Random Numbers Summation# using random.sample() + sum()import random  # using random.sample() + sum()# Random Numbers Summationres = sum(random.sample(range(1, 50), 7))  # printing resultprint ("Random number summation list is : " + str(res))
Random number summation list is : 187

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Program to count submatrices with all ones using Python

Suppose we have m x n binary matrix, we have to find how many submatrices have all ones.
So, if the input is like
then the output will be 13 as there are 6 (1x1) matrices, 3 (2,1) matrices, 2 (1x2) matrices, 1 (3x1) matrix and 1 (4x4) matrix.
To solve this, we will follow these steps −
m := row count of matrix
m := row count of matrix
n := column count of matrix
n := column count of matrix
dp := a zero matrix of same size m x n
dp := a zero matrix of same size m x n
for i in range 0 to m - 1, dofor j in range 0 to n - 1, doif i is same as 0 and matrix[i, j], thendp[i, j] := 1otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1
for i in range 0 to m - 1, do
for j in range 0 to n - 1, doif i is same as 0 and matrix[i, j], thendp[i, j] := 1otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1
for j in range 0 to n - 1, do
if i is same as 0 and matrix[i, j], thendp[i, j] := 1
if i is same as 0 and matrix[i, j], then
dp[i, j] := 1
dp[i, j] := 1
otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1
otherwise when matrix[i][j] is non-zero, then
dp[i, j] := dp[i-1, j] + 1
dp[i, j] := dp[i-1, j] + 1
total := 0
total := 0
for i in range 0 to m - 1, dofor j in range 0 to n - 1, dofor k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]
for i in range 0 to m - 1, do
for j in range 0 to n - 1, dofor k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]
for j in range 0 to n - 1, do
for k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]
for k in range j+1 to n, do
total := total + minimum of dp[i,j] to dp[i,k]
total := total + minimum of dp[i,j] to dp[i,k]
return total
return total
Let us see the following implementation to get better understanding −
 Live Demo
def solve(matrix):
   m = len(matrix)
   n = len(matrix[0])
   dp = [[0] * n for _ in range(m)]
   for i in range(m):
      for j in range(n):
         if i == 0 and matrix[i][j]:
            dp[i][j] = 1
         elif matrix[i][j]:
            dp[i][j] = dp[i-1][j] + 1
   total = 0
   for i in range(m):
      for j in range(n):
         for k in range(j+1, n+1):
            total += min(dp[i][j:k])
   return total
matrix = [[1,0,1],[0,1,1],[0,1,1]]
print(solve(matrix))
[4,6,7,8], 11
13
DAX Date & Time - SECOND function

Returns the seconds of a time value, as a number from 0 to 59.
SECOND (<datetime>) 

datetime
A datetime value representing time. E.g. 18:15:15 or 5:45:15 P.M.
An integer number from 0 to 59.
The parameter to the SECOND function is the time that contains the second you want to find.
You can specify the time as one of the following −
Output of a date/time function.
An expression that returns a datetime value.
A value in one of the accepted time formats.
An accepted text representation of a time.
DAX SECOND function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. Most locales use the colon (:) as the time separator and any input text using colons as time separators will parse correctly. Review your locale settings to understand your results.
= SECOND ("18:15:45") returns 45. 
= SECOND ("2:15:05") returns 5. 
= SECOND (NOW ()) returns 57 if NOW () returns 12/16/2016 10:07:57 AM. 

    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
How to return a string from a JavaScript function?

To return a string from a JavaScript function, use the return statement in JavaScript.
You need to run the following code to learn how to return a string using return statement −
<html>
   <head>
      <script>
         function concatenate(name, subject) {
            var val;
            val = name + subject;
            return val;
         }
         function DisplayFunction() {
            var result;
            result = concatenate('Amit', ' Java');
            document.write (result );
         }
      </script>
   </head>
   
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "DisplayFunction()" value = "Result">
      </form>
   </body>
</html>
List sublist() Method in Java with Examples

19 Jun, 2019
This method gives a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Syntax:
List subList(int fromIndex,
              int toIndex)
Parameters: This function has two parameter fromIndex and toIndex, which are the starting and ending ranges respectively to create a sublist form the given list.
Returns: This method returns the view of list between the given ranges.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// lastIndexOf method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(1);        l.add(3);        l.add(5);        l.add(7);        l.add(3);        System.out.println(l);        System.out.println(l.lastIndexOf(3));    }}
[1, 3, 5, 7, 3]
4

[1, 3, 5, 7, 3]
4

Program 2: Below is the code to show implementation of list.subList() using Linkedlist.
// Java code to show the implementation of// subList method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(10);        l.add(30);        l.add(50);        l.add(70);        l.add(30);        List<Integer> sub = new LinkedList<>();        System.out.println(l);        sub = l.subList(1, 3);        System.out.println(sub);    }}
[10, 30, 50, 70, 30]
[30, 50]

Reference:Oracle Docs
Akanksha_Rai
Java - util package
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.
Python | Pandas Series.str.len()

28 Sep, 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 str.len() method is used to determine length of each string in a Pandas series. This method is only for series of strings.Since this is a string method, .str has to be prefixed everytime before calling this method. Otherwise it will give an error.
Syntax: Series.str.len()
Return type: Series of integer values. NULL values might be present too depending upon caller series.
To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Calculating length of string series (dtype=str)
In this example, the string length of Name column is calculated using str.len() method. The dtype of the Series is already string. So there is no need of data type conversion. Before doing any operations, null rows are removed to avoid errors.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # creating new column for len# passing values through str.len()data["Name Length"]= data["Name"].str.len()  # displaydata
Output:As shown in the output image, the length of each string in name column is returned.Note:
This method doesn’t count length of integer or float series. It will give an error since it’s not a string series. The series need to be converted first ( Shown in next Example)
There is no parameter to handle null values. A null value would return null in the output string too.
 Example #2:In this example, the length of salary column is calculated using the str.len() method. Since the series is imported as float64 dtype, it’s first converted to string using .astype() method.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # converting to string dtypedata["Salary"]= data["Salary"].astype(str)  # passing valuesdata["Salary Length"]= data["Salary"].str.len()  # converting back to float dtypedata["Salary"]= data["Salary"].astype(float)  # displaydata
Output:As shown in the output, length of int or float series can only be computed by converting it to string dtype.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
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
How to Use xlim() and ylim() in R?

28 Nov, 2021
In this article, we will be looking at the different ways to use the xlim() and the ylim() functions in the R programming language.
The xlim() function with the provided parameters as the range of the x-axis in vectors is used to set the x-axis without dropping any data of the given plot or an object accordingly.
Syntax:
xlim(...)
Parameters:
...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale.
Example:
In this example, we will be using the xlim() function to change the x-axis of the given bar plot in the R programming language.
R
# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4)    # Creating bar plot and setting # the x-axis limitsbarplot(gfg,xlim=c(0,10))
Output:
The xlim() function with the provided parameters as the range of the y-axis in vectors is used to set the y-axis without dropping any data of the given plot or an object accordingly.
Syntax:
xlim(...)
Parameters:
...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale.
Example:
In this example, we will be using the ylim() function to change the y-axis of the given bar plot (with the same data as in the previous example)in the R programming language.
R
# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4)  # Creating bar plot and setting # the y-axis limitsbarplot(gfg,ylim=c(0,20))
Output:
Here, we will be using both xlim() and the ylim() function together to set the axis limits accordingly of both the x-axis and y-axis together in the same plot to get a clear idea of the outcomes, refer to the below example.
Example:
In this example, we will be using the xlim() and the ylim() function both together in the same barplot with the same data as the previous example and set the axis limits accordingly in the R programming language.
R
# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4)  # Creating bar plot and setting the# x-axis and y-axis limitsbarplot(gfg,xlim=c(0,10),ylim=c(0,20))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js line() method

19 Aug, 2020
The d3.line() method is used to constructs a new line generator with the default settings. The line generator is then used to make a line.
Syntax:
d3.line();
Parameters: This method takes no parameters.
Return Value: This method returns a line Generator.
Example 1: Making a simple line using this method.
<!DOCTYPE html><html><meta charset="utf-8"><head>  <title>Line in D3.js</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>  <style>path {    fill: none;    stroke: green;}</style>  <body>    <h1 style="text-align: center;        color: green;">GeeksforGeeks</h1>  <center>    <svg width="500" height="500">    <path></path>  </svg></center>  <script>        // Making a line Generator        var Gen = d3.line();        var points = [            [0, 100],            [500, 100]                     ];          var pathOfLine = Gen(points);          d3.select('path')            .attr('d', pathOfLine);  </script></body></html>
Output:
Example 2: Making a Multiconnected line.
<!DOCTYPE html><html><meta charset="utf-8"><head>  <title>Line in D3.js</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>  <style>path {    fill: none;    stroke: green;}</style>  <body>    <h1 style="text-align: center;        color: green;">GeeksforGeeks</h1>  <center>    <svg width="500" height="500">    <path></path>  </svg></center>  <script>        // Making a line Generator        var Gen = d3.line();        var points = [            [0, 100],            [500, 100],            [200, 200],            [500, 200]                     ];          var pathOfLine = Gen(points);          d3.select('path')            .attr('d', pathOfLine);  </script></body></html>
Output:
D3.js
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.axes() in Python

17 May, 2020
Pyplot is another module of matplotlib that enables users to integrate MATLAB within Python environment, and thus providing MATLAB like interface and making Python visually interactive.
pyplot.axes is a function of the matplotlib library that adds axes to the current graph and makes it as current axes. Its output depends on the arguments used.
Syntax: matplotlib.pyplot.axes(*args, **kwargs)
Parameters:*args: It may include either None(nothing) or 4 tuples of float type
none: It gives a new full window axes
4 tuples: It takes 4 tuples as list i.e [left bottom width height] and gives a window of these dimensions as axes.
**kwargs: There are several keyword arguments(kwargs) used as parameters to pyplot.axes(), most common include facecolor, gid, in_layout, label, position, xlim, ylim, etc.
Example 1:
# importing matplot library along # with necessary modulesimport matplotlib.pyplot as plt    # providing values to x and y x = [8, 5, 11, 13, 16, 23]y = [14, 8, 21, 7, 12, 15]  # to plot x and yplt.plot(x, y)  # to generate the full window axesplt.axes()
Output:
Example 2:
# importing matplot library along # with necessary modulesimport matplotlib.pyplot as plt    # providing values to x and y x = [8, 5, 11, 13, 16, 23]y = [14, 8, 21, 7, 12, 15]  # to plot x and y#plt.plot(x, y)# to generate window of custom # dimensions [left, bottom, width,# height] along with the facecolor plt.axes([0, 2.0, 2.0, 2.0], facecolor = 'black') 
Output:
afshan_mairaj
Matplotlib Pyplot-class
Python-matplotlib
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Ruby | Array zip() function

06 Dec, 2019
Array#zip() : zip() is a Array class method which Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument.
Syntax: Array.zip()
Parameter: Array
Return: merges elements of self with corresponding elements from each argument.
Example #1 :
# Ruby code for zip() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 50, 6]    # zip method exampleputs "zip() method form : #{a.zip(b)}\n\n"  puts "zip() method form : #{b.zip(c)}\n\n"  puts "zip() method form : #{c.zip(c)}\n\n"
Output :
zip() method form : [[18, 1], [22, 4], [33, 1], [nil, 1], [5, 88], [6, 9]]

zip() method form : [[1, 18], [4, 22], [1, 50], [1, 6], [88, nil], [9, nil]]

zip() method form : [[18, 18], [22, 22], [50, 50], [6, 6]]


Example #2 :
# Ruby code for zip() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["cat", nil]  # declaring arrayb = ["cow", nil, "dog"]    # zip method exampleputs "zip() method form : #{a.zip(b)}\n\n"  puts "zip() method form : #{b.zip(c)}\n\n"  puts "zip() method form : #{c.zip(c)}\n\n"
Output :
zip() method form : [["abc", "cow"], ["nil", nil], ["dog", "dog"]]

zip() method form : [["cow", "cat"], [nil, nil], ["dog", nil]]

zip() method form : [["cat", "cat"], [nil, nil]]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby on Rails Introduction
Ruby | String concat Method
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | Array shift() function
Ruby | Types of Variables
Get all fields names in a MongoDB collection?

You can use the concept of Map Reduce. Let us first create a collection with documents −
> db.getAllFieldNamesDemo.insertOne({"StudentFirstName":"David","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd998e9b50a6c6dd317ad90")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.getAllFieldNamesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName" : "David", "StudentAge" : 23 }
Following is the query to get all fields names in a MongoDB collection −
> myMapReduce = db.runCommand({
   "mapreduce" : "getAllFieldNamesDemo",
   "map" : function() {
      for (var myKey in this) { emit(myKey, null); }
   },
   "reduce" : function(myKey, s) { return null; },
   "out": "getAllFieldNamesDemo" + "_k"
})
{
   "result" : "getAllFieldNamesDemo_k",
   "timeMillis" : 1375,
   "counts" : {
      "input" : 1,
      "emit" : 3,
      "reduce" : 0,
      "output" : 3
   },
   "ok" : 1
}
> db[myMapReduce.result].distinct("_id");
This will produce the following output displaying the filed names −
[ "StudentAge", "StudentFirstName", "_id" ]