code-rag-bench/online-tutorials huggingface dataset:
SQL NOT NULL Constraint

22 Sep, 2021
In SQL, constraints are some set of rules that are applied to the data type of the specified table. Or we can say that using constraints we can apply limits on the type of data that can be stored in the particular column of the table. Constraints are typically placed specified along with CREATE statement. By default, a column can hold null values.
Example:
If you don’t want to have a null column or a null value you need to define constraints like NOT NULL. NOT NULL constraints make sure that a column does not hold null values, or in other words, NOT NULL constraint make sure that you cannot insert a new record or update a record without entering a value to the specified column(i.e., NOT NULL column). It prevents for acceptance of NULL values. It can be applied for column-level constraints. 
Syntax:
CREATE TABLE table_Name
(
column1 data_type(size) NOT NULL,
column2 data_type(size) NOT NULL,
....
);
In SQL, we can add NOT NULL constraints while creating a table. For example, the “EMPID”, “EName” will not accept NULL values when the EMPLOYEES table is created because NOT NULL constraints are used with these columns.
CREATE TABLE EMPLOYEES(
EMPID INTEGER NOT NULL,
EName VARCHAR2(10) NOT NULL,
DOJ DATE);
We can also add a NOT NULL constraint in the existing table using the ALTER statement. For example, if the EMPLOYEES table has already been created then add NOT NULL constraints to the “DOJ” column use ALTER statements in SQL as follows:
ALTER TABLE EMPLOYEES modify DOJ DATE NOT NULL;
Blogathon-2021
Picked
Blogathon
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check whether a form or a control is touched or not in Angular 10 ?

03 Jun, 2021
In this article, we are going to check whether a form is touched or not in Angular 10. The touched property is used to report that the control or the form is touched or not.
Syntax:
form.touched
Return Value:
boolean: the boolean value to check whether a form is touched or not.
NgModule: Module used by the touched property is:
FormsModule
 
Approach: 
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using the touched property.
Serve the angular app using ng serve to see the output.
Example:
app.component.ts
import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray,         Validators } from '@angular/forms'  @Component({  selector: 'app-root',  templateUrl: './app.component.html'})  export class AppComponent {  form = new FormGroup({    name: new FormControl(    ),    rollno: new FormControl()   });    get name(): any {    return this.form.get('name');  }    onSubmit(): void {    console.log("Form is touched : ",this.form.touched);  }}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()">  <input formControlName="name" placeholder="Name">  <br>      <button type='submit'>Submit</button>  <br><br></form>
Output:
Reference: https://angular.io/api/forms/AbstractControlDirective#touched
AngularJS-Basics
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Program to print duplicates from a list of integers

30 Jun, 2022
Given a list of integers with duplicate elements in it. The task to generate another list, which contains only the duplicate elements. In simple words, the new list should contain the elements which appear more than one.
Examples : 
Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output : output_list = [20, 30, -20, 60]


Input :  list = [-1, 1, -1, 8]
Output : output_list = [-1]
Python3
# Python program to print# duplicates from a list# of integersdef Repeat(x):    _size = len(x)    repeated = []    for i in range(_size):        k = i + 1        for j in range(k, _size):            if x[i] == x[j] and x[i] not in repeated:                repeated.append(x[i])    return repeated # Driver Codelist1 = [10, 20, 30, 20, 20, 30, 40,         50, -20, 60, 60, -20, -20]print (Repeat(list1))     # This code is contributed# by Sandeep_anand
[20, 30, -20, 60]

Python3
from collections import Counter l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]d = Counter(l1)print(d) new_list = list([item for item in d if d[item]>1])print(new_list)
Counter({1: 4, 2: 3, 5: 2, 9: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1})
[1, 2, 5, 9]

Python3
# program to print duplicate numbers in a given list# provided inputlist = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] new = []  # defining output list # condition for reviewing every# element of given input listfor a in list:      # checking the occurrence of elements    n = list.count(a)     # if the occurrence is more than    # one we add it to the output list    if n > 1:         if new.count(a) == 0:  # condition to check             new.append(a) print(new) # This code is contributed by Himanshu Khune
[1, 2, 5, 9]

Python3
def duplicate(input_list):    return list(set([x for x in input_list if input_list.count(x) > 1])) if __name__ == '__main__':    input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]    print(duplicate(input_list)) # This code is contributed by saikot
[1, 2, 5, 9]

Python3
def duplicate(input_list):    new_dict, new_list = {}, []     for i in input_list:        if not i in new_dict:            new_dict[i] = 1        else:            new_dict[i] += 1     for key, values in new_dict.items():        if values > 1:            new_list.append(key)     return new_list if __name__ == '__main__':    input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]    print(duplicate(input_list)) # This code is contributed by saikot
[1, 2, 5, 9]

Python3
lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]x = []y = []for i in lis:    if i not in x:        x.append(i)for i in x:    if lis.count(i) > 1:        y.append(i)print(y)
[1, 2, 5, 9]

sandeep_anand
pragya gupta 1
himanshukhune3
saikot
kogantibhavya
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.to_csv()

24 Jun, 2020
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_csv() function write the given series object to a comma-separated values (csv) file/format.
Syntax: Series.to_csv(*args, **kwargs)
Parameter :path_or_buf : File path or object, if None is provided the result is returned as a string.sep : String of length 1. Field delimiter for the output file.na_rep : Missing data representation.float_format : Format string for floating point numbers.columns : Columns to writeheader : If a list of strings is given it is assumed to be aliases for the column names.index : Write row names (index).index_label : Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used.mode : Python write mode, default ‘w’.encoding : A string representing the encoding to use in the output file.compression : Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}.quoting : Defaults to csv.QUOTE_MINIMAL.quotechar : String of length 1. Character used to quote fields.
Returns : None or str
Example #1: Use Series.to_csv() function to convert the given series object to csv format.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe / Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.to_csv() function to convert the given Series object into a comma separated format.
# convert to comma-separatedsr.to_csv()
Output :
As we can see in the output, the Series.to_csv() function has converted the given Series object into a comma-separated format. Example #2: Use Series.to_csv() function to convert the given series object to csv format.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.to_csv() function to convert the given Series object into a comma separated format.
# convert to comma-separatedsr.to_csv()
Output :
As we can see in the output, the Series.to_csv() function has converted the given Series object into a comma-separated format.
nidhi_biet
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
int keyword in C

15 Jun, 2022
In the C programming language, the keyword ‘int’ is used in a type declaration to give a variable an integer type. However, the fact that the type represents integers does not mean it can represent all integers. The size of an int variable is fixed and determined by the C implementation you use. The C Standard dictates that an int must have a range of at least -32768 to +32767. The C implementation can, and very often do, have a much larger range than this. The range of the int type on a particular C implementation can be obtained via the INT_MAX and INT_MIN variables defined in the header <limits.h>:
C
#include <limits.h>#include <stdio.h> int main(){    printf("minimum int value = %d\n"           "maximum int value = %d\n"           "size of int in bytes = %zu\n"           "size of int in bits = %zu",           INT_MIN, INT_MAX, sizeof(int),           sizeof(int) * CHAR_BIT);}
minimum int value = -2147483648
maximum int value = 2147483647
size of int in bytes = 4
size of int in bits = 32
Do keep in mind though that not all C implementations are the same, and they don’t all have the same ranges for integer types.
SIGNED INTEGER
The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.
Attempting to assign a signed integer type with a value that is outside of its range of representable values (from INT_MIN to INT_MAX) will result in undefined behavior.
Signed integers commonly use two’s complement on all modern machines, and in the upcoming (as of Jan 2022) C23 standard, two’s complement is the only valid way of representing signed integers. You can read more about how signed numbers are represented in binary and why two’s complement is the most common representation in this article.
UNSIGNED INTEGER
In the case of an unsigned integer, only positive numbers can be stored. In this data type, all of the bits in the integer are used to store a positive value, rather than having some reserved for sign information. This means the magnitude of the maximum representable value in an unsigned integer is greater than that of a signed integer with the same number of bits.
In the case of an unsigned int value, the maximum value is specified by the UINT_MAX macro, defined in <limits.h>, and the minimum value is 0. As per the C standard, unsigned arithmetic can never overflow, rather it is performed modulo the maximum value of the unsigned type + 1, so for unsigned int, arithmetic is performed modulo UINT_MAX + 1 such that UINT_MAX + 1 is 0, and UINT_MAX + 2 is 1, and so on:
C
#include <limits.h>#include <stdio.h> int main(){    printf("UINT_MAX + 1 = %u", UINT_MAX + 1);}
UINT_MAX + 1 = 0
tijinabet
tanwarsinghvaibhav
lennymclennington
sagar0719kumar
sumitgumber28
sonaliparkhe9
C Basics
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove array element in MongoDB?

To remove array element in MongoDB, you can use pullandin operator. The syntax is as follows:
db.yourCollectionName.update({},
   {$pull:{yourFirstArrayName:{$in:["yourValue"]},yourSecondArrayName:"yourValue"}},
   {multi:true}
);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
>db.removeArrayElement.insertOne({"StudentName":"Larry","StudentCoreSubject":["MongoD
B","MySQL","SQL Server","Java"],"StudentFavouriteTeacher":["John","Marry","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ec9c46fd07954a4890688")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.removeArrayElement.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ec9c46fd07954a4890688"),
   "StudentName" : "Larry",
   "StudentCoreSubject" : [
      "MongoDB",
      "MySQL",
      "SQL Server",
      "Java"
   ],
   "StudentFavouriteTeacher" : [
      "John",
      "Marry",
      "Carol"
   ]
}
Here is the query to remove array element in MongoDB:
> db.removeArrayElement.update({},
... {$pull:{StudentCoreSubject:{$in:["Java"]},StudentFavouriteTeacher:"Marry"}},
... {multi:true}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
We have “Java” element from first array(“StudentCoreSubject”) above and the second value “Marry” element from second array(“StudentFavouriteTeacher”).
Let us display documents from a collection once again to check the two elements have been removed or not. The query is as follows:
> db.removeArrayElement.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ec9c46fd07954a4890688"),
   "StudentName" : "Larry",
   "StudentCoreSubject" : [
      "MongoDB",
      "MySQL",
      "SQL Server"
   ],
   "StudentFavouriteTeacher" : [
      "John",
      "Carol"
   ]
}
Look at the above sample output, there is no “Java” element in the first array(“StudentCoreSubject”) and no “Marry” element in second array(“StudentFavouriteTeacher”). Therefore, we have successfully removed them from the collection.
TestNG - Run JUnit Tests

Now that you have understood TestNG and its various tests, you must be worried by now as to how to refactor your existing JUnit code. There's no need to worry, as TestNG provides a way to shift from JUnit to TestNG at your own pace. You can execute your existing JUnit test cases using TestNG.
TestNG can automatically recognize and run JUnit tests, so that you can use TestNG as a runner for all your existing tests and write new tests using TestNG. All you have to do is to put JUnit library on the TestNG classpath, so it can find and use JUnit classes, change your test runner from JUnit to TestNG in Ant, and then run TestNG in "mixed" mode. This way, you can have all your tests in the same project, even in the same package, and start using TestNG. This approach also allows you to convert your existing JUnit tests to TestNG incrementally.
Let us have an example to demonstrate this amazing ability of TestNG.
Create a java class, which is a JUnit test class, TestJunit.java in /work/testng/src.
  import org.junit.Test;
  import static org.testng.AssertJUnit.*;

  public class TestJunit {
     @Test
     public void testAdd() {
        String str = "Junit testing using TestNG";
        assertEquals("Junit testing using TestNG",str);
     }
  }
Now, let's write the testng.xml in /work/testng/src, which would contain the <suite> tag as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name = "Converted JUnit suite" >
   <test name = "JUnitTests" junit="true">
      <classes>
         <class name = "TestJunit" />
      </classes>
   </test>
</suite>
To execute the JUnit test cases, define the property junit="true" as in the xml above. The JUnit test case class TestJunit is defined in class name.
For JUnit 4, TestNG will use the org.junit.runner.JUnitCore runner to run your tests.
Compile all java classes using javac.
/work/testng/src$ javac TestJunit.java

Now, run testng.xml, which will run the JUnit test case as TestNG.
/work/testng/src$java -cp "/work/testng/src/junit-4.13.2.jar:/work/testng/src/hamcrest-core-1.3.jar" org.testng.TestNG testng.xml

Here, we have placed the dependent JAR files junit-4.13.2.jar and hamcrest-core-1.3.jar under /work/testng/src/.
Verify the output.
  ===============================================
  Converted JUnit suite
  Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
  ===============================================


    38 Lectures 
     4.5 hours 

 Lets Kode It

    15 Lectures 
     1.5 hours 

 Quaatso Learning

    28 Lectures 
     3 hours 

 Dezlearn Education
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.6 - Show Python

f = open("demofile.txt", "r")
for x in f:
Python Program for Common Divisors of Two Numbers

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given two integers, we need to display the common divisors of two numbers
Here we are computing the minimum of the two numbers we take as input. A loop to
calculate the divisors by computed by dividing each value from 1 to the minimum computed
Each time the condition is evaluated to be true counter is incremented by one.
Now let’s observe the concept in the implementation below−
 Live Demo
a = 5
b = 45
count = 0
for i in range(1, min(a, b)+1):
   if a%i==0 and b%i==0:
      count+=1
print(count)
2
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about the python program to find the common divisors of two numbers.
Google Guice - Constructor Injection

Injection is a process of injecting dependeny into an object. Constructor injection is quite common. In this process, dependency is injected as argument to the constructor. See the example below.
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck(); 
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   }
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
   } 
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}


//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}
Compile and run the file, you will see the following output.
Inside checkSpelling.


    27 Lectures 
     1.5 hours 

 Lemuel Ogbunude
 Print
 Add Notes
 Bookmark this page
Python List insert() Method

Python list method insert() inserts object obj into list at offset index.
Following is the syntax for insert() method −
list.insert(index, obj)

index − This is the Index where the object obj need to be inserted.
index − This is the Index where the object obj need to be inserted.
obj − This is the Object to be inserted into the given list.
obj − This is the Object to be inserted into the given list.
This method does not return any value but it inserts the given element at the given index.
The following example shows the usage of insert() method.
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print "Final List : ", aList
When we run above program, it produces following result −
Final List : [123, 'xyz', 'zara', 2009, 'abc']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to make empty an array using AngularJS ?

14 Oct, 2020
The task is to make empty an array or delete all elements from the array in AngularJS.
Approach: First example uses the [] notation to reinitialize the array which eventually removes all the elements from the array. Second example sets the length of the array to 0 by using length property, which also empty the array.
Example 1:
<!DOCTYPE HTML><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>      <script>        var myApp = angular.module("app", []);        myApp.controller("controller", function ($scope) {            $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg'];            $scope.emptyArr = function () {                $scope.arr = [];              };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to empty an array in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            Array = {{arr}}<br><br>            <button ng-click='emptyArr()'>                Clear Array            </button>        </div>    </div></body>  </html>
Output:
Example 2:
<!DOCTYPE HTML><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>          <script>        var myApp = angular.module("app", []);        myApp.controller("controller", function ($scope) {            $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg'];            $scope.emptyArr = function () {                $scope.arr.length = 0;              };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to empty an array in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            Array = {{arr}}<br><br>            <button ng-click='emptyArr()'>                Clear Array            </button>        </div>    </div></body>  </html>
Output:
AngularJS-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
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)
Hide or show elements in HTML using display property
Yacc Program to evaluate a given arithmetic expression

22 Mar, 2021
Prerequisite – Introduction to YACC Problem: Write a YACC program to evaluate a given arithmetic expression consisting of ‘+’, ‘-‘, ‘*’, ‘/’ including brackets.Examples:  
Input: 7*(5-3)/2
Output: 7

Input: 6/((3-2)*(-5+2))
Output: -2 
Lexical Analyzer Source Code: 
C
%{    /* Definition section*/    #include "y.tab.h"    extern yylval;}% %%[0-9]+    {              yylval = atoi(yytext);              return NUMBER;            } [a-zA-Z]+    { return ID; }[ \t]+         ;  /*For skipping whitespaces*/ \n            { return 0; }.            { return yytext[0]; } %%
Parser Source Code: 
C
%{    /* Definition section */  #include <stdio.h>%} %token NUMBER ID// setting the precedence// and associativity of operators%left '+' '-'%left '*' '/' /* Rule Section */%%E : T        {                printf("Result = %d\n", $$);                return 0;            } T :    T '+' T { $$ = $1 + $3; }    | T '-' T { $$ = $1 - $3; }    | T '*' T { $$ = $1 * $3; }    | T '/' T { $$ = $1 / $3; }    | '-' NUMBER { $$ = -$2; }    | '-' ID { $$ = -$2; }    | '(' T ')' { $$ = $2; }    | NUMBER { $$ = $1; }    | ID { $$ = $1; };% % int main() {    printf("Enter the expression\n");    yyparse();} /* For printing error messages */int yyerror(char* s) {    printf("\nExpression is invalid\n");}
Output: 
Notes: Yacc programs are generally written in 2 files one for lex with .l extension(for tokenization and send the tokens to yacc) and another for yacc with .y extension (for grammar evaluation and result evaluation).Steps for execution of Yacc program:  
yacc -d sample_yacc_program.y
lex sample_lex_program.l
cc lex.yy.c y.tab.c -ll
./a.out
 
aaaayush25
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to import an excel file into Python using Pandas?

17 Aug, 2020
It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a ‘.xlsx’ format. 
Before we get started,  we need to install a few libraries. 
pip install pandas
pip install xlrd

 For importing an Excel file into Python using Pandas we have to use pandas.read_excel() function.
Syntax: pandas.read_excel(io, sheet_name=0, header=0, names=None,....)
Return: DataFrame or dict of DataFrames.
Let’s suppose the Excel file looks like this:
Now, we can dive into the code. 
Example 1: Read an Excel file.
Python3
import pandas as pd  df = pd.read_excel("sample.xlsx")print(df)
Output:
Example 2: To select a particular column, we can pass a parameter “index_col“. 
Python3
import pandas as pd  # Here 0th column will be extracteddf = pd.read_excel("sample.xlsx",                   index_col = 0)    print(df)
Output:
Example 3: In case you don’t prefer the initial heading of the columns, you can change it to indexes using the parameter “header”.
Python3
import pandas as pd  df = pd.read_excel('sample.xlsx',                   header = None)print(df)
Output:
Example 4: If you want to change the data type of a particular column you can do it using the parameter “dtype“.
Python3
import pandas as pd  df = pd.read_excel('sample.xlsx',                    dtype = {"Products": str,                            "Price":float})print(df)
Output:
Example 5: In case you have unknown values, then you can handle it using the parameter “na_values“. It will convert the mentioned unknown values into “NaN” 
Python3
import pandas as pddf = pd.read_excel('sample.xlsx',                    na_values =['item1',                                'item2'])print(df)
Output:
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between List and Array in Python

17 Jul, 2020
List: A list in Python is a collection of items which can contain elements of multiple data types, which may be either numeric, character logical values, etc. It is an ordered collection supporting negative indexing. A list can be created using [] containing data values.Contents of lists can be easily merged and copied using python’s inbuilt functions.
# creating a list containing elements # belonging to different data typessample_list = [1,"Yash",['a','e']]print(sample_list)
Output :
[1, 'Yash', ['a', 'e']]

The first element is an integer, the second a string and the third is an list of characters.
Array: An array is a vector containing homogeneous elements i.e. belonging to the same data type. Elements are allocated with contiguous memory locations allowing easy modification, that is, addition, deletion, accessing of elements. In Python, we have to use the array module to declare arrays. If the elements of an array belong to different data types, an exception “Incompatible data types” is thrown.
# creating an array containing same # data type elements import array  sample_array = array.array('i', [1, 2, 3])    # accessing elements of arrayfor i in sample_array:     print(i)
Output :
1
2
3

Here are the differences between List and Array in Python :
Python-array
python-list
Difference Between
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Java program to check occurrence of each character in String

In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.Now when a character repeats during insertion as key in Map increase its value by one.Continue this for each character untill all characters of string get inserted.
public class occurenceOfCharacter {
   public static void main(String[] args) {
      String str = "SSDRRRTTYYTYTR";
      HashMap <Character, Integer> hMap = new HashMap<>();
      for (int i = str.length() - 1; i > = 0; i--) {
         if (hMap.containsKey(str.charAt(i))) {
            int count = hMap.get(str.charAt(i));
            hMap.put(str.charAt(i), ++count);
         } else {
            hMap.put(str.charAt(i),1);
         }
      }
      System.out.println(hMap);
   }
}
{D=1, T=4, S=2, R=4, Y=3}
Python – tensorflow.fingerprint()

10 Jul, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 
fingerprint() is used to generate fingerprint value.
Syntax: tensorflow.fingerprint( data, method, name)
Parameters:
data: It is a Tensor having rank 1 or higher.
method: It defines the algorithm to be used to generate fingerprint.
name(optional): It defines the name for the operation.
Return: It returns a 2-D Tensor of dtype unit32.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputdata = tf.constant([1, 2, 3, 4])method = 'farmhash64'  # Printing the inputprint('data: ', data)print('method: ', method)  # Calculating resultres = tf.fingerprint(data, method)  # Printing the resultprint('res: ', res)
Output:
data:  tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)
method:  farmhash64
res:  tf.Tensor(
[[ 84  24  96  84 195  82 124 105]
 [ 15 219 106 105  88 163  17  93]
 [ 92   8   0 238 168 146  54  37]
 [178 113  27   7 149 125 165 247]], shape=(4, 8), dtype=uint8)


Example 2:
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputdata = tf.constant([[1, 2], [ 3, 4]])method = 'farmhash64'  # Printing the inputprint('data: ', data)print('method: ', method)  # Calculating resultres = tf.fingerprint(data, method)  # Printing the resultprint('res: ', res)
Output:
data:  tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)
method:  farmhash64
res:  tf.Tensor(
[[ 76  18 253 133 168 204 240  10]
 [254 162  60 240 103 244  53 255]], shape=(2, 8), dtype=uint8)



Python-Tensorflow
Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to compute cross-correlation of two given NumPy arrays?

08 Dec, 2020
In the Numpy program, we can compute cross-correlation of two given arrays with the help of correlate(). In this first parameter and second parameter pass the given arrays it will return the cross-correlation of two given arrays.
Syntax : numpy.correlate(a, v, mode = ‘valid’)
Parameters :a, v : [array_like] Input sequences.mode : [{‘valid’, ‘same’, ‘full’}, optional] Refer to the convolve docstring. Default is ‘valid’.
Return : [ndarray] Discrete cross-correlation of a and v.
Example 1:
In this example, we will create two NumPy arrays and the task is to compute cross-correlation using correlate().
Python3
import numpy as nparray1 = np.array([0, 1, 2])array2 = np.array([3, 4, 5])  # Original array1print(array1)  # Original array2print(array2)  # ross-correlation of the arraysprint("\nCross-correlation:\n",      np.correlate(array1, array2))
Output:
[0 1 2]
[3 4 5]

Cross-correlation:
 [14]
Example 2:
Python3
import numpy as nparray1 = np.array([1,2])array2 = np.array([1,2])  # Original array1print(array1)  # Original array2print(array2)# Cross-correlation of the arraysprint("\nCross-correlation:\n",      np.correlate(array1, array2))
Output:
[1 2]
[1 2]

Cross-correlation:
 [5]
Python numpy-Matrix Function
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
PyQt5 – Changing background color of Label when hover

30 May, 2022
In this article we will see how to change the background color of the label when cursor will hover over it. When cursor will come upon the label it will change color to it and when cursor is not over the label, it goes back to it default color. In order to do this we have to change the style sheet code which is used with the label object, and have to set background color when mouse hover over it, below is the style sheet code.
QLabel::hover
{
background-color : lightgreen;
}
Below is the implementation. 
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 600, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for widgets    def UiComponents(self):         # creating label        label = QLabel("Hello Geeks", self)         # setting geometry of the label        label.setGeometry(200, 150, 100, 40)         # setting background color to label when mouse hover over it        label.setStyleSheet("QLabel::hover"                            "{"                            "background-color : lightgreen;"                            "}") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
vinayedula
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Can we update MySQL with if condition?

You can update MySQL with IF condition as well as CASE statement. For this purpose, let us first create a table. The query to create a table −
mysql> create table UpdateWithIfCondition
   −> (
   −> BookId int,
   −> BookName varchar(200)
   −> );
Query OK, 0 rows affected (0.60 sec)
Now you can insert records in the table using insert command. The query is as follows −
mysql> insert into UpdateWithIfCondition values(1000,'C in Depth');
Query OK, 1 row affected (0.12 sec)

mysql> insert into UpdateWithIfCondition values(1001,'Introduction to Java');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from UpdateWithIfCondition;
The following is the output −
+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | C in Depth           |
| 1001   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)
Let us update the value ‘C in Depth’ with the value 'Introduction to C' and 1001 with the value 2000 using if condition. The query is as follows −
mysql> update UpdateWithIfCondition
   −> set BookName = if(BookName = 'C in Depth','Introduction to C',BookName),
   −> BookId = if(BookId = 1001,2000,BookId);
Query OK, 2 rows affected (0.43 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Above, we have updated both the column values. The following is the query to check both the two values have been updated or not −
mysql> select *from UpdateWithIfCondition;
The following is the output displaying that we have successfully updated the values using if −
+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | Introduction to C    |
| 2000   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)
How to get items from an object array in MongoDB?

To get items from an object array, use aggregate(). Let us create a collection with documents −
> db.demo459.insertOne(
... { "_id" : 1,
... "Information" : [
...    {
...       "Name" : "Chris",
...       "_id" : new ObjectId(),
...       "details" : [
...          "HR"
...       ]
...    },
... {
...
...    "Name" : "David",
...    "_id" : new ObjectId(),
...    "details" : [
...       "Developer"
...    ]
... },
... {
...
...    "Name" : "Bob",
...    "_id" : new ObjectId(),
...    "details" : [
...       "Account"
...    ]
... }
... ]
... }
... )
{ "acknowledged" : true, "insertedId" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo459.find();
This will produce the following output −
{ "_id" : 1, "Information" : [ { "Name" : "Chris", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95c9"),
"details" : [ "HR" ] }, { "Name" : "David", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95ca"),
"details" : [ "Developer" ] }, { "Name" : "Bob", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95cb"),
"details" : [ "Account" ] } ] }
Following is the query to get items from an object array in MongoDB −
> db.demo459.aggregate([
...    { $unwind: '$Information' },
...    { $unwind: '$Information.details' },
...    { $match: { 'Information.Name': { $in: ["Chris","Bob"]} } },
...    { $group: { _id: null, detailList: { $addToSet: '$Information.details' } } },
... ])
This will produce the following output −
{ "_id" : null, "detailList" : [ "Account", "HR" ] }
Get Day from date in Pandas - Python - GeeksforGeeks

10 Jul, 2020
Let’s discuss how to get the day from the date in Pandas. There can be various ways for doing the same. Let’s go through them with the help of examples for better understanding.
Example 1 : Pandas.dt_range takes input as a range of dates and returns a fixed frequency DatetimeIndex. Series.dt.dayofweek returns the day of the week ranging from 0 to 6 where 0 denotes Monday and 6 denotes Sunday.
import pandas as pd    date = pd.date_range('2018-12-30', '2019-01-07',                     freq='D').to_series()date.dt.dayofweek
Output :
Example 2 : Pandas.DataFrame acts as a dict type container for series objects. pandas.to_datetime converts the input to datetime.
import pandas as pd    date = pd.DataFrame({'inputDate':['2020-07-07']})date['inputDate'] = pd.to_datetime(date['inputDate'])date['dayOfWeek'] = date['inputDate'].dt.day_name()  date
Output :
Example 3 : For more than one input date.
import pandas as pd    date = pd.DataFrame({'inputDates':['2015-01-07', '2015-12-02',                                   '2005-01-03', '2016-11-13',                                   '2020-06-03'],                      'inputVals':[1, 2, 3, 4, 5]})  date['inputDates'] = pd.to_datetime(date['inputDates'])date['dayOfWeek'] = date['inputDates'].dt.day_name()  date
Output :
Example 4 : In order to print the days in a particular format.
import pandas as pd    date = pd.DataFrame({'inputDates':['1999-7-14', '1998-12-14',                                    '2001-01-18', '2020-07-18',                                   '2006-01-8'],                      'inputVals':[1, 2, 3, 4, 5]})  date['inputDates'] = pd.to_datetime(date['inputDates'])date['dayOfWeek'] = date['inputDates'].dt.dayofweekdays = {0:'Mon', 1:'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}date['dayOfWeek'] = date['dayOfWeek'].apply(lambda x: days[x])  date
Output :
Example 5 : Take input as a range of dates and print their names along with the numbers given(0-6).
import pandas as pd    myDate = pd.DataFrame({'inputDates':list(pd.date_range('2018-12-30',                                                       '2019-01-07',                                                        freq ='D').to_series())})  myDate['inputDates'] = pd.to_datetime(myDate['inputDates'])myDate['dayOfWeek'] = myDate['inputDates'].dt.dayofweekmyDate['dayOfWeek'] = myDate['inputDates'].dt.day_name()  myDate
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
PyQt5 QCalendarWidget - Setting Focus Policy - GeeksforGeeks

09 Feb, 2022
In this article we will see how we can set the focus policy to the QCalendarWidget. This property holds the way the widget accepts keyboard focus, there are many focus policy available for calendar like no focus, strong focus, wheel focus etc.
In order to do this we will use setFocusPolicy method with the QCalendarWidget object.
Syntax : calendar.setFocusPolicy(Qt.NoFocus)
Argument : It takes focus policy as argument
Return : It return None
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 650, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating a QCalendarWidget object        self.calender = QCalendarWidget(self)          # setting geometry to the calendar        self.calender.setGeometry(50, 10, 400, 250)          # setting cursor        self.calender.setCursor(Qt.PointingHandCursor)          # setting focus policy to calendar        # as no focus is set keyboard input will not work        self.calender.setFocusPolicy(Qt.NoFocus)      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
sweetyty
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Java Examples - Create a Socket

How to create a socket at a specific port ?
Following example shows how to sing Socket constructor of Socket class.And also get Socket details using getLocalPort() getLocalAddress , getInetAddress() & getPort() methods.
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Main {
   public static void main(String[] args) {
      try {
         InetAddress addr = InetAddress.getByName("74.125.67.100");
         Socket theSocket = new Socket(addr, 80);
         System.out.println("Connected to " 
            + theSocket.getInetAddress()
            + " on port " + theSocket.getPort() + " from port "
            + theSocket.getLocalPort() + " of " 
            + theSocket.getLocalAddress());
      } catch (UnknownHostException e) {
         System.err.println("I can't find " + e  );
      } catch (SocketException e) {
         System.err.println("Could not connect to " +e );
      } catch (IOException e) {
         System.err.println(e);
      }
   }
}
The above code sample will produce the following result.
Connected to /74.125.67.100 on port 80 from port 
2857 of /192.168.1.4

 Print
 Add Notes
 Bookmark this page
Setting up a JDBC connection to remote SAP HANA system

You are using the correct Port number for instance number “00”. Port number 300315, here 00 represents instance number of your HANA system.
Try using HANA client jar file ngdbc.jar instead of SAP Jar file.
try {
   Class.forName("com.sap.db.jdbc.Driver");
   String url ="jdbc:sap://xx.x.x.xxx:30015/DBNAME"; //IP Address of HANAsystem followed by Port number
   String user ="user";
   String password = "password";
   Connection cn = java.sql.DriverManager.getConnection(url, user, password);
   ResultSet rs = cn.createStatement().executeQuery("CALL Test.STORED_PROC");
   // ...Enter the action here
} catch(Exception e) {
   e.printStackTrace();
}
Python program to convert any base to decimal by using int() method - GeeksforGeeks

13 Jul, 2020
Given a number and its base, the task is to convert the given number into its corresponding decimal number. The base of number can be anything like digits between 0 to 9 and A to Z. Where the value of A is 10, value of B is 11, value of C is 12 and so on. 
Examples:  
Input : '1011' 
base = 2 
Output : 11 

Input : '1A' 
base = 16
Output : 26

Input : '12345' 
base = 8
Output : 5349

Approach –
Given number in string form and base 
Now call the builtin function int(‘number’, base) by passing the two parameters any base number in String form and base of that number and store the value in temp 
Print the value temp 
Python3
# Python program to convert any base# number to its corresponding decimal# number  # Function to convert any base number# to its corresponding decimal numberdef any_base_to_decimal(number, base):          # calling the builtin function     # int(number, base) by passing     # two arguments in it number in    # string form and base and store    # the output value in temp    temp = int(number, base)          # printing the corresponding decimal    # number    print(temp)  # Driver's Codeif __name__ == '__main__' :    hexadecimal_number = '1A'    base = 16    any_base_to_decimal(hexadecimal_number, base)
Output:
26
Akanksha_Rai
Python function-programs
Python-Built-in-functions
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary