code-rag-bench/online-tutorials huggingface dataset:
Count number of set bits in a range using bitset - GeeksforGeeks

25 Nov, 2021
Given a large binary number.The task is to count the number of 1’s in a given range from L to R (1 based indexing).Examples: 
Input : s = “101101011010100000111”, L = 6, R = 15 Output : 5 s [L : R] = “1011010100” There is only 5 set bits.Input : s = “10110”, L = 2, R = 5 Output : 2  
 
Approach:  
Convert the string of size len to the bitset of size N.
There is no need of (N – len) + (L – 1) bits in the left side and (N – R) bits in the right side of the bitset .
Remove those bits efficiently using left and right shift bitwise operation.
Now there are all zeroes in the left side of L and right side of R, so just use count() function to get the count of 1’s in the bitset as all positions except [L, R] are ‘0’.
Below is the implementation of above approach:  
C++
Python3
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std;#define N 32 // C++ function to count// number of 1's using bitsetint GetOne(string s, int L, int R){     int len = s.length();     // Converting the string into bitset    bitset<N> bit(s);     // Bitwise operations    // Left shift    bit <<= (N - len + L - 1);     // Right shifts    bit >>= (N - len + L - 1);    bit >>= (len - R);     // Now bit has only those bits    // which are in range [L, R]     // return count of one in [L, R]    return bit.count();} // Driver codeint main(){     string s = "01010001011";     int L = 2, R = 4;     cout << GetOne(s, L, R);     return 0;}
# Python3 implementation of above approach N = 32 # function for converting binary# string into integer valuedef binStrToInt(binary_str):    length = len(binary_str)    num = 0    for i in range(length):        num = num + int(binary_str[i])        num = num * 2    return num / 2  # function to count# number of 1's using bitsetdef GetOne(s, L, R) :     length = len(s);     # Converting the string into bitset    bit = s.zfill(32-len(s));         bit = int(binStrToInt(bit))     # Bitwise operations    # Left shift    bit <<= (N - length + L - 1);     # Right shifts    bit >>= (N - length + L - 1);    bit >>= (length - R);     # Now bit has only those bits    # which are in range [L, R]     # return count of one in [L, R]    return bin(bit).count('1');  # Driver codeif __name__ == "__main__" :     s = "01010001011";     L = 2; R = 4;     print(GetOne(s, L, R));     # This code is contributed by AnkitRai01
2
 
Time Complexity: O(len)
Auxiliary Space: O(len)
ankthon
subhammahato348
CPP-bitset
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Hamming code Implementation in C/C++
Write an Efficient Method to Check if a Number is Multiple of 3
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
How to prepend a string to a column value in MySQL?

To prepend a string to a column value in MySQL, we can use the function CONCAT. The CONCAT function can be used with UPDATE statement.
Creating a table.
mysql> create table PrependStringOnCOlumnName
   -> (
   -> Id int,
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (1.35 sec)
Inserting some records.
mysql> insert into PrependStringOnCOlumnName values(1,'John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into PrependStringOnCOlumnName values(2,'Carol');
Query OK, 1 row affected (0.18 sec)

mysql> insert into PrependStringOnCOlumnName values(3,'Johnson');
Query OK, 1 row affected (0.45 sec)
Displaying all the records.
mysql> select *from PrependStringOnCOlumnName;
The following is the output.
+------+---------+
| Id   | Name    |
+------+---------+
|    1 | John    |
|    2 | Carol   |
|    3 | Johnson |
+------+---------+
3 rows in set (0.00 sec)

Syntax to prepend a string to column value.
UPDATE yourTableName SET yourColumnName = CONCAT(Value,yourColumnName);
Applying the above query to prepend a string ‘First’ to a column ‘Name’
mysql> UPDATE PrependStringOnCOlumnName SET Name=CONCAT('First',Name);
Query OK, 3 rows affected (0.13 sec)
Rows matched: 3  Changed: 3  Warnings: 0
Let us check what we did above.
mysql> select *from PrependStringOnCOlumnName;
The following is the output that displays we have successfully concatenated a string to column value.
+------+--------------+
| Id   | Name         |
+------+--------------+
|    1 | FirstJohn    |
|    2 | FirstCarol   |
|    3 | FirstJohnson |
+------+--------------+
3 rows in set (0.00 sec)
Java Program to check if all digits of a number divide it

To check if all digits of a number divide it, the Java code is as follows −
 Live Demo
import java.io.*;
public class Demo{
   static boolean divisibility_check(int val, int digit){
      return (digit != 0 && val % digit == 0);
   }
   static boolean divide_digits(int val){
      int temp = val;
      while (temp > 0){
         int digit = val % 10;
         if ((divisibility_check(val, digit)) == false)
         return false;
         temp /= 10;
      }
      return true;
   }
   public static void main(String args[]){
      int val = 150;
      if (divide_digits(val))
      System.out.println("All the digits of the number divide the number completely.");
      else
      System.out.println("All the digits of the number are not divided by the number
      completely.");
   }
}
All the digits of the number are not divided by the number completely.
A class named Demo contains a function named ‘divisibility_check’, which has two parameters- the number and the digit. This function returns a Boolean value depending on whether the output returned is true or false. It checks if the number is not 0 and if the number divided by digit of the number is completely divided or not.
Another function named ‘divide_digits’ is a Boolean function that takes the number as the parameter. This function checks to see if all the digits in a number divide the number fully. In the main function, a value for the number is defined and the function is called with this value, if it returns ‘true’, then relevant message is displayed. If not, then it gives a message stating the number can’t be completely divided.
Java Examples - Displaying months in short format

How to display name of the months in short format ?
This example displays the names of the months in short form with the help of DateFormatSymbols().getShortMonths() method of DateFormatSymbols class.
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;

public class Main {
   public static void main(String[] args) {
      String[] shortMonths = new DateFormatSymbols().getShortMonths();
      
      for (int i = 0; i < (shortMonths.length-1); i++) {
         String shortMonth = shortMonths[i];
         System.out.println("shortMonth = " + shortMonth);
      }
   }
}
The above code sample will produce the following result.
shortMonth = Jan
shortMonth = Feb
shortMonth = Mar
shortMonth = Apr
shortMonth = May
shortMonth = Jun
shortMonth = Jul
shortMonth = Aug
shortMonth = Sep
shortMonth = Oct
shortMonth = Nov
shortMonth = Dec

The following is an another sample example of Date, Time and short month.
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;

public class Main { 
   public static void main(String[] argv) throws Exception {
      String str1 = "dd-MMM-yy";
      Date d = Calendar.getInstance().getTime();
      SimpleDateFormat sdf = new SimpleDateFormat(str1, Locale.FRENCH);
      System.out.println(sdf.format(d));
      sdf = new SimpleDateFormat(str1, Locale.ENGLISH);
      System.out.println(sdf.format(d));
   }
}
The above code sample will produce the following result(Result is depends on Current date.
11-nov.-16
11-Nov-16

 Print
 Add Notes
 Bookmark this page
C++ program to find the Parity of a number efficiently

In this article, we will be discussing a program to find the parity of a given number N.
Parity is defined as the number of set bits (number of ‘1’s) in the binary representation of a number.
If the number of ‘1’s in the binary representation are even, the parity is called even parity and if the number of ‘1’s in the binary representation is odd, the parity is called odd parity.
If the given number is N, we can perform the following operations.
y = N ^ (N >> 1)
y = y ^ (y >> 2)
y = y ^ (y >> 4)
y = y ^ (y >> 8)
y = y ^ (y >> 16)
Once all these operations are done, the rightmost bit in y will represent the parity of the number. If the bit is 1, the parity would be odd and if the bit would be 0, the parity will be even.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool calc_parity(int N) {
   int y;
   y= N ^ (N >> 1);
   y = y ^ (y >> 2);
   y = y ^ (y >> 4);
   y = y ^ (y >> 8);
   y = y ^ (y >> 16);
   //checking the rightmost bit
   if (y & 1)
      return 1;
   return 0;
}
int main() {
   int n=1345;
   int result = calc_parity(n);
   if(result==1)
      cout << "Odd Parity" << endl;
   else
      cout << "Even Parity" << endl;
   return 0;
}
Even Parity
Python | Convert list of strings to space separated string - GeeksforGeeks

16 May, 2020
Given a list of strings, write a Python program to convert the given list of strings into a space-separated string.
Examples:
Input : ['geeks', 'for', 'geeks']
Output : geeks for geeks

Input : ['Python', 'Language']
Output : Python Language

Approach #1 : Python string translate()
The string translate() method returns a string where each character is mapped to its corresponding character in the translation table. The limitation of this method is that it does not work for Python 3 and above versions.
# Python3 program to Convert a list of # strings to space-separated string  def convert(lst):          return str(lst).translate(None, '[],\'')      # Driver codelst = ['geeks', 'for', 'geeks']print(convert(lst))
geeks for geeks

 Approach #2 : join() functionThe join() method is a string method and returns a string in which the elements of sequence have been joined by str separator. In this approach space is the separator.
# Python3 program to Convert list of # strings to space separated string  def convert(lst):          return ' '.join(lst)      # Driver codelst = ['geeks', 'for', 'geeks']print(convert(lst))
geeks for geeks

shaikmudassir753
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python?
Python Get a list as input from user

In this article we will see you how to ask the user to enter elements of a list and finally create the list with those entered values.
The format function can be used to fill in the values in the place holders and the input function will capture the value entered by the user. Finally, we will append the elements into the list one by one.
listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
# iterating till the range
for i in range(0, n):
   print("Enter element No-{}: ".format(i+1))
   elm = int(input())
   listA.append(elm) # adding the element
print("The entered list is: \n",listA)
Running the above code gives us the following result −
Enter number of elements in the list : 4
Enter element No-1:
7
Enter element No-2:
45
Enter element No-3:
1
Enter element No-4:
74
The entered list is:
[7, 45, 1, 74]
Another approach is to ask the user to enter the values continuously but separated by comma. Here we use the map function together the inputs into a list.
listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
# Enter elements separated by comma
listA = list(map(int,input("Enter the numbers : ").strip().split(',')))[:n]
print("The entered list is: \n",listA)
Running the above code gives us the following result −
Enter number of elements in the list : 4
Enter the numbers : 12,45,65,32
The entered list is:
[12, 45, 65, 32]
We can also use input function twice so that we can create a list of lists. Use the range function to keep account on number of elements to be entered and the format function to enter the elements one by one. Finally, we append each entered element to the newly created list.
listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
# Each sublist has two elements
for i in range(0, n):
   print("Enter element No-{}: ".format(i + 1))
   ele = [input(), int(input())]
   listA.append(ele)
print("The entered list is: \n",listA)
Running the above code gives us the following result −
Enter number of elements in the list : 2
Enter element No-1:
'Mon'
3
Enter element No-2:
'Tue'
4
The entered list is:
[["'Mon'", 3], ["'Tue'", 4]]
How to list all databases in the Mongo shell?

To list all databases in the Mongo shell, you need to use show command. The syntax is as follows −
show dbs;
Let us implement the above syntax for MongoDB. The query is as follows −
> show dbs;
The following is the output −
admin 0.000GB
config 0.000GB
local 0.000GB
sample 0.000GB
sampleDemo 0.000GB
test 0.003GB
If you create a new database in MongoDB then it won’t be present in list of databases.
Let us check the same. Create a new database −
> use studentTracker;
switched to db studentTracker
Now list all the databases from Mongo shell. The query is as follows −
> show dbs;
The following is the output −
admin 0.000GB
config 0.000GB
local 0.000GB
sample 0.000GB
sampleDemo 0.000GB
test 0.003GB
Look at the above sample output, the database ‘studentTracker’ is not present in database list. This is because the database is empty and it isn’t having any collection −
Note: In order to display the newly created database in the list, you need to create a collection in the new database.
How to draw a Bezier Curve with HTML5 Canvas?

The HTML5 <canvas> tag is used to draw graphics, animations, etc. using scripting. It is a new tag introduced in HTML5. The canvas element has a DOM method called getContext, which obtains rendering context and its drawing functions. This function takes one parameter, the type of context 2d.
To draw a Bezier curve with HTML5 canvas, use the bezierCurveTo() method. The method adds the given point to the current path, connected to the previous one by a cubic Bezier curve with the given control points.
You can try to run the following code to learn how to draw a Bezier curve on HTML5 Canvas. The x and y parameters in bezierCurveTo() method are the coordinates of the endpoint. cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the coordinates of the second control point.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas Tag</title>
</head>

<body>
<canvas id = "newCanvas" width = "500" height = "300" style = "border:1px solid #000000;"></canvas>
<script>
var c = document.getElementById('newCanvas');
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.moveTo(75,40);
ctx.bezierCurveTo(75,37,70,25,50,25);
ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
ctx.bezierCurveTo(20,80,40,102,75,120);
ctx.bezierCurveTo(110,102,130,80,130,62.5);
ctx.bezierCurveTo(130,62.5,130,25,100,25);
ctx.bezierCurveTo(85,25,75,37,75,40);
ctx.fill();
</script>

</body>
</html>
Type of Java constructors

There are two types of constructor java supports −
Default constructor: A constructor with no arguments
Parameterized constructor: A constructor with parameters.
public class Puppy {
   //Default constructor
   public Puppy() {
   }
   //Parameterized constructor
   public Puppy(String name) {
      // This constructor has one parameter, name.
   }
}
JavaScript Break and Continue

The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in 
the loop.
You have already seen the break statement used in an earlier 
chapter of this tutorial. It was used to "jump out" of a switch() statement.
The break statement can also be used to jump out of a loop:
In the example above, the break statement ends the loop ("breaks" the loop)
when the loop counter (i) is 3.
The continue statement breaks one iteration (in the loop), if a specified 
condition occurs, and continues with the next iteration in the loop.
This example skips the value of 3: 
To label JavaScript statements you precede the statements with a label name 
and a colon:
The break and the continue statements are the only JavaScript statements that 
can "jump out of" a code block.
Syntax:

The continue 
statement (with or without a label reference) can only be used to skip one 
loop iteration.
The break statement, without a label reference, can only be used to 
jump out of a loop 
or a switch.
With a label reference, the break statement can be used to jump out 
of any code block: 
A code block is a block of code between { and }.
Make the loop stop when i is 5.
for (i = 0; i < 10; i++) {
  console.log(i);
  if (i == 5) {   
    ;
  }
}

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Binary Tree with Array implementation in C++

A binary tree is a special type of tree in which each node of the tree can have at most two child nodes. These child nodes are known as right child and left child.
A simple binary tree is −
For representing trees, there are two ways,
dynamic node representation which uses linked list
Sequential representation which uses array.
Here, we will discuss about array representation of binary tree. For this we need to number the nodes of the BT. This numbering can start from 0 to (n-1) or from 1 to n.
Lets derive the positions of nodes and their parent and child nodes in the array.
When we use 0 index based sequencing,
Suppose parent node is an index p.
Then, the left_child node is at index (2*p)+ 1.
The right_child node is at index (2*p) + 2.
Root node is at index 0.
left_child is at index 1.
Right_child is at index 2.
When we use 1 index based sequencing,
Suppose parent node is at index p,
Right_node is at index (2*p).
Left_node is at index (2*p)+1.
Root node is at index 1.
left_child is at index 2.
Right_child is at index 3.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
char tree[10];
int rootnode(char key){
   if(tree[0] != '\0')
      cout<<"Tree already had root";
   else
      tree[0] = key;
   return 0;
}
int leftchild(char key, int parent){
   if(tree[parent] == '\0')
      cout <<"\nCan't set child at"<<(parent * 2) + 1<<" , no parent found";
   else
      tree[(parent * 2) + 1] = key;
   return 0;
}
int rightchild(char key, int parent){
   if(tree[parent] == '\0')
      cout<<"\nCan't set child at"<<(parent * 2) + 2<<" , no parent found";
   else
      tree[(parent * 2) + 2] = key;
   return 0;
}
int traversetree(){
   cout << "\n";
   for(int i = 0; i < 10; i++){
      if(tree[i] != '\0')
         cout<<tree[i];
      else
         cout<<"-";
   }
   return 0;
}
int main(){
   rootnode('A');
   rightchild('C', 2);
   leftchild('D', 0);
   rightchild('E', 1);
   rightchild('F', 2);
   traversetree();
   return 0;
}
Can't set child at6 , no parent found
Can't set child at6 , no parent found
AD--E-----
Find the elements of a vector that are not in another vector in R - GeeksforGeeks

26 Mar, 2021
Two vectors can hold some values common. This article discusses how can we find set difference of these vectors i.e. display elements which are present in one vector but not in the other.
If we want all the elements of a vector that are not in another vector then we can use setdiff() method in R. It takes two vectors and returns a new vector with the elements of the first vector that are not present in the second vector.
Syntax:
setdiff(a, b)
Approach
Create first vector
Create second vector
Find set difference
Store this in another vector
Display result
Example 1:
R
a = c(1, 3, 8, 29, 9, 71, 90)b = c(17, 8, 6, 90)  print("vector a is")  print("vector b is")  print("Elements of vector a that are not in vector b are:")  ans = setdiff(a, b)print(ans)
Output:
[1]  1  3 29  9 71
Example 2:
R
a = c("ram", "rahul", "rohan", "ashish", "rohit", "kapil")b = c("ram", "aakash", "ashish")  print("vector a is")  print("vector b is")  print("Elements of vector a that are not in vector b are:")  ans = setdiff(a, b)print(ans)
Output:
[1] “rahul” “rohan” “rohit” “kapil”
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to import an Excel File into R ?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
GitLab - Create Project

In this chapter, we will discuss about how to create a new project in the GitLab. 
Step 1 − To create new project, login to your GitLab account and click on the New project button in the dashboard −
Step 2 − It will open the New project screen as shown below in the image −
Enter the project name, description for the project, visibility level (accessing the project's visibility in publicly or internally) and click on the Create project button.
Step 3 − Next it will create a new project (here given the project name as first-gitlab-prjt) with successful message as shown below −
Step 4 − You can clone the repository to your local system by using the git-clone command −
The clone command makes a copy of repository into a new directory called first-gitlab-prjt. 
Step 5 − Now go to your newly created directory and type the below command −
C:\>cd first-gitlab-prjt
C:\first-gitlab-prjt>touch README.md

The above command creates a README.md file in which you can put the information about your folder.
Step 6 − Add the README.md file to your created directory by using the below command −
C:\first-gitlab-prjt>git add README.md

Step 7 − Now store the changes to the repository along with the log message as shown below −
C:\first-gitlab-prjt>git commit -m "add README"

The flag -m is used for adding a message on the commit.
Step 8 − Push the commits to remote repository which are made on the local branch −
C:\first-gitlab-prjt>git push -u origin master

The below image depicts the usage of above commands in pushing the commits to remote repository −
 Print
 Add Notes
 Bookmark this page
Get ASCII table in Arduino

In this article, we will walkthrough the example code in Arduino, which helps generate the ASCII table in the Serial Monitor output. For your reference, this is what the ASCII table looks like − http://www.asciitable.com/
It contains the character, followed by its ASCII code in decimal, hexadecimal, and sometimes, even octal and binary representations. In this example, we will print out all these representations for printable ASCII characters. Remember that the first printable ASCII character starts from number 33, and the printable characters go on up to number 126. Since we will print out the ASCII table on the Serial Monitor, we will concern ourselves with only printable characters.
In order to access this example, go to File → Examples → 04 Communication → ASCII Table.
Let us begin the walkthrough of this code. As you can see, we begin with the initialization of Serial in the setup and then wait for the Serial port to connect. After that, we just print the title of the sketch.
void setup() {
   //Initialize serial and wait for port to open:
   Serial.begin(9600);
   while (!Serial) {
      ; // wait for serial port to connect. Needed for native USB port only
   }
   // prints title with ending line break
   Serial.println("ASCII Table ~ Character Map");
}
Next, there is the definition of the global variable thisByte. It is initialized to 33. Remember that 33 is equal to the first printable ASCII character.
int thisByte = 33;
Within the loop, we print the value of thisByte as a character (using Serial.write()), then we print its decimal value (using Serial.print()), and then we print its hexadecimal, octal and binary representations, using format specifiers in Serial.print().
We later increment the value of thisByte, until we reach the value of 126, after which we enter an infinite loop, and essentially do nothing.
void loop() {
   // prints value unaltered, i.e. the raw binary version of the byte.
   // The Serial Monitor interprets all bytes as ASCII, so 33, the first number will show up as '!'
   Serial.write(thisByte);

   Serial.print(", dec: ");
   // prints value as string as an ASCII-encoded decimal (base 10).
   // Decimal is the default format for Serial.print() and Serial.println(),
   // so no modifier is needed:
   Serial.print(thisByte);
   // But you can declare the modifier for decimal if you want to.
   // this also works if you uncomment it:
   // Serial.print(thisByte, DEC);

   Serial.print(", hex: ");
   // prints value as string in hexadecimal (base 16):
   Serial.print(thisByte, HEX);

   Serial.print(", oct: ");
   // prints value as string in octal (base 8);
   Serial.print(thisByte, OCT);
   Serial.print(", bin: ");
   // prints value as string in binary (base 2) also prints ending line break:
   Serial.println(thisByte, BIN);

   // if printed last visible character '~' or 126, stop:
   if (thisByte == 126) { // you could also use if (thisByte == '~')
   {
      // This loop loops forever and does nothing
      while (true) {
         continue;
      }
   }
   // go on to the next character
   thisByte++;
}
The Serial Monitor Output is shown below −
C library function - atoi()

The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
Following is the declaration for atoi() function.
int atoi(const char *str)
str − This is the string representation of an integral number.
str − This is the string representation of an integral number.
This function returns the converted integral number as an int value. If no valid conversion could be performed, it returns zero.
The following example shows the usage of atoi() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   int val;
   char str[20];
   
   strcpy(str, "98993489");
   val = atoi(str);
   printf("String value = %s, Int value = %d\n", str, val);

   strcpy(str, "tutorialspoint.com");
   val = atoi(str);
   printf("String value = %s, Int value = %d\n", str, val);

   return(0);
}
Let us compile and run the above program that will produce the following result −
String value = 98993489, Int value = 98993489
String value = tutorialspoint.com, Int value = 0


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Difference between %d and %i format specifier in C 

The format specifier %d takes integer value as a signed decimal integer value which means values should be decimal whether it is negative or positive.
Here is an example of format specifier %d in C language,
 Live Demo
#include <stdio.h>
int main() {
   int v1 = 7456;
   int v2 = -17346;
   printf("The value in decimal form : %d\n", v1);
   printf("The value in negative : %d", v2);
   return 0;
}
The value in decimal form : 7456
The value in negative : -17346
The format specifier %i takes integer value as an integer value which means values should be decimal, octal and hexadecimal and octal value is provided by preceding ‘0’ while hexadecimal value is provided by preceding ‘0x’.
Here is an example of format specifier %i in C language,
 Live Demo
#include <stdio.h>
int main() {
   int v1 = 1327;
   int v2 = 0x42451;
   printf("The value in decimal form : %d\n", v1);
   printf("The value in hexadecimal form : %i", v2);
   return 0;
}
The value in decimal form : 1327
The value in hexadecimal form : 271441
How to change the point size in geom_point conditionally in R?

To change the point size in geom_point conditionally, we can define the condition in geom_point with aes and the size using scale_size_manual function of ggplot2 package. For example, if we have a data frame called df that contains two columns say x and y then the scatterplot with different size of points for x values greater than 5 and less than equal to 5 can be drawn by using the below command −
ggplot(df,aes(x,y))+geom_point(aes(size=x>5))+scale_size_manual(values=c(4,7))
Consider the below data frame −
 Live Demo
x<-rnorm(20,6,1.2)
y<-rnorm(20,10,0.3)
df<-data.frame(x,y)
df
         x        y
1   3.328193  10.220022
2   5.230092  9.947973
3   7.870149  9.385716
4   7.250473  10.312204
5   7.859332  9.628415
6   6.344924  9.389630
7   5.950067  9.927424
8   3.598442  10.078970
9   5.243530  9.545237
10  5.546215  10.153369
11  8.037851  9.903173
12  7.607763  10.354359
13  6.264471  10.029382
14  5.604859  10.421269
15  6.053001  9.621305
16  6.778453  9.819948
17  5.570402  9.931298
18  5.046742  10.003627
19  6.783095  9.783940
20  4.774991  10.502797
Loading ggplot2 package and creating a scatterplot between x and y −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating scatterplot between x and y with different point size for x values greater than 6 and less than equal to 6 −
ggplot(df,aes(x,y))+geom_point(aes(size=x>6))+scale_size_manual(values=c(3,10))
ggplot(df,aes(x,y))+geom_point(aes(size=x>6))+scale_size_manual(values=c(2,6))
ggplot(df,aes(x,y))+geom_point(aes(size=x>6))+scale_size_manual(values=c(4,7))
Converting seconds in years days hours and minutes in JavaScript

We are required to write a JavaScript function that takes in a number, num, that represents the
number of seconds as the first and the only argument.
Our function should then construct and return a string that contains information of years, days,
hours and minutes contained in those seconds, obviously if contained at all.
For the purpose of this question, we consider that all the years have 365 days
For example, if the input to the function is −
const num = 5454776657;
Then the output should be −
const output = '172 years, 353 days, 23 hours, 44 minutes and 17 seconds';
Following is the code −
const findTime = (num) => {
   if(num < 1){
      return '0'
   };
   const qualifier = num => (num > 1 ? 's' : '')
   const numToStr = (num, unit) => num > 0 ? ` ${num}
   ${unit}${qualifier(num)}` : ''
   const oneMinute = 60;
   const oneHour = oneMinute * 60;
   const oneDay = oneHour * 24;
   const oneYear = oneDay * 365;
   const times = {
      year: ~~(num / oneYear),
      day: ~~((num % oneYear) / oneDay),
      hour: ~~((num % oneDay) / oneHour),
      minute: ~~((num % oneHour) / oneMinute),
      second: num % oneMinute,
   };
   let str = '';
   for (let [key, value] of Object.entries(times)) {
      str += numToStr(times[key], key)
   }
   const arr = str.trim().split(' ')
   const res = []
   arr.forEach((x, i) => {
      if (i % 2 === 0 && i !== 0) res.push(i === arr.length - 2 ? 'and' : ',')
      res.push(x)
   })
   return res.join(' ').replace(/\s,/g, ',')
}
console.log(findTime(5454776657));
Following is the console output −
172 years, 353 days, 23 hours, 44 minutes and 17 seconds
C library function - longjmp()

The C library function void longjmp(jmp_buf environment, int value) restores the environment saved by the most recent call to setjmp() macro in the same invocation of the program with the corresponding jmp_buf argument.
Following is the declaration for longjmp() function.
void longjmp(jmp_buf environment, int value)
environment − This is the object of type jmp_buf containing information to restore the environment at the setjmp's calling point.
environment − This is the object of type jmp_buf containing information to restore the environment at the setjmp's calling point.
value − This is the value to which the setjmp expression evaluates.
value − This is the value to which the setjmp expression evaluates.
This function does not return any value.
The following example shows the usage of longjmp() function.
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

int main () {
   int val;
   jmp_buf env_buffer;

   /* save calling environment for longjmp */
   val = setjmp( env_buffer );
   
   if( val != 0 ) {
      printf("Returned from a longjmp() with value = %s\n", val);
      exit(0);
   }
   printf("Jump function call\n");
   jmpfunction( env_buffer );
   
   return(0);
}

void jmpfunction(jmp_buf env_buf) {
   longjmp(env_buf, "tutorialspoint.com");
}
Let us compile and run the above program that will produce the following result −
Jump function call
Returned from a longjmp() with value = tutorialspoint.com


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to sum rows of VARCHAR datatype or TIME datatype in MySQL?

Let us first create a −
mysql> create table DemoTable1442
   -> (
   -> DueTime time
   -> );
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1442 values('00:08:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1442 values('00:04:00');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1442 values('12:55:00');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select −
mysql> select * from DemoTable1442;
This will produce the following output −
+----------+
| DueTime  |
+----------+
| 00:08:00 |
| 00:04:00 |
| 12:55:00 |
+----------+
3 rows in set (0.00 sec)
Following is the query to sum rows of VARCHAR datatype or TIME datatype in MySQL −
mysql> select sec_to_time(sum(time_to_sec(DueTime) ) ) as TotalTime from DemoTable1442;
This will produce the following output −
+-----------+
| TotalTime |
+-----------+
| 13:07:00  |
+-----------+
1 row in set (0.03 sec)
Can Enum extend any class in java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can define an enumeration using the keyword enum followed by the name of the enumeration as −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Just like arrays, the elements/constants in an enumeration are identified using numbers starting from 0 in the above example the days are identified using numbers as shown in the following illustration −
Enumerations are similar to classes and, you can have variables, methods and constructors within them. Only concrete methods are allowed in an enumeration.
All enumerations internally extend a class named Enum the base class of all the language enumeration types. Since Java doesn’t support multiple inheritance you cannot extend another class with enumeration if you try to do so, a compile time error will be generated.
In the following java snippet we have a class with name Sample and we have created an Enum type named Scooters and tried to extend the Sample class.
import java.util.Scanner;
class Sample {
}
enum Scooters extends Sample {
}
On executing, this class generates the following compile time error.
D:\>javac EnumExample.java
EnumExample.java:5: error: '{' expected
enum Scooters extends Sample{
              ^
EnumExample.java:5: error: ',', '}', or ';' expected
enum Scooters extends Sample{
                      ^
2 errors
Check for duplicates in an array in MongoDB?

To check for duplicates in an array, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo756.insertOne({"SubjectName":["MySQL","MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb01e0d5637cd592b2a4add")
}
> db.demo756.insertOne({"SubjectName":["MongoDB","MySQL","MongoDB","C","C+","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb01e2b5637cd592b2a4ade")
}
Display all documents from a collection with the help of find() method −
> db.demo756.find();
This will produce the following output −
{ "_id" : ObjectId("5eb01e0d5637cd592b2a4add"), "SubjectName" : [ "MySQL", "MongoDB", "Java" ] }
{ "_id" : ObjectId("5eb01e2b5637cd592b2a4ade"), "SubjectName" : [ "MongoDB", "MySQL", "MongoDB", "C", "C+", "MySQL" ] }
Following is the query to check for duplicates in an array −
> db.demo756.aggregate([
...    {"$project": {"SubjectName":1}},
...    {"$unwind":"$SubjectName"},
...    {"$group": {"_id":{"_id":"$_id", "Name":"$SubjectName"}, "count":{"$sum":1}}},
...    {"$match": {"count":{"$gt":1}}},
...    {"$group": {"_id": "$_id._id", "SubjectName":{"$addToSet":"$_id.Name"}}}
... ])
This will produce the following output −
{ "_id" : ObjectId("5eb01e2b5637cd592b2a4ade"), "SubjectName" : [ "MongoDB", "MySQL" ] }
Find Index Position of First Non-NA Value in vector in R - GeeksforGeeks

16 May, 2021
An atomic vector contains elements belonging to the same data type. It may also contain missing or NA values, at any index within the range of this vector. These NA values can be accessed in R using standard indexing methods. In this article, we are going to see how to find the Index Position of First Non-NA Value in vector in R Programming Language.
Method 1: Using is.na() and which() methods
The negation is.na() method is first applied over the atomic vector, which returns a boolean vector of the same length, where TRUE indicates that the value is non-na and FALSE indicates a missing or NA value. This is followed by the application of which() method which returns the indices of the non-na values. The aggregate function min() is then applied to get the first or the minimum elements out of all the indexes. 
Code:
R
# declaring a vectorvec <- c(NA, NA, 2, NA, 5, 7)print ("Original Vector")print (vec)  # getting indexes of all the non na elementsnon_na_vec <- which(!is.na(vec))  # determining the minimum from these indicesfirst_non_na <- min(non_na_vec)print ("First non-na index")print (first_non_na)
Output:
[1] "Original Vector"
[1] NA NA  2 NA  5  7
[1] "First non-na index"
[1] 3
In case the vector doesn’t contain any non-missing values, then this approach throws an exception and returns Inf 
Warning message:
In min(non_na_vec) : no non-missing arguments to min; returning Inf
Method 2: which.max() method
which.max() method returns the first argument that is encountered within the vector with non-na value. The method has the following syntax in R : 
which.max(vec)
Code:
R
# declaring a vectorvec <- c(NA, 1, 3, NA, 2, NA, 5, 7)print ("Original Vector")print (vec)  # getting indexes of all the non na elementsnon_na_vec <- which.max(!is.na(vec))print ("First non-na index")print (non_na_vec)
Output:
[1] "Original Vector"
[1] NA  1  3 NA  2 NA  5  7
[1] "First non-na index"
[1] 2
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
C# Program for Maximum size square sub-matrix with all 1s - GeeksforGeeks

12 Dec, 2018
Given a binary matrix, find out the maximum size square sub-matrix with all 1s.
For example, consider the below binary matrix.
C#
// C# Code for Maximum size square// sub-matrix with all 1s  using System;  public class GFG {    // method for Maximum size square sub-matrix with all 1s    static void printMaxSubSquare(int[, ] M)    {        int i, j;        // no of rows in M[, ]        int R = M.GetLength(0);        // no of columns in M[, ]        int C = M.GetLength(1);        int[, ] S = new int[R, C];          int max_of_s, max_i, max_j;          /* Set first column of S[, ]*/        for (i = 0; i < R; i++)            S[i, 0] = M[i, 0];          /* Set first row of S[][]*/        for (j = 0; j < C; j++)            S[0, j] = M[0, j];          /* Construct other entries of S[, ]*/        for (i = 1; i < R; i++) {            for (j = 1; j < C; j++) {                if (M[i, j] == 1)                    S[i, j] = Math.Min(S[i, j - 1],                                       Math.Min(S[i - 1, j], S[i - 1, j - 1]))                              + 1;                else                    S[i, j] = 0;            }        }          /* Find the maximum entry, and indexes of             maximum entry in S[, ] */        max_of_s = S[0, 0];        max_i = 0;        max_j = 0;        for (i = 0; i < R; i++) {            for (j = 0; j < C; j++) {                if (max_of_s < S[i, j]) {                    max_of_s = S[i, j];                    max_i = i;                    max_j = j;                }            }        }          Console.WriteLine("Maximum size sub-matrix is: ");        for (i = max_i; i > max_i - max_of_s; i--) {            for (j = max_j; j > max_j - max_of_s; j--) {                Console.Write(M[i, j] + " ");            }            Console.WriteLine();        }    }      // Driver program    public static void Main()    {        int[, ] M = new int[6, 5] { { 0, 1, 1, 0, 1 },                                    { 1, 1, 0, 1, 0 },                                    { 0, 1, 1, 1, 0 },                                    { 1, 1, 1, 1, 0 },                                    { 1, 1, 1, 1, 1 },                                    { 0, 0, 0, 0, 0 } };          printMaxSubSquare(M);    }}
Maximum size sub-matrix is: 
1 1 1 
1 1 1 
1 1 1

Please refer complete article on Maximum size square sub-matrix with all 1s for more details!
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Program to Read and Write a Byte Array to File using FileStream Class
C# Program to Check a Specified Type is an Enum or Not
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
C# Program to Join Multiple Data Sources using LINQ
How to Get a Comma Separated String From an Array in C#?
C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method
How to Sort Object Array By Specific Property in C#?
C# Program to Delete an Empty and a Non-Empty Directory
C# Program to Check a Specified Type is a Primitive Data Type or Not
C# Program to Check a Specified Type is an Array or Not
Mahotas - Image Overlay - GeeksforGeeks

12 Dec, 2021
In this article we will see how we can apply image overlay in mahotas. Image overlay in mahotas create an image which is grayscale, but with possible boolean overlays.
In this tutorial we will use “lena” image, below is the command to load it.
mahotas.demos.load('lena')
Below is the lena image  
In order to do this we will use mahotas.overlay methodSyntax : mahotas.overlay(img)Argument : It takes image object as argumentReturn : It returns image object  
Note : Input image should be filtered or should be loaded as grey
In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this 
image = image[:, :, 0]
Below is the implementation  
Python3
# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as npimport matplotlib.pyplot as plt   # loading imageimg = mahotas.demos.load('lena')   # filtering imageimg = img.max(2) print("Image")   # showing imageimshow(img)show() # Overlay methodnew_img = mahotas.overlay(img)   # showing imageprint("Overlay Image")imshow(new_img)show()
Output :
Image
 
Overlay Image
 
Another example 
Python3
# importing required librariesimport mahotasimport numpy as npfrom pylab import gray, imshow, showimport osimport matplotlib.pyplot as plt  # loading imageimg = mahotas.imread('dog_image.png')  # filtering imageimg = img[:, :, 0]   print("Image")   # showing imageimshow(img)show() # Overlay methodnew_img = mahotas.overlay(img)   # showing imageprint("Overlay Image")imshow(new_img)show()
Output :
Image
 
Overlay Image
 
 
surinderdawra388
gabaa406
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Python - Log Normal Distribution in Statistics - GeeksforGeeks

31 Dec, 2019
scipy.stats.lognorm() is a log-Normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : log-Normal continuous random variable
Code #1 : Creating log-Normal continuous random variable
# importing library  from scipy.stats import lognorm      numargs = lognorm.numargs a, b = 4.32, 3.18rv = lognorm(a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D5417648

Code #2 : log-Normal continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = lognorm.rvs(a, b) print ("Random Variates : \n", R)   # PDF R = lognorm.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 3.331870599932328

Probability Distribution : 
 [0.02619234 0.02690484 0.02765301 0.0284395  0.02926727 0.03013955
 0.03105993 0.03203241 0.03306142 0.03415191]


Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449  0.67346939
 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
 1.10204082 1.16326531 1.2244898  1.28571429 1.34693878 1.40816327
 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
 2.20408163 2.26530612 2.32653061 2.3877551  2.44897959 2.51020408
 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
 2.93877551 3.        ]
 
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np      x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = lognorm .pdf(x, 1, 3) y2 = lognorm .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python