code-rag-bench/online-tutorials huggingface dataset:
Sum of Array Elements | Practice | GeeksforGeeks

Given an integer array arr of size n, you need to sum the elements of arr.
Example 1:
Input:
n = 3
arr[] = {3 2 1}
Output: 6
Example 2:
Input:
n = 4
arr[] = {1 2 3 4}
Output: 10

Your Task:
You need to complete the function sumElement() that takes arr and n and returns the sum. The printing is done by the driver code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
Constraints:
1 <= n <= 103
1 <= arri <= 104
0
adityadixit70541 day ago
Take a variable sum=0
then iterate the array and add to sum
then return sum
def sumElement(arr,n):   sum=0   for i in range(n):       sum=sum+arr[i]   return sum
0
mehtay0376 days ago
Python Solution:
def sumElement(arr,n):   #code here   return sum(arr) 
0
atif836146 days ago
JAVA SOLUTION
 if(n==0){
           return 0;
       }
       int sum=0;
       for(int i=0;i<n;i++){
           sum=sum+arr[i];
       }
       return sum;
0
rishabhchemistry31 week ago
 int res=0;   for(int i=0;i<n;i++){       res=res+arr[i];   }   return res;
0
zubairbinmasood786abcd1 week ago
C++ Recursion
if(n<0)
        return 0;
return arr[n - 1] + sumElement(arr,n - 1);
0
zubairbinmasood786abcd1 week ago
C++ One Liner : )
return accumulate(arr,arr + n,0);
0
diagovenk2 weeks ago
Hello guys. Four lines easy java solution
public static int sumElement(int arr[], int n)   {       // Your code here       int sum = 0;       for(int i=0; i<n; i++){           sum += arr[i];       }       return sum;   }
0
shaikhusama7453 weeks ago
C++ Code using Recursionint sumElement(int arr[],int n){   //Base Case   if( n == 0 ){       return 0;   }   if( n == 1 ){       return arr[0];   }
   //Recursive Call
      int remainingPart = sumElement(arr+1,n-1);   int sum = arr[0] + remainingPart;      return sum;} 
0
rapuriteja1 month ago
def sumElement(arr,n):   su = sum(arr)   return su
0
ravi119033851 month ago
//JAVA
int sum=0;       for(int i: arr)       {           sum+=i;       }       return sum;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to subset an R data frame with condition based on only one value from categorical column?

To subset an R data frame with condition based on only one value from categorical
column, we can follow the below steps −
First of all, create a data frame.
Then, subset the data frame with condition using filter function of dplyr package.
Let's create a data frame as shown below −
 Live Demo
Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE)
x<-sample(1:10,25,replace=TRUE)
y<-sample(1:10,25,replace=TRUE)
z<-sample(1:10,25,replace=TRUE)
df<-data.frame(Class,x,y,z)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Class x y z
1 Fourth 10 6 7
2 First 10 1 5
3 Third 3 5 9
4 First 2 8 5
5 Third 4 9 9
6 First 2 5 3
7 Second 2 7 7
8 Third 6 4 4
9 First 2 9 3
10 First 10 7 4
11 Fourth 1 9 3
12 First 8 7 8
13 First 7 5 3
14 First 10 4 2
15 First 8 9 2
16 First 9 9 10
17 Third 1 1 10
18 Third 5 9 6
19 First 3 2 9
20 Third 8 5 4
21 Third 9 2 7
22 Second 5 9 3
23 Third 10 3 6
24 First 10 6 9
25 Third 1 10 4
Using filter function to subset df when x is greater than 5 and Class is First −
Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE)
x<-sample(1:10,25,replace=TRUE)
y<-sample(1:10,25,replace=TRUE)
z<-sample(1:10,25,replace=TRUE)
df<-data.frame(Class,x,y,z)
library(dplyr)
df %>% group_by(Class) %>% filter(x>5 & Class=="First")
# A tibble: 8 x 4
# Groups: Class [1]
Class    x      y    z
 <chr> <int> <int> <int>
1 First 10    1    5
2 First 10    7    4
3 First 8     7    8
4 First 7     5    3
5 First 10    4    2
6 First 8     9    2
7 First 9     9    10
8 First 10    6    9
Using filter function to subset df when y is greater than 5 and Class is First −
Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE)
x<-sample(1:10,25,replace=TRUE)
y<-sample(1:10,25,replace=TRUE)
z<-sample(1:10,25,replace=TRUE)
df<-data.frame(Class,x,y,z)
library(dplyr)
df %>% group_by(Class) %>% filter(y>5 & Class=="First")
# A tibble: 7 x 4
# Groups: Class [1]
Class    x     y    z
 <chr> <int> <int> <int>
1 First 2     8    5
2 First 2     9    3
3 First 10    7    4
4 First 8     7    8  
5 First 8     9    2
6 First 9     9    10
7 First 10    6    9
Using filter function to subset df when z is greater than 5 and Class is First −
Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE)
x<-sample(1:10,25,replace=TRUE)
y<-sample(1:10,25,replace=TRUE)
z<-sample(1:10,25,replace=TRUE)
df<-data.frame(Class,x,y,z)
library(dplyr)
df %>% group_by(Class) %>% filter(z>5 & Class=="First")
# A tibble: 4 x 4
# Groups: Class [1]
Class    x    y    z
<chr> <int> <int> <int>
1 First 8    7    8
2 First 9    9    10
3 First 3    2    9
4 First 10   6    9
C++ Program to Check if it is a Sparse Matrix

A sparse matrix is a matrix in which majority of the elements are 0. In other words, if more than half of the elements in the matrix are 0, it is known as a sparse matrix. For example −
The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix.
1 0 2
5 0 0
0 0 9
A program to check if it is a sparse matrix or not is as follows.
 Live Demo
#include<iostream>
using namespace std;
int main () {
   int a[10][10] = { {2, 0, 0} , {0, 3, 8} , {0, 9, 0} };
   int i, j, count = 0;
   int r = 3, c = 3;
   for (i = 0; i < r; ++i) {
      for (j = 0; j < c; ++j) {
         if (a[i][j] == 0)
         count++;
      }
   }
   cout<<"The matrix is:"<<endl;
   for (i = 0; i < r; ++i) {
      for (j = 0; j < c; ++j) {
         cout<<a[i][j]<<" ";
      }
      cout<<endl;
   }
   cout<<"There are "<<count<<" zeros in the matrix"<<endl;
   if (count > ((r * c)/ 2))
   cout<<"This is a sparse matrix"<<endl;
   else
   cout<<"This is not a sparse matrix"<<endl;
   return 0;
}
The matrix is:
2 0 0
0 3 8
0 9 0
There are 5 zeros in the matrix
This is a sparse matrix
In the above program, a nested for loop is used to count the number of zeros in the matrix. This is demonstrated using the following code snippet.
for (i = 0; i < r; ++i) {
   for (j = 0; j < c; ++j) {
      if (a[i][j] == 0)
      count++;
   }
}
After finding the number of zeros, the matrix is displayed using a nested for loop. This is shown below −
cout<<"The matrix is:"<<endl;
for (i = 0; i < r; ++i) {
   for (j = 0; j < c; ++j) {
      cout<<a[i][j]<<" ";
   }
   cout<<endl;
}
Finally, the number of zeroes are displayed. If the count of zeros is more than half the elements in the matrix, then it is displayed that the matrix is a sparse matrix otherwise the matrix is not a sparse matrix.
cout<<"There are "<<count<<" zeros in the matrix"<<endl;
if (count > ((r * c)/ 2))
cout<<"This is a sparse matrix"<<endl;
else
cout<<"This is not a sparse matrix"<<endl;
How to search Python dictionary for matching key?

If you have the exact key you want to find, then you can simply use the [] operator or get the function to get the value associated with this key. For example,
a = {
   'foo': 45,
   'bar': 22
}
print(a['foo'])
print(a.get('foo'))
This will give the output:
45
45
If you have a substring that you want to search in the dict, you can use substring search on the keys list and if you find it, use the value. For example,
a = {
   'foo': 45,
   'bar': 22
}
for key in a.keys():
   if key.find('oo') > -1:
      print(a[key])
This will give the output
45
Text and File processing using sed Linux Commands

Sed is a stream editor. A stream editor is used to participate in normal textual content transformations on an enter a file. At the same time in some approaches much like an editor which allows scripted edits (comparable to ed). sed works by means of making only one cross over on the input(s) and is more efficient. Now, let us explore more about – “Text and File processing using sed Linux Commands”.
Firstly, to verify the sed version, use the following command –
$ sed --v
The sample output should be like this –
sed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
.........................................................................................

In the below example, abc.txt is the file name.
In this article, we have learnt about – Learn Text and File processing using sed Linux Commands. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
Object Slicing in C++

Object slicing is used to describe the situation when you assign an object of a derived class to an instance of a base class. This causes a loss of methods and member variables for the derived class object. This is termed as information being sliced away. For example,
class Foo {
   int a;
};
class Bar : public Foo {
   int b;
}
Since Bar extends Foo, it now has 2 member variables, a and b. So if you create a variable bar of type Bar and then create a variable of type Foo and assign bar, you'll lose the member variable b in the process. For example,
Bar bar;
Foo foo = bar;
In this case, the information in for about b is lost in a bar. This is known as member slicing.
What is operator binding in Python?

For expressions like −
a == b

first the python interpreter looks up the __eq__() method on the object a. If it finds that, then executes that with b as argument, ie, a.__eq__(b). If this method returns a NotImplemented, then it tries doind just the reverse, ie, it tries to call,
b.__eq__(a)
Handling Child Windows with Cypress

Sometimes on clicking a link or button, it opens to another window often known as
the child window. Cypress has a unique way of handling child windows unlike other
automation tools like Selenium and Protractor. It basically keeps no information on
the child window by shifting its focus from the parent to the child window.
Now let us understand why a link or a button opens a new webpage on a different tab considered as a child. This is due to the attribute target set in the html for that element. If omitted, it shall open in the same window.
Cypress cannot directly handle a child window and it provides the workaround to continue our tasks on the parent window itself. At first the href attribute from the html code is grabbed. This is done with the help JQuery method prop() [ this shall give the value of the property passed as an argument to the method].
Now after the value of the href property is obtained, we can launch the url with the help of visit() command in Cypress. However the test gets successful only if the other application should have the same domain as the original application [a different sub domain of the two applications is accepted].
Cypress takes it as a security threat if we are to access another application in the
same window with the help of visit() command. Thus we cannot work with more than one domain at a time.
Code Implementation to handle child windows.
describe('Tutorialspoint Test', function () {
   // test case
   it('Test Case6', function (){
      // launch the application
      cy.visit("https://accounts.google.com/signup");
      // grab the href prop with prop() JQuery method
      cy.get(':nth-child(1) > a').then(function(l){
         const txt = l.prop('href');
         // get the url in logs
         cy.log(txt);
         // launch the url again
         cy.visit(txt);
      })
   });
});
Test runner logs is as shown below −
Run Python 3 on Sublime Text (Mac) | by Wafiq Syed | Towards Data Science

Sublime Text is one of the most widely used lightweight text editors when it comes to programming. If you’re a Python programmer, you may not be running your preferred version of Python. This tutorial explains how to get Sublime Text running Python 3.7.
If you prefer a video tutorial, here’s my accompanying YouTube video:
Create a new Python file. I called mine scratch.py. It’s important that you save your file as a .py extension before running Python code. Otherwise, you won’t be able to execute Python code. Also, it’s always nice to have a scratch Python file to run quick code.
Now type the following code:
import sysprint(sys.version)
To run the code, press Command B or go to Tools -> Build.
As you can see, my Sublime Text is running Python 2.7. To change this to Python 3.7, we have to add a “Build System.”
Go to Tools -> Build System -> New Build System..
Notice, in my list of Build Systems, I have both Python and Python 3. Python comes automatically and runs 2.7. Python3 is what we’re going to add.
Once you click New Build System... you’ll be brought to a new window called untitled.sublime-build.
We need to change the text between the curly brackets. First delete the code between the brackets. Next copy and paste the following code:
"cmd": ["python3", "-i", "-u", "$file"],     "file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",     "selector": "source.python"
You might have to press Tab to indent the second and third lines. Now save the file by pressing Command S. Rename the file to what you’d like to call your Build System. Something short and clear to understand. I named mine Python3. Note, don’t change the extension, it must be .sublime-build. And don’t change the path either. Sublime Text will put it in the right path by default.
Once you click save, close the file so that you’re back on your scratch.py file. Now go to Tools -> Build System, and select Python3 (or whatever you named your Build System). If you don’t see your new build system, you may have to quit Sublime Text and reopen it.
Now run the same code to test which version of Python you’re using.
There you go, Python 3.7 up and running. Happy coding!
If you’d like to see my video tutorial on running python 3 in Sublime Text, click this link: https://youtu.be/IprbE2C_rsEv
Dart Programming - Runes

Strings are a sequence of characters.  Dart represents strings as a sequence of Unicode UTF-16 code units. Unicode is a format that defines a unique numeric value for each letter, digit, and symbol.
Since a Dart string is a sequence of UTF-16 code units, 32-bit Unicode values within a string are represented using a special syntax. A rune is an integer representing a Unicode code point.
The String class in the dart:core library provides mechanisms to access runes. String code units / runes can be accessed in three ways −
Using String.codeUnitAt() function
Using String.codeUnits property
Using String.runes property
Code units in a string can be accessed through their indexes. Returns the 16-bit UTF-16 code unit at the given index.
String.codeUnitAt(int index);

import 'dart:core'; 
void main(){ 
   f1(); 
} 
f1() { 
   String x = 'Runes'; 
   print(x.codeUnitAt(0)); 
}
It will produce the following output −
82

This property returns an unmodifiable list of the UTF-16 code units of the specified string.
String. codeUnits;

import 'dart:core';  
void main(){ 
   f1(); 
}  
f1() { 
   String x = 'Runes'; 
   print(x.codeUnits); 
} 
It will produce the following output −
[82, 117, 110, 101, 115]

This property returns an iterable of Unicode code-points of this string.Runes extends iterable.
String.runes

void main(){ 
   "A string".runes.forEach((int rune) { 
      var character=new String.fromCharCode(rune); 
      print(character); 
   });  
} 
It will produce the following output −
A 
s 
t 
r 
i 
n 
g

Unicode code points are usually expressed as \uXXXX, where XXXX is a 4-digit hexadecimal value. To specify more or less than 4 hex digits, place the value in curly brackets.  One can use the constructor of the Runes class in the dart:core library for the same.
main() { 
   Runes input = new Runes(' \u{1f605} '); 
   print(new String.fromCharCodes(input)); 
}  
It will produce the following output −

    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
C library function - calloc()

The C library function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero.
Following is the declaration for calloc() function.
void *calloc(size_t nitems, size_t size)
nitems − This is the number of elements to be allocated.
nitems − This is the number of elements to be allocated.
size − This is the size of elements.
size − This is the size of elements.
This function returns a pointer to the allocated memory, or NULL if the request fails.
The following example shows the usage of calloc() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   int i, n;
   int *a;

   printf("Number of elements to be entered:");
   scanf("%d",&n);

   a = (int*)calloc(n, sizeof(int));
   printf("Enter %d numbers:\n",n);
   for( i=0 ; i < n ; i++ ) {
      scanf("%d",&a[i]);
   }

   printf("The numbers entered are: ");
   for( i=0 ; i < n ; i++ ) {
      printf("%d ",a[i]);
   }
   free( a );
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Number of elements to be entered:3
Enter 3 numbers:
22
55
14
The numbers entered are: 22 55 14


    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 apply manually created x-axis labels in a histogram created by hist function in R?

When we generate a histogram in R using hist function, the x-axis labels are automatically generated but we might want to change them to values defined by researchers or by any other authority. Therefore, firstly we need to create the histogram by ignoring the labels and then axis function can be used for new values.
Consider the below vector x and create a histogram of x by ignoring x-axis labels −
set.seed(1999)
x<-rnorm(5000,9,1)
hist(x,xaxt='n')
Now adding new values for x-axis labels −
axis(side=1,at=seq(6,12,1),labels=seq(6,12,1))
Ruby | Hash empty? function

15 Apr, 2021
Hash#empty?() is a Hash class method which checks whether the Hash array has any key-value pair. 
Syntax: Hash.empty?()Parameter: Hash valuesReturn: true – if no key value pair otherwise return false
Example #1 :  
Ruby
# Ruby code for Hash.empty?() method  # declaring Hash valuea = {a:100, b:200}  # declaring Hash valueb = {a:100, c:300, b:200}  # declaring Hash valuec = {a:100}    # empty? Valueputs "Hash a empty? form : #{a.empty?()}\n\n"  puts "Hash b empty? form : #{b.empty?()}\n\n"  puts "Hash c empty? form : #{c.empty?()}\n\n"
Output :  
Hash a empty? form : false

Hash b empty? form : false

Hash c empty? form : false
Example #2 : 
Ruby
# Ruby code for Hash.empty?() method  # declaring Hash valuea = { "a" => 100, "b" => 200 }  # declaring Hash valueb = {}  # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200}  # emoty? Valueputs "Hash a empty? form : #{a.empty?()}\n\n"  puts "Hash b empty? form : #{b.empty?()}\n\n"  puts "Hash c empty? form : #{c.empty?()}\n\n"
Output :
Hash a empty? form : false

Hash b empty? form : true

Hash c empty? form : false
 
hritikbhatnagar2182
Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | String concat Method
Ruby | Array shift() function
Ruby on Rails Introduction
Ruby | Types of Variables
Bitwise right shift operator in Java


Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.
The signed right shift operator '>>' uses the sign bit to fill the trailing positions. For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions.
Assume if a = 60 and b = -60; now in binary format, they will be as follows −
a = 0000 0000 0000 0000 0000 0000 0011 1100
b = 1111 1111 1111 1111 1111 1111 1100 0100
In Java, negative numbers are stored as 2's complement.
Thus a >> 1 = 0000 0000 0000 0000 0000 0000 0001 1110
And b >> 1 = 1111 1111 1111 1111 1111 1111 1110 0010
The unsigned right shift operator '>>>' do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0s.
Thus a >>> 1 = 0000 0000 0000 0000 0000 0000 0001 1110
And b >>>  1 = 0111 1111 1111 1111 1111 1111 1110 0010
Live Demo
public class Tester {
   public static void main(String[] args) {
      int a = 60;          int b = -60;        int c = 0;
      System.out.println("60  = " + Integer.toBinaryString(a));
      System.out.println("-60 = " + Integer.toBinaryString(b));

      //signed shift
      c = a >> 1;              
      System.out.println("60 >> 1  = " + Integer.toBinaryString(c));

      //unsigned shift
      c = a >>> 1;            
      System.out.println("60 >>> 1 = " + Integer.toBinaryString(c) );

      c = b >> 1;              
      System.out.println("-60 >> 1  = " + Integer.toBinaryString(c) );

      c = b >>> 1;            
      System.out.println("-60 >>> 1 = " + Integer.toBinaryString(c));
   }
}
60  = 111100
-60 = 11111111111111111111111111000100
60 >> 1  = 11110
60 >>> 1 = 11110
-60 >> 1  = 11111111111111111111111111100010
-60 >>> 1 = 1111111111111111111111111100010
Java Program To Find Largest Between Three Numbers Using Ternary Operator

02 Nov, 2020
Java offers a lot of Operators and one such operator is the Ternary Operator. It is a linear replacement for an if-else statement. Thus, it is a very useful operator and it uses less space in comparison to an if-else statement.
Ternary Operator Syntax :
variable = condition ? expression1 : expression2 ;

The same statement can be written in if-else statement as follows:
if(condition){
      variable = expression1 ;
}
else{
      variable = expression2 ;
}

Given three numbers we have to find the maximum among them by just using the ternary operator.
Example : 
Input  : a = 15 , b = 10 , c = 45
Output : 45

Input  : a = 31 , b = 67 , c = 23
Output : 67

Thus, we can make use of nested ternary operator to find the maximum of 3 number as shown below :
Java
// Java Program to Find Largest// Between Three Numbers Using// Ternary Operatorclass MaximumNumber {      // Main function    public static void main(String args[])    {        // Variable Declaration        int a = 10, b = 25, c = 15, max;          // Maximum among a, b, c        max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);          // Print the largest number        System.out.println("Maximum number among " + a                           + ", " + b + " and " + c + " is "                           + max);    }}
Maximum number among 10, 25 and 15 is 25
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Python | TextBlob.noun_phrases() method

09 Sep, 2019
With the help of TextBlob.noun_phrases() method, we can get the noun phrases of the sentences by using TextBlob.noun_phrases() method.
Syntax : TextBlob.noun_phrases()Return : Return list of noun values.
Example #1 :In this example we can say that by using TextBlob.noun_phrases() method, we are able to get the list of noun words.
# import TextBlobfrom textblob import TextBlob  gfg = TextBlob("Python is a high-level language.")  # using TextBlob.noun_phrases methodgfg = gfg.noun_phrases  print(gfg)
Output :
[‘python’, ‘high-level language’]
Example #2 :
# import TextBlobfrom textblob import TextBlob  gfg = TextBlob("Sandeep Jain An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways.")  # using TextBlob.noun_phrases methodgfg = gfg.noun_phrases  print(gfg)
Output :
[‘sandeep jain’, ‘iit roorkee’, ‘geeksforgeeks’, ‘efficient ways’]
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
SQL Query to Add Unique key Constraints Using ALTER Command

29 Apr, 2021
Here we will see how to add unique key constraint to a column(s) of a MS SQL Server’s database with the help of a SQL query using ALTER clause.
For the demonstration purpose, we will be creating a demo table in a database called “geeks”.
Creating the Database :
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Using the Database :
Use the below SQL statement to switch the database context to geeks:
USE geeks;
Table Definition :
We have the following demo table in our geeks database.
CREATE TABLE demo(
  ID INT IDENTITY(1,1) PRIMARY KEY, --IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.
                                      --Starts from 1 and increases by 1 with each inserted row.
  NAME VARCHAR(30) NOT NULL,
  PHONE VARCHAR(10) NOT NULL
);
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS demo;
Adding data to the table :
Use the below statement to add data to the demo table:
INSERT INTO demo --no need to mention columns explicitly as we are inserting into all columns and ID gets 
                 --automatically incremented.
VALUES
('Yogesh Vaishnav', '000000001'),
('Ajit Yadav', '000000002'),
('Ashish Yadav', '000000003'),
('Vishal Vishwakarma', '000000004'),
('Suhana Shaikh', '000000005');
To verify the contents of the table use the below statement :
SELECT * FROM demo;
Now let’s add an unique key constraint to column phone as phone no. should be unique.
NOTE: There can be multiple unique key columns but only one primary key column in a database table.
Syntax for adding the unique key constraint to single as well as multiple columns is given below:
Syntax :
–Adding unique key constraint to a column.
ALTER TABLE <table_name>
ADD UNIQUE (<column_name>);
–Adding unique key constraint to multiple columns
ALTER TABLE <table_name>
ADD  CONSTRAINT <identifier_name> UNIQUE (<column_name1>, <column_name2>,...);
Example :
ALTER TABLE demo
ADD UNIQUE (PHONE);

--Let's insert a row into the table.

INSERT INTO demo
VALUES ('GeeksforGeeks','000000001'); --error
As string ‘000000001’ already exist in the phone column which has an unique key constraint now, thus when executing the above query results into an error.
Thus we can say that the unique key constraint has been successfully applied.
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
HTML | Responsive full page image using CSS

08 Feb, 2022
Responsive Web design (RWD), a design strategy developed to cope with the amazing popularity of mobile devices for viewing the Web. Responsive images are an important component of responsive Web design (RWD), Responsive web design is a new approach to website design that ensures users have a good viewing experience no matter what type of device they’re using. Web designer Ethan Marcotte is credited with coining the term “responsive design.” In 2010, he published an article on A List Apart discussing the rapidly changing environment of devices, browsers, screen sizes, and orientations. Building separate sites for every type of device simply wouldn’t be sustainable. Instead, he proposed an alternative concept: responsive design, which calls for building flexible and fluid layouts that adapt to almost any screen.  
There are several frameworks used by developers to make a webpage responsive.  
Bootstrap
Foundation
Pure
Skeleton
Symantec
A responsive Full page background image scales itself according to the user’s viewport. There are several websites that use this effect such as-  
sailingcollective.com
sailingcollective.com
Berlin Real Estate
This full page background image effect can be easily added to a webpage using CSS. Example Implementation Input HTML  
HTML
<!DOCTYPE html><head>    <link rel="stylesheet" href="css/main.css">    <title>Responsive Background Example</title></head><body>    <h1>Hi GFG</h1></body></html>
CSS  
HTML
body {    /* Image Location */    background-image: url("../img/Fall-Nature-Background-Pictures.jpg");     /* Background image is centered vertically and horizontally at all times */    background-position: center center;    background-repeat: no-repeat;    background-attachment: fixed;    background-size: cover;    background-color: #464646;    /* Font Colour */    color:white;}
EXPLANATION background-size: cover; This property tells the browser to scale the background image proportionally so that its width and height are equal to, or greater than, the width/height of the element. background-position: center center; The above sets the scaling axis at the center of the viewport. background-attachment: fixed; The background is fixed with regard to the viewport OUTPUT The output shows the background image in different viewports.  
 
 
 
sagar0719kumar
HTML and XML
HTML-Misc
Web technologies-HTML and XML
HTML
Web Technologies
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
How to set the default value for an HTML <select> element ?
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 ?
What is the best way to read an entire file into a std::string in C++?

This is an simple way to read an entire file into std::string in C++
Begin
   Take the filename as inputstream.
   Declare a string variable str.
   Read the file till the end by using rdbuf().
   Put the data into st.
   Print the data.
End.
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main() {
   ifstream f("a.txt");
   string str;
   if(f) {
      ostringstream ss;
      ss << f.rdbuf();
      str = ss.str();
   }
   cout<<str;
}
a.txt data file contains the string “hi”
hi
Bootstrap Collapsible list group

To create a collapsible list group, use the panel-collapse property with list-group property.
The list-group property lists items using the list-group-item property −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Questions/ Answers</h2>
         <p>Click below to learn about the technologies for which we provide Interview Questions.</p>
         <div class = "panel-group">
            <div class = "panel panel-default">
               <div class = "panel-heading">
                  <h4 class = "panel-title">
                     <a data-toggle = "collapse" href = "#test">Info</a>
                  </h4>
               </div>
               <div id = "test" class="panel-collapse collapse">
                  <ul class = "list-group">
                     <li class = "list-group-item">Java</li>
                     <li class = "list-group-item">PHP</li>
                     <li class = "list-group-item">C++</li>
                     <li class =" list-group-item">HTML5</li>
                     <li class =" list-group-item">jQuery</li>
                  </ul>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
Display Numpy array in Fortran order

01 Oct, 2020
Fortran order/ array is a special case in which all elements of an array are stored in column-major order. Sometimes we need to display array in fortran order, for this numpy has a function known as numpy.nditer(). 
Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order=’K’, casting=’safe’, op_axes=None, itershape=None, buffersize=0)
Example 1:
Python3
# importing Numpy packageimport numpy as np  # creating a Numpy arraynum_array = np.arange(12).reshape(3, 4)  print("Array:")print(num_array)  # Display array in Fortran order# using numpy.nditer()print("\nElements of the array in Fortan array:")for num_array in np.nditer(num_array, order="F"):    print(num_array, end=' ')
Output:
Array:
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]

Elements of the array in Fortan array:
0 4 8 1 5 9 2 6 10 3 7 11

Example 2:
Python3
# importing Numpy package import numpy as np  # creating a Numpy arraynum_array = np.arange(12).reshape(2, 6)      print("Array:")print(num_array)  # Display array in Fortran order # using numpy.nditer() print("\nElements of the array in Fortan array:")for num_array in np.nditer(num_array, order="F"):    print(num_array,end=' ')
Output:
Array:
[[ 0  1  2  3  4  5]
[ 6  7  8  9 10 11]]

Elements of the array in Fortan array:
0 6 1 7 2 8 3 9 4 10 5 11

Example 3:
Python3
# importing Numpy package import numpy as np  # creating a Numpy arraynum_array = np.arange(42).reshape(6, 7)      print("Array:")print(num_array)  # Display array in Fortran order # using numpy.nditer() print("\nElements of the array in Fortan array:")for num_array in np.nditer(num_array, order="F"):    print(num_array,end=' ')
Output:
Array:[[ 0  1  2  3  4  5  6][ 7  8  9 10 11 12 13][14 15 16 17 18 19 20][21 22 23 24 25 26 27][28 29 30 31 32 33 34][35 36 37 38 39 40 41]]
Elements of the array in Fortan array:0 7 14 21 28 35 1 8 15 22 29 36 2 9 16 23 30 37 3 10 17 24 31 38 4 11 18 25 32 39 5 12 19 26 33 40 6 13 20 27 34 41
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
MongoDB – db.collection.Find() Method

17 Feb, 2021
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one. If we want to return pointer on all documents then use empty() parameter that returns all documents one by one. It takes only some optional parameters. The first optional parameter is the selection criteria on which we want to return a cursor. To return all documents in a collection use empty document({}). Using this method you can also replace embedded documents. You can also use this method in multi-document transactions. If you use this method in the mongo shell, then the shell will automatically iterate the cursor to display up to 20 documents in the collection, if you want to continue then type it or you can manually iterate the result of the find() method by assigning the returned cursor to a variable with the var keyword. You can also modify the behavior of this method using cursor methods.
Syntax:
db.Collection_name.find(selection_criteria, projection)
Optional parameters:
selection_criteria: It specifies selection criteria. To return all documents in a collection use empty document({}). The type of this parameter is document.
projection: It specifies the fields to return in the documents that match the selection criteria. To return all fields in the matching documents, remove this parameter. It is of the document type.
This document takes:
{ field1: <value1>, field2: <value2> ... }
Here if the value of the field is 1/true then it specifies the inclusion of the field, or if the value of the field is 0/false then it specifies the exclusion of the field.
Return:
It returns a cursor to the documents that match the selection criteria. When the find() method returns documents, the method is actually returning a cursor to the documents.
Examples:
In the following example, we are working with:
Database: gfg
Collections: student
Document: Three documents contains the details of the students
Find all the documents present in the collection:
db.student.find()
Find all the documents present in the collection by passing empty document:
db.student.find({})
Find all the document that matches the given filter query(i.e., age:18):
db.student.find({age:18})
Find the embedded document that matches the given filter query:
db.student.find({score:{math: 230, science: 234}})
Display only the specified fields(Using Projection):
db.student.find({},{name:1, _id:0})
Display only two documents using the limit() method:
db.student.find().limit(2)
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
Aggregation in MongoDB
Upsert in MongoDB
MongoDB - Check the existence of the fields in the specified collection
How to connect MongoDB with ReactJS ?
How to build a basic CRUD app with Node.js and ReactJS ?
MongoDB - limit() Method
Create user and add role in MongoDB
MongoDB - sort() Method
How to draw rectangle in Pygame?

01 Oct, 2020
Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language.
Functions  Used:
pygame.display.set_mode(): This function is used to initialize a surface for display. This function takes the size of the display as a parameter.
pygame.display.flip(): This function is used to update the content of the entire display surface of the screen.
pygame.draw.rect(): This function is used to draw a rectangle. It takes the surface, color, and pygame Rect object as an input parameter and draws a rectangle on the surface.
Example 1: This example draws a rectangle that is filled with red color.
Python3
# Importing the libraryimport pygame  # Initializing Pygamepygame.init()  # Initializing surfacesurface = pygame.display.set_mode((400,300))  # Initialing Colorcolor = (255,0,0)  # Drawing Rectanglepygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60))pygame.display.flip()
Output:
Example 2: This example draws a rectangle with a red border and no color-filled inside.
Python3
# Importing the libraryimport pygame  # Initializing Pygamepygame.init()  # Initializing surfacesurface = pygame.display.set_mode((400,300))  # Initialing Colorcolor = (255,0,0)  # Drawing Rectanglepygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60),  2)pygame.display.flip()
Output:
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
How to generate XML documents with namespaces in Python?

Currently you cannot add namespaces to XML documents directly as it is not yet supported in the in built Python xml package. So you will need to add namespace as a normal attribute to the tag. For example,
import xml.dom.minidom
doc = xml.dom.minidom.Document()
element = doc.createElementNS('http://hello.world/ns', 'ex:el')
element.setAttribute("xmlns:ex", "http://hello.world/ns")
doc.appendChild(element)
print(doc.toprettyxml())
This will give you the document,
<?xml version="1.0" ?>
<ex:el xmlns:ex="http://example.net/ns"/>
C# program to merge two Dictionaries

Set the two dictionaries −
Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("laptop", 1);
dict1.Add("desktop", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("desktop", 3);
dict2.Add("tablet", 4);
dict2.Add("mobile", 5);
Now use HashSet and UnionWith() method to merge the two dictionaries −
HashSet < string > hSet = new HashSet < string > (dict1.Keys);
hSet.UnionWith(dict2.Keys);
Here is the complete code −
using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      Dictionary < string, int > dict1 = new Dictionary < string, int > ();
      dict1.Add("laptop", 1);
      dict1.Add("desktop", 2);

      Dictionary < string, int > dict2 = new Dictionary < string, int > ();
      dict2.Add("desktop", 3);
      dict2.Add("tablet", 4);
      dict2.Add("mobile", 5);

      HashSet < string > hSet = new HashSet < string > (dict1.Keys);
      hSet.UnionWith(dict2.Keys);
      Console.WriteLine("Merged Dictionary...");

      foreach(string val in hSet) {
         Console.WriteLine(val);
      }
   }
}
How to create a Sandbox in Lua?

In order to create a sandbox and to be able to use it we must first understand what a sandbox is and why we need it. A sandbox is term that is used in different fields of computer science, like in case we are talking about the software testing domain, then a sandbox is a testing environment that isolates untested code changes and outright experimentation from the production environment and if we talk about cybersecurity, then a sandbox is an environment that is an isolated virtual machine in which potentially unsafe software code can execute.
Sandboxing is basically all about isolating a piece of software and that piece of software is isolated with the help of the sandbox. It should be noted that sandboxing is a bit tricky and generally difficult to get right.
Lua provides different approaches to creating a sandbox and also it provides different keywords and functions that we can make use inside of a sandbox.
Now, let’s create a simple sandbox in which we will store the untrusted code.
Consider the example shown below −
 Live Demo
function print_env()
   print(_ENV)
end
function sandbox()
   print(_ENV)
   -- need to keep access to a few globals:
   _ENV = { print = print, print_env = print_env, debug = debug, load = load }
   print(_ENV)
   print_env()
   local code1 = load('print(_ENV)')
   code1()
   debug.setupvalue(code1, 1, _ENV) -- set our modified env code1()
   local code2 = load('print(_ENV)', nil, nil, _ENV) -- pass 'env' arg code2()
end
sandbox()
table: 0x1a409c0
table: 0x1a47790
table: 0x1a47790
table: 0x1a409c0
table: 0x1a47790
table: 0x1a47790
HTML5 - range

The range type is used for input fields that should contain a value from a range of numbers.
<!DOCTYPE HTML>

<html>
   <body>

      <form action = "/cgi-bin/html5.cgi" method = "get">
         Select Range : <input type = "range" min = "0" max = "10" step "1" 
            value = "5" name = "newinput" />
         <input type = "submit" value = "submit" />
      </form>

   </body>
</html>

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How do you create a Button on a tkinter Canvas? - GeeksforGeeks

03 Jan, 2021
In this article, we will see how to create a button on a Tkinter Canvas.
The Canvas widget display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs.
 It is used trigger any function which is presented in the code
Intro to code :
In this we try to create button on canvas widget. Firstly make canvas then place the button on the canvas.
Syntax:
C = Canvas(root, height, width, bd, bg)
Syntax:
button = Button ( root,height,width,bg,command)
Steps :
Import tkinter fromThen define the window size and other requirements.First create canvas from the above give syntax.With the help of place function in tkinter place the button.
Import tkinter from
Then define the window size and other requirements.
First create canvas from the above give syntax.
With the help of place function in tkinter place the button.
Python3
# import everything from tkinter modulefrom tkinter import *  root = Tk()  root.geometry('430x300')  title = Label(root, text="Geeksforgeeks", bg="green", font=("bold", 30))title.pack()c = Canvas(root, width=330, height=200, bg="red")c.place(x=50, y=50)btn = Button(root, text='Welcome to Tkinter!', width=40,             height=5, bd='10', command=root.destroy)  btn.place(x=65, y=100)  root.mainloop()
OUTPUT:
Picked
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
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 unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python