code-rag-bench/online-tutorials huggingface dataset:
Get psycopg2 count(*) number of results - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to get psycopg2 count(*) number of results. 
psycopg2 count(*) returns the number of rows from a database table holding some specific conditions. If no condition is given then it returns the total number of tuples present in the relation. 
Syntax:
SELECT  COUNT(*)  FROM  table_name;  # to return total no. of rows in the table
SELECT  COUNT(*)  FROM  table_name  WHERE condition;  # to return no. of rows with some specified condition
Let’s see the following syntax in PostgreSql prompt:
First of all, we will import psycopg2 module that will deal with postgreSQL database, and then a database connection is established. Then we will create a cursor object that allows Python code to execute PostgreSQL command in a database session. We will then write a query to execute the total number of rows with specific details. 
For ex- in the code given below, we are writing the first query to return the total no. of rows present in the table and the second query is written to return the total number of rows where the price name is 1.99. Finally, the number of rows has been fetched and displayed.
Python3
# importing psycopg2import psycopg2  conn=psycopg2.connect(    database="geeks",    user="postgres",    password="root",    host="localhost",    port="5432")  # Creating a cursor object using the cursor()# methodcursor = conn.cursor()  # query to count total number of rowssql = 'SELECT count(*) from products;'data=[]  # execute the querycursor.execute(sql,data)results = cursor.fetchone()  #loop to print all the fetched detailsfor r in results:  print(r)print("Total number of rows in the table:", r)  # query to count number of rows# where country name is India  sql1 = 'SELECT count(*) from products WHERE "price" = 1.99;'data1=['India']  # execute querycursor.execute(sql1,data1)result = cursor.fetchone()for r1 in result:  print(r1)print("Total Number of rows where country name is India:",r1)  # Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output:
Count number of rows in the cursor
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sciPy stats.histogram() function | Python - GeeksforGeeks

13 Feb, 2019
scipy.stats.histogram(a, numbins, defaultreallimits, weights, printextras) works to segregate the range into several bins and then returns the number of instances in each bin. This function is used to build the histogram.
Parameters :arr : [array_like] input array.numbins : [int] number of bins to use for the histogram. [Default = 10]defaultlimits : (lower, upper) range of the histogram.weights : [array_like] weights for each array element.printextras : [array_like] to print the no, if extra points to the standard output, if true
Results :– cumulative frequency binned values– width of each bin– lower real limit– extra points.
Code #1:
# building the histogram import scipyimport numpy as np import matplotlib.pyplot as plt  hist, bin_edges = scipy.histogram([1, 1, 2, 2, 2, 2, 3],                                       bins = range(5))  # Checking the resultsprint ("No. of points in each bin : ", hist)print ("Size of the bins          : ", bin_edges)  # plotting the histogramplt.bar(bin_edges[:-1], hist, width = 1)plt.xlim(min(bin_edges), max(bin_edges))plt.show()
Output :
No. of points in each bin :  [0 2 4 1]
Size of the bins          :  [0 1 2 3 4]

Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
ChronoLocalDate get() method in Java with Examples - GeeksforGeeks

29 Apr, 2019
The get() method of ChronoLocalDate interface in Java method gets the value of the specified field from this Date as an int.
Syntax:
public int get(TemporalField field)

Parameter: This method accepts a parameter field which is the field to get and not necessary null.
Return Value: It returns the value for the field.
Exceptions: The function throws three exceptions as described below:
DateTimeException: this exception is thrown if a value for the field cannot be obtained or the value is outside the range of valid values for the field.
UnsupportedTemporalTypeException: this exception is thrown if the field is not supported or the range of values exceeds an int
ArithmeticException: this exception is thrown if numeric overflow occurs
Below programs illustrate the get() method of ChronoLocalDate in Java:Program 1:
// Program to illustrate the get() method  import java.util.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.ChronoField;  public class GfG {    public static void main(String[] args)    {          ChronoLocalDate dt            = LocalDate.parse("2017-02-16");        System.out.println(dt.get(            ChronoField.MONTH_OF_YEAR));    }}
2

Program 2:
// Program to illustrate the get() method// Exception Program  import java.util.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.ChronoField;  public class GfG {    public static void main(String[] args)    {        try {            ChronoLocalDate dt                = LocalDate.parse("2017-02-30");            System.out.println(dt.get(                ChronoField.MONTH_OF_YEAR));        }        catch (Exception e) {            System.out.println(e);        }    }}
java.time.format.DateTimeParseException: 
 Text '2017-02-30' could not be parsed: 
 Invalid date 'FEBRUARY 30'

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAccessor.html#get-java.time.temporal.TemporalField-
Java-ChronoLocalDate
Java-Functions
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
How to create a Pie Chart using HTML & CSS ? - GeeksforGeeks

11 Jun, 2020
Pie Chart is a type of graph that displays data in a circular shape and is generally used to show percentage or proportional data. The percentage represented in the graph by each category is provided near the corresponding slice of one portion of pie chart. These charts are very good for displaying data for two or more categories.
HTML Code: In the following code, the basic design or structure is shown.
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content=      "width=device-width, initial-scale=1.0">    <title>Pie Chart</title>    <link rel="stylesheet" href="style.css"></head><body>    <h1>Pie Chart</h1>    <div class="piechart"></div></body></html>
CSS Code: In the following section, the design of pie-chart is demonstrated using some CSS properties.
<style>    .piechart {        margin-top: 300px;        display: block;        position: absolute;        width: 400px;        height: 400px;        border-radius: 50%;        background-image: conic-gradient(            pink 70deg,             lightblue 0 235deg,             orange 0);    }      body,    .piechart {        display: flex;        justify-content: center;        align-items: center;    }</style>
Complete Code:
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <title>Pie Chart</title>      <style>        .piechart {            margin-top: 300px;            display: block;            position: absolute;            width: 400px;            height: 400px;            border-radius: 50%;            background-image: conic-gradient(                pink 70deg,                 lightblue 0 235deg,                 orange 0);        }          body,        .piechart {            display: flex;            justify-content: center;            align-items: center;        }    </style></head>  <body>    <h1>Pie Chart</h1>    <div class="piechart"></div></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
How to position a div at the bottom of its container using CSS?
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
Find size of array in C/C++ without using sizeof

In this program, we find out Find size of array in C/C++ without using sizeof.
Begin
   Initialize the elements of the array.
   &a => This is the pointer to array which points at the same memory address as a.
   &a + 1 => It points at the address after the end of the array.
   *(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element.
   *(a+1)-a => Subtract the pointer to the first element to get the length of the array.
   Print the size.
End.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a[] = {6,7,5,3,1,4,2,10,9};
   int s = *(&a + 1) - a;
   cout << "Number of elements in array is "<< s;
}
Number of elements in array is 9
To check divisibility of any large number by 9 in java

If the sum of the digits of a number is divisible by 9, then the number is divisible by 9.
Some examples of numbers divisible by 9 are as follows.
 The number 51984 is divisible by 9 because the sum of its digits (5+ 1 + 9 + 8 + 4 = 27) is divisible by 9.
The number 91403 is not divisible by 9 because the sum of its digits (9 + 1 + 4 + 0 + 3 = 17) is not divisible by 9.
import java.util.Scanner;

public class DivisibleBy9 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number :");
      String num = sc.nextLine();
      int digitSum = 0;
      for(int i = 0; i<num.length(); i++){
         digitSum = digitSum + num.charAt(i)-'0';
      }
      if(digitSum % 9 == 0){
         System.out.println("Given number is divisible by 9");
      } else {
         System.out.println("Given number is not divisible by 9");
      }
   }
}
Enter a number :
51984
Given number is divisible by 9
Intersection process of two DFAs

10 Aug, 2021
Prerequisite – Design a Finite automata 
Let’s understand the intersection of two DFA with an example. Designing a DFA for the set of string over {0, 1} such that it ends with 01 and has even number 0f 1’s. There two desired language will be formed:  
L1= {01, 001, 101, 0101, 1001, 1101, ....} 
L2= {11, 011, 101, 110, 0011, 1100, .....}
L = L1 and L2 = L1 ∩ L2 
State Transition Diagram for the language L1 : This is a DFA for language L1 
It accepts all the string that accept 01 at end. 
State Transition Diagram for the language L2 : This is a DFA for language L2  
It accepts all the string that accept with even number of 1’s. 
State Transition Diagram of L1 ∩ L2 : Intersection of L1 and L2 can be explained by language that a string over {0, 1} accept such that it ends with 01 and has even number of 1’s.  
L = L1 ∩ L2
= {1001, 0101, 01001, 10001, ....} 
 
Thus as we see that L1 and L2 have been combined through intersection process and this final DFA accept all the language that has even number of 1’s and is ending with 01.
wilsphone28
simmytarika5
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Halting Problem in Theory of Computation
Decidable and Undecidable problems in Theory of Computation
Post Correspondence Problem
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Pushdown Automata Acceptance by Final State
Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}
Undecidability and Reducibility in TOC
Arden's Theorem in Theory of Computation
Install Pytorch on Linux

09 Jun, 2022
In this article, we are going to see how you can install PyTorch in the Linux system. We are using Ubuntu 20 LTS you can use any other one. To successfully install PyTorch in your Linux system, follow the below procedure:
First, check if you are using python’s latest version or not.
Because PyGame requires python 3.7 or a higher version, make sure you are using the latest version of python. Type the below command to check the version of python.
python3 –version
Note: If Python is not installed, refer to install python in Linux.
Check if you are using the latest version of pip or not:
The pip is a python package installer, if you want to use any external package in your python file you first install it in your local system using pip. Run the following command to check the version of pip. 
pip3 –version
If you are already using the new pip version so follow the below steps if not, so refer to the article on how to install pip in Linux.
Switch to root user and update Linux packages if you are not using the latest pip version:
Open the terminal and make sure you are the root user. Run the following command to switch to root user.
sudo su
Update Linux packages using the below command.
apt update
After this step, you are ready to install PyTorch on your Linux system.
pip3 install torch==1.8.1+cpu torchvision==0.9.1+cpu torchaudio==0.8.1 -f https://download.pytorch.org/whl/torch_stable.html
The above command was used to install PyTorch in the system that didn’t have GPU. You just copy the command and paste it into the terminal and run it.
The below command is used to install PyTorch on a system which has GPU. Make sure you have python 3.7 or higher.
pip3 install torch torchvision torchaudio
To make sure PyTorch is installed in your system, just type python3 in your terminal and run it. After that type import torch for use PyTorch library at last type and run print(torch.__version__) it shows which version of PyTorch was installed on your system if PyTorch was installed on your system.
jivendrasah
how-to-install
Picked
Python-PyTorch
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Run Apache Kafka on Windows?
How to Install and Use NVM on Windows?
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
p5.js | strokeWeight() function

16 Apr, 2019
The strokeWeight() function in p5.js is used to set the width of the stroke used for lines, points, and the border around shapes. The stroke weight are set by using pixel.
Syntax:
strokeWidth(weight)
Parameters: This function accepts single parameter weight which stores the weight (in pixels) of the stroke.
Below programs illustrate the strokeWeight() function in p5.js:
Example 1: This example uses strokeWeight() function to set the width of stroke.
function setup() {      // Create Canvas of given size    createCanvas(380, 170);}  function draw() {          // Set the background color    background(220);          // Set the stroke width    strokeWeight(20);          // Set the filled color    fill('green');          // Draw the circle    circle(60, 60, 34);          // Set the text size    textSize(20);          // Set the text to print    text("GeeksForGeeks", 120, 70);}
Output:
Example 2: This example uses strokeWeight() function to set the width of stroke.
function setup() {          // Create Canvas of given size    createCanvas(380, 170);}  function draw() {          // Set the background color    background(220);          // Set the stroke clor    stroke('orange');          // Set the stroke width to 10    strokeWeight(10); // Orange          // Draw a line    line(20, 70, 80, 70);          // Set the stroke color    stroke('white');          // Set the stroke width to 8    strokeWeight(8); // White          // Draw a line    line(20, 90, 80, 90);          // Set stroke color    stroke('green');          // Set the stroke width to 6    strokeWeight(6); // Green          // Draw a line    line(20, 110, 80, 110);}
Output:
Reference: https://p5js.org/reference/#/p5/strokeWeight
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Find value of k-th bit in binary representation

16 Jun, 2022
Given a number n and k (1 <= k <= 32), find the value of k-th bit in the binary representation of n. Bits are numbered from right (Least Significant Bit) to left (Most Significant Bit).
Examples : 
Input :  
n = 13, k = 2
Output : 
0
Explanation:
Binary representation of 13 is 1101.
Second bit from right is 0.

Input :  
n = 14, k = 3
Output : 
1
Explanation:
Binary representation of 14 is 1110.
Third bit from right is 1.
Approach:1) Find a number with all 0s except k-th position. We get this number using ( 1 << (k-1) ). For example if k = 3, then ( 1 << 2) gives us (00..00100). 2) Do bitwise and of above-obtained number with n to find if k-th bit in n is set or not.  
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find k-th bit from right#include <bits/stdc++.h>using namespace std; void printKthBit(unsigned int n, unsigned int k){    cout << ((n & (1 << (k - 1))) >> (k - 1));} // Driver Codeint main(){    unsigned int n = 13, k = 2;       // Function Call    printKthBit(n, k);    return 0;}
// Java program to find// k-th bit from rightimport java.io.*; class GFG {    static void printKthBit(long n, long k)    {        System.out.println(            ((n & (1 << (k - 1))) >> (k - 1)));    }     // Driver Code    public static void main(String[] args)    {        long n = 13, k = 2;               // Function Call        printKthBit(n, k);    }} // This code is contributed by anuj_67.
# Python 3 program to find# k-th bit from right def printKthBit(n, k):     print((n & (1 << (k - 1))) >> (k - 1)) # Driver Coden = 13k = 2 # Function CallprintKthBit(n, k) # This code is contributed by Smitha
// C# program to find k-th bit from rightusing System; class GFG {     static void printKthBit(long n, long k)    {        Console.WriteLine((n & (1 << (k - 1))) >> (k - 1));    }     // Driver Code    public static void Main()    {        long n = 13, k = 2;                 // Function Call        printKthBit(n, k);    }} // This code is contributed by anuj_67.
<?php// PHP program to find// k-th bit from right function printKthBit($n, $k){    echo ($n & (1 << ($k - 1)));} // Driver Code$n = 13; $k = 2;printKthBit($n, $k); // This code is contributed// by anuj_67.?>
<script> // JavaScript program to find k-th bit from right function printKthBit(n, k){    document.write((n & (1 << (k - 1))) >> (k - 1));} // Driver Codevar n = 13, k = 2; // Function CallprintKthBit(n, k); </script>
0
 
Time Complexity: O(1), the code will run in a constant time.Auxiliary Space: O(1), no extra space is required, so it is a constant.
vt_m
Smitha Dinesh Semwal
raj96
itsok
tamanna17122007
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to combine 2 arrays into 1 object in JavaScript

Let’s say, we have two arrays of equal lengths and are required to write a function that maps the
two arrays into an object. The corresponding elements of the first array becomes the
corresponding keys of the object and the elements of the second array become the value.
We will reduce the first array, at the same time accessing elements of the second array by
index. The code for this will be −
const keys = [
   'firstName',
   'lastName',
   'isEmployed',
   'occupation',
   'address',
   'salary',
   'expenditure'
];
const values = [
   'Hitesh',
   'Kumar',
   false,
   'Frontend Developer',
   'Tilak Nagar, New Delhi',
   90000,
   45000
];
const combineArrays = (first, second) => {
   return first.reduce((acc, val, ind) => {
      acc[val] = second[ind];
      return acc;
   }, {});
};
console.log(combineArrays(keys, values));
The output in the console will be −
{
   firstName: 'Hitesh',
   lastName: 'Kumar',
   isEmployed: false,
   occupation: 'Frontend Developer',
   address: 'Tilak Nagar, New Delhi',
   salary: 90000,
   expenditure: 45000
}
Intersection of Two Objects in R Programming – intersect() Function

15 Jun, 2020
intersect() function in R Language is used to find the intersection of two Objects. This function takes two objects like Vectors, dataframes, etc. as arguments and results in a third object with the common data of both the objects.
Syntax: intersect(x, y)
Parameters:x and y: Objects with sequence of items
Example 1:
# R program to illustrate # intersection of two vectors     # Vector 1 x1 <- c(1, 2, 3, 4, 5, 6, 5, 5)        # Vector 2  x2 <- c(2:4)         # Intersection of two vectors   x3 <- intersect(x1, x2)           print(x3)                 
Output:
[1] 2 3 4

Example 2:
# R program to illustrate  # the intersection of two data frames     # Data frame 1 data_x <- data.frame(x1 = c(2, 3, 4),                          x2 = c(1, 1, 1))     # Data frame 2 data_y <- data.frame(y1 = c(2, 3, 4),                             y2 = c(2, 2, 2))     # Intersection of two data frames data_z <- intersect(data_x, data_y)       print(data_z)                
Output:
  y1
1  2
2  3
3  4

R Array-Functions
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Printing Output of an R Program
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
time.Time.Sub() Function in Golang With Examples

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Sub() function in Go language is used to yield the duration obtained by performing the operation t-u. And if the output here surpasses the maximum or the minimum value that can be stored in a Duration “d” then the maximum or the minimum duration will be returned. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.
Syntax:
func (t Time) Sub(u Time) Duration

Here, “t” and “u” are the stated time.
Note: In order to calculate “t-d” for a given duration “d” you need to use t.Add(-d).
Return value: It returns the duration obtained by performing the operation t-u.
Example 1:
// Golang program to illustrate the usage of// Time.Sub() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining t and u for Sub method    t := time.Date(2020, 11, 14, 16,               45, 16, 36, time.UTC)    u := time.Date(2019, 9, 5, 18, 0,                      0, 0, time.UTC)      // Calling Sub method    subtract := t.Sub(u)      // Prints output    fmt.Printf("t-d = %v\n", subtract)}
Output:
t-d = 10462h45m16.000000036s

Example 2:
// Golang program to illustrate the usage of// Time.Sub() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining t and u for Sub method    t := time.Date(2020, 11, 14, 34,                67, 98, 63, time.UTC)    u := time.Date(2019, 9, 5, 28,             66, 89, 100, time.UTC)      // Calling Sub method    subtract := t.Sub(u)      // Prints output    fmt.Printf("t-d = %v\n", subtract)}
Output:
t-d = 10470h1m8.999999963s

Here, the times “t” and “u” stated in the above code have values that are out of usual range but they are normalized while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Active and Inactive cells after k Days?

Here we will see one interesting problem. Suppose one binary array is given of size n. Here n > 3. A true value or 1 value indicates that the active state, and 0 or false indicates inactive. Another number k is also given. We have to find active or inactive cells after k days. After every
day state of ith cell will be active if the left and right cells are not same, if they are same, then it will be inactive. The left most and right most cell has no cell before and after it. So left most and right most cells are always 0.
Let us see one example to get the idea. Suppose one array is like {0, 1, 0, 1, 0, 1, 0, 1}, and the value of k = 3. So let us see how it changes day by day.
After 1 day the array will be {1, 0, 0, 0, 0, 0, 0, 0}
After 2 days the array will be {0, 1, 0, 0, 0, 0, 0, 0}
After 3 days the array will be {1, 0, 1, 0, 0, 0, 0, 0}
So 2 active cells and 6 inactive cells
begin
   make a copy of arr into temp
   for i in range 1 to k, do
      temp[0] := 0 XOR arr[1]
      temp[n-1] := 0 XOR arr[n-2]
      for each cell i from 1 to n-2, do
         temp[i] := arr[i-1] XOR arr[i+1]
      done
      copy temp to arr for next iteration
   done
   count number of 1s as active, and number of 0s as inactive, then return the values.
end
#include <iostream>
using namespace std;
void activeCellKdays(bool arr[], int n, int k) {
   bool temp[n]; //temp is holding the copy of the arr
   for (int i=0; i<n ; i++)
      temp[i] = arr[i];
   for(int i = 0; i<k; i++){
      temp[0] = 0^arr[1]; //set value for left cell
      temp[n-1] = 0^arr[n-2]; //set value for right cell
      for (int i=1; i<=n-2; i++) //for all intermediate cell if left and
         right are not same, put 1
      temp[i] = arr[i-1] ^ arr[i+1];
      for (int i=0; i<n; i++)
         arr[i] = temp[i]; //copy back the temp to arr for the next iteration
   }
   int active = 0, inactive = 0;
   for (int i=0; i<n; i++)
      if (arr[i])
         active++;
      else
         inactive++;
   cout << "Active Cells = "<< active <<", Inactive Cells = " << inactive;
}
main() {
   bool arr[] = {0, 1, 0, 1, 0, 1, 0, 1};
   int k = 3;
   int n = sizeof(arr)/sizeof(arr[0]);
   activeCellKdays(arr, n, k);
}
Active Cells = 2, Inactive Cells = 6
How to install matplotlib in Python?

Matplotlib is a Python library that helps to plot graphs. It is used in data visualization and graphical plotting.
To use matplotlib, we need to install it.
Type the following commands in the command prompt to check is python and pip is installed on your system.
python --version
If python is successfully installed, the version of python installed on your system will be displayed.
pip -V
The version of pip will be displayed, if it is successfully installed on your system.
Matplotlib can be installed using pip. The following command is run in the command prompt to install Matplotlib.
pip install matplotlib
This command will start downloading and installing packages related to the matplotlib library. Once done, the message of successful installation will be displayed.
To verify that matplotlib is successfully installed on your system, execute the following command in the command prompt. If matplotlib is successfully installed, the version of matplotlib installed will be displayed.
import matplotlib
matplotlib.__version__
Python Program to Print the Incremented Date if valid - GeeksforGeeks

06 Oct, 2021
In this article, we will write a python program to input a date and check whether it is a valid date or not. If it is valid, output the incremented date. Otherwise, print “Invalid date”.
Examples:
Input : 1/2/2000
Output: 2/2/2000

Input : 29/2/2002
Output: Invalid date

Input : 31/12/2015
Output: 1/1/2016 
The first step is to check whether the entered date is valid or not. For this step, we need to first obtain the maximum possible day number for the month entered. Then we need to see whether the day lies between 1 and the obtained maximum day number and whether the month lies between 1 and 12. If both these conditions get satisfied, that means it is a valid date, and we need to increment it. To increment the date, we need to handle the following cases:
If the entered date is the last day of the year.If the entered date is the last day of the month.If the entered date is not the last day of the month.
If the entered date is the last day of the year.
If the entered date is the last day of the month.
If the entered date is not the last day of the month.
For the first case, increment the year and set both the day and the month to 1.  For the second case, increment the month and set the day to 1. For the third case, just increment the day. If even one of the two conditions did not get satisfied, then it is an invalid date. 
Below is the implementation.
Python3
# input the date and split it to day, month and yearday, month, year = map(int, input().split('/')) if month == 2:     # check for February    if year % 4 != 0:        d_max = 28    else:        d_max = 29         elif month in [4, 6, 9, 11]:       # check the months with 30 days    d_max = 30 else:    d_max = 31 if 1 <= day <= d_max and 1 <= month <= 12:         # increment the date since it is a    # valid date    if day == d_max:        day = 1        if month == 12:                         # If this block is entered,            # then it is the last day of            # the year            month = 1            year += 1        else:                       # If this block is entered,            # then it is the last day of            # the month            month += 1    else:               # If this block is entered, then it        # is NOT the last day of the month        day += 1    print(str(day) + "/" + str(month) + "/" + str(year))else:    print("Invalid date")
Output:
31/12/2015
1/1/2016
prachisoda1234
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Tryit Editor v3.7

CSS User Interface
Tryit: Allow resize height only
Python | Type casting whole List and Matrix

30 Dec, 2020
Sometimes, while working with Python List or Matrix, we usually have a problem in which we require to get a generalized function which could perform the type casting of whole container at once. There is always a need of a mechanism code which can transform entirely the allowed change of data type for all elements in container. Let’s discuss a way in which this task can be performed.
Method : Using map() + list comprehensionThis task can be performed using a map(). The transformation of a normal list can be performed using a single map function by just passing the desired data type. But when it comes to transformation of whole matrix, we need the help of list comprehension for the same.
# Python3 code to demonstrate working of# Type casting whole List and Matrix# using map() + list comprehension  # helper function to type cast list def cast_list(test_list, data_type):    return list(map(data_type, test_list))      # helper function to type cast Matrix def cast_matrix(test_matrix, data_type):    return list(map(lambda sub: list(map(data_type, sub)), test_matrix))      # initialize list test_list = [1, 4, 9, 10, 19]  # initialize Matrixtest_matrix = [[5, 6, 8], [8, 5, 3], [9, 10, 3]]  # printing original listprint("The original list is : " + str(test_list))  # printing original matrixprint("The original Matrix is : " + str(test_matrix))  # Type casting whole List and Matrix# using map() + list comprehensionres_list = cast_list(test_list, str)res_matrix = cast_matrix(test_matrix, str)  # printing resultprint("The List after type casting is : " + str(res_list))print("The Matrix after type casting is : " + str(res_matrix))
The original list is : [1, 4, 9, 10, 19]
The original Matrix is : [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
The List after type casting is : ['1', '4', '9', '10', '19']
The Matrix after type casting is : [['5', '6', '8'], ['8', '5', '3'], ['9', '10', '3']]

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print a character n times without using loop, recursion or goto in C++

09 Oct, 2019
Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion and goto.
Examples :
Input : n = 10, c = 'a'
Output : aaaaaaaaaa

Input  : n = 6, c = '\n'
Output :

Input  : n = 6, character = '@'
output : @@@@@@

In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While declaring a string, it can be initialized by using the feature provided by c++. It takes 2 arguments. First is the number of times we want to print a particular character and the other is the character itself.
Below is the implementation which illustrates this.
// CPP Program to print a character // n times without using loop,// recursion or goto#include<bits/stdc++.h>using namespace std;  // print functionvoid printNTimes(char c, int n){    // character c will be printed n times    cout << string(n, c) << endl;}  // driver codeint main(){    // no of times a character    // need to be printed    int n = 6;    char c = 'G';          // function calling    printNTimes(c, n);      return 0; }
Output:
GGGGGG

Another Method: As we know that every time an object of a class is created the constructor of that class is called we can use it to our advantage and print the character inside the constructor, and create N objects of that class.
#include<bits/stdc++.h>using namespace std;  class Geeks{      public:        Geeks(){            cout<<"@ ";        }         };  int main(){    int N =6;      Geeks obj[N];    return 0;}
Output:
@ @ @ @ @ @

Blinkii
cpp-puzzle
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
Substring in C++
The C++ Standard Template Library (STL)
Object Oriented Programming in C++
C++ Classes and Objects
TypeScript | String substr() Method

18 Jun, 2020
The split() is an inbuilt function in TypeScript which is used to returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax: 
string.substr(start[, length])
Parameter: This method accepts two parameter as mentioned above and described below.: 
start – This parameter is the location at which to start extracting characters.
length – This parameter is the number of characters to extract.
Return Value: This method returns the new sub-string. Below examples illustrate the String substr() method in TypeScript.
Example 1: 
Javascript
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";       // use of String substr() Method    var newstr = str.substr(0,5)       console.log(newstr);</script>
Output: 
Geeks

Example 2: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";       // use of String substr() Method    var newstr = str.substr(0,5)     console.log(newstr);      newstr = str.substr(-2,5)     console.log(newstr);      newstr = str.substr(12,22)     console.log(newstr);      newstr = str.substr(0,1)     console.log(newstr);</script>
Output: 
Geeks
rm
s - Best Platform
G

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Edit Distance


There are two strings given. The first string is the source string and the second string is the target string. In this program, we have to find how many possible edits are needed to convert first string to the second string. 
The edit of strings can be either Insert some elements, delete something from the first string or modify something to convert into the second string.
Input:
Two strings to compare.
string 1: Programming
string 2: Programs
Output:
Enter the initial string: Programming
Enter the final string: Programs
The number of changes required to convert Programming to Programs is 4
editCount(initStr, finalStr, initLen, finalLen)
Input − The initial and final string and their lengths.Output − Number of edits are required to make initStr to finalStr.
Begin
   if initLen = 0, then
      return finalLen
   if finalLen := 0, then
      return initLen

   if initStr[initLen - 1] = finalStr[finalLen - 1], then
      return editCount(initStr, finalStr, initLen – 1, finalLen - 1)
   answer := 1 + min of (editCount(initStr, finalStr, initLen , finalLen - 1)),
      (editCount(initStr, finalStr, initLen – 1, finalLen ),
      (editCount(initStr, finalStr, initLen – 1, finalLen - 1)
   return answer
End
#include<iostream>
using namespace std;

int min(int x, int y, int z) {       //find smallest among three numbers
   if(x < y) {
      if(x < z)
         return x;
      else
         return z;
   }else {
      if(y < z)
         return y;
      else
         return z;
   }
}

int editCount(string initStr , string finalStr, int initLen, intfinalLen) {
   if (initLen == 0)       //when initial string is empty, add all characters of final string
      return finalLen;

   if (finalLen == 0)       //when final string is empty, delete all characters from initial string
      return initLen;

   //when last character matches, recursively check previous characters
   if (initStr[initLen-1] == finalStr[finalLen-1])
      return editCount(initStr, finalStr, initLen-1, finalLen-1);

   //if last character match is not found, check for insert, delete and update operations recursively
   return 1 + min ( editCount(initStr, finalStr, initLen, finalLen- 1),  // insert
 
      editCount(initStr, finalStr, initLen-1, finalLen), // delete
      editCount(initStr, finalStr, initLen-1, finalLen-1) // update
   );
}

int main() {
   string initStr;
   string finalStr;

   cout << "Enter the initial string: "; cin >> initStr;
   cout << "Enter the final string: "; cin >> finalStr;
   cout << "The number of changes required to convert " << initStr << " to " << finalStr;
   cout << " is " << editCount( initStr , finalStr, initStr.size(), finalStr.size()) << endl;
}
Enter the initial string: Programming
Enter the final string: Programs
The number of changes required to convert Programming to Programs is 4
T-SQL - DELETE Statement

The SQL Server DELETE Query is used to delete the existing records from a table.
You have to use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.
Following is the basic syntax of DELETE query with WHERE clause −
DELETE FROM table_name 
WHERE [condition]; 

You can combine N number of conditions using AND or OR operators.
Consider the CUSTOMERS table having the following records −
ID  NAME       AGE       ADDRESS            SALARY 
1   Ramesh     32        Ahmedabad          2000.00 
2   Khilan     25        Delhi              1500.00 
3   kaushik    23        Kota               2000.00 
4   Chaitali   25        Mumbai             6500.00 
5   Hardik     27        Bhopal             8500.00 
6   Komal      22        MP                 4500.00 
7   Muffy      24        Indore             10000.00 

Following command is an example, which would DELETE a customer, whose ID is 6 −
DELETE FROM CUSTOMERS 
WHERE ID = 6;

CUSTOMERS table will now have the following records.
ID  NAME       AGE       ADDRESS              SALARY 
1   Ramesh     32        Ahmedabad            2000.00 
2   Khilan     25        Delhi                1500.00 
3   kaushik    23        Kota                 2000.00 
4   Chaitali   25        Mumbai               6500.00 
5   Hardik     27        Bhopal               8500.00 
7   Muffy      24        Indore               10000.00 

If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause. DELETE query would be as follows −
DELETE FROM CUSTOMERS;

CUSTOMERS table now will not have any record.
Create a new empty file in Java

A new empty file with the required abstract path name can be created using the method java.io.File.createNewFile(). This method requires no parameters and it returns true if the file is newly created and it did not exist previously. If the file existed previously, it returns false.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("File: " + file);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
File: demo1.txt
Now let us understand the above program.
The file is created using the method java.io.File.createNewFile(). Then the file name is printed. A code snippet that demonstrates this is given as follows −
try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("File: " + file);
} catch(Exception e) {
   e.printStackTrace();
}
Load testing using LOCUST

19 Feb, 2020
Locust is an open source load testing tool. Load testing is a type of software testing that is conducted to check the tolerance/behavior of the system under a specific expected load. The target of locust is load-testing web sites and checking number of concurrent users a system can handle.During a locust test, a swarm of locusts will attack the target i.e website. The behavior of each locust is configurable and the swarming process is monitored from a web UI in real-time.
Speciality of locust:
Test scenarios can be written in Python
Distributed and scalable
Web-based UI
Any system can be tested using this tool
Installation:
Locust can be installed with pip.
pip install locust
Once the locust is successfully installed, a locust command should be available in your shell.To see more available options:
locust --help
Getting started:
from locust import HttpLocust, TaskSet, taskfrom locust import ResponseErrorimport json     class UserBehavior(TaskSet):       def __init__(self, parent):        super(UserBehavior, self).__init__(parent)        self.token = ""        self.headers = {}       def on_start(self):        # The on_start method is called         # when a simulated user starts         # executing that TaskSet class        self.token = self.login()        self.headers = {'Authorization': 'Bearer {}'.format(self.token)}        self.login()       def login(self):        # admin login  and retrieving it's access token        response = self.client.post("/login/",                                    data = {'username': 'admin',                                          'password': 'ZYT5nsg3565!'})                  return json.loads(response._content)['access']        class WebsiteUser(HttpLocust):    # The task_set attribute should point    # to a TaskSet class which defines     # the behaviour of the user    task_set = UserBehavior    min_wait = 5000    max_wait = 9000
Start locust:To run the above code, create a Python file named locustfile.py, and open the terminal in the directory of the above created file. Then write the following command in the terminal.
locust
Note: By default locust searches for locustfile.py.
After the successful execution of the above command, you should open a browser and hit http://127.0.0.1:8089
The Locust UI will appear like below:
python-utility
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.