code-rag-bench/online-tutorials huggingface dataset:
Dictionary.ContainsKey() Method in C#

The Dictionary.ContainsKey() method in C# checks whether the Dictionary<TKey, TValue< has the specified key or not.
public bool ContainsKey (TKey key);
Above, the parameter key is the key to be found.
Let us now see an example to implement the Dictionary.ContainsKey() method −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      if (dict.ContainsKey("Three"))
         Console.WriteLine("Key found!");
      else
         Console.WriteLine("Key isn't in the dictionary!");
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Key found!
Cleared Key/value pairs...
Count of elements now = 0
Let us now see another example to implement the Dictionary. ContainsKey property −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      if (dict.ContainsKey("mykey"))
         Console.WriteLine("Key found!");
      else
         Console.WriteLine("Key isn't in the dictionary!");
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Key isn't in the dictionary!
Cleared Key/value pairs...
Count of elements now = 0
numpy.char.add()

This function performs elementwise string concatenation.
import numpy as np 
print 'Concatenate two strings:' 
print np.char.add(['hello'],[' xyz']) 
print '\n'

print 'Concatenation example:' 
print np.char.add(['hello', 'hi'],[' abc', ' xyz'])
Its output would be as follows −
Concatenate two strings:
['hello xyz']

Concatenation example:
['hello abc' 'hi xyz']


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to convert Java Array/Collection to JSON array?

Google provides a library named org.json.JSONArray and, following is the maven dependency to add library to your project.
<dependency>
   <groupId>com.googlecode.json-simple</groupId>
   <artifactId>json-simple</artifactId>
   <version>1.1</version>
</dependency>
The JSONArray class of the org.json package provides put() method. Using this method, you can populate the JSONArray object with the contents of the elements.
import org.json.JSONArray;
public class ArrayToJson {
   public static void main(String args[]) {
      String [] myArray = {"JavaFX", "HBase", "JOGL", "WebGL"};
      JSONArray jsArray = new JSONArray();
      for (int i = 0; i < myArray.length; i++) {
         jsArray.put(myArray[i]);
      }
      System.out.println(jsArray);
   }
}
["JavaFX","HBase","JOGL","WebGL"]

In the same way you can pass a collection object to the constructor of the JSONArray class.
import java.util.ArrayList;
import org.json.JSONArray;
public class ArrayToJson {
   public static void main(String args[]) {
      ArrayList <String> arrayList = new ArrayList<String>();
      arrayList.add("JavaFX");
      arrayList.add("HBase");
      arrayList.add("JOGL");
      arrayList.add("WebGL");
      JSONArray jsArray2 = new JSONArray(arrayList);
      System.out.println(jsArray2);
   }
}
["JavaFX","HBase","JOGL","WebGL"]
What does the KEY keyword mean in MySQL?

Key is synonymous to an index. If you want to create an index for a column, then use ‘Key’.
As stated in the official docs:
KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.
The key can be used with Primary Key:

Let us first create a table. Here is the query to set primary key for a column “id”.
mysql> create table KeyDemo
    -> (
    -> id int,
    -> primary key(id)
    -> );
Query OK, 0 rows affected (0.55 sec)
Inserting two records.
mysql> insert into KeyDemo values(1);
Query OK, 1 row affected (0.12 sec)

mysql> insert into KeyDemo values(2);
Query OK, 1 row affected (0.14 sec)
To display all the records.
mysql> select *from KeyDemo;
Here is the output.
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.00 sec)
Python | Pandas Series.fillna()

13 Feb, 2019
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.fillna() function is used to fill NA/NaN values using the specified method.
Syntax: Series.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)
Parameter :value : Value to use to fill holesmethod : Method to use for filling holes in reindexed Series pad / ffillaxis : {0 or ‘index’}inplace : If True, fill in place.limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward filldowncast : dict, default is None
Returns : filled : Series
Example #1: Use Series.fillna() function to fill out the missing values in the given series object. Use a dictionary to pass the values to be filled corresponding to the different index labels in the series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio'])  # Create the Indexsr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.fillna() function to fill out the missing values in the given series object.
# fill the values using dictionaryresult = sr.fillna(value = {'City 4' : 'Lisbon', 'City 1' : 'Dublin'})  # Print the resultprint(result)
Output :
As we can see in the output, the Series.fillna() function has successfully filled out the missing values in the given series object. Example #2 : Use Series.fillna() function to fill out the missing values in the given series object using forward fill (ffill) method.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :Now we will use Series.fillna() function to fill out the missing values in the given series object. We will use forward fill method to fill out the missing values.
# fill the values using forward fill methodresult = sr.fillna(method = 'ffill')  # Print the resultprint(result)
Output :
As we can see in the output, the Series.fillna() function has successfully filled out the missing values in the given series object.
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.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
HTML | input readonly Attribute

16 Apr, 2019
The readonly attribute of <input> element in HTML is used to specify that the input field is read-only. If an input is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute.
Syntax:
<input readonly>
Example: This example uses HTML <input> readonly Attribute.
<!DOCTYPE html> <html>   <head>     <title>HTML Input readonly Attribute</title> </head>   <body style = "text-align:center">         <h1 style = "color: green;">        GeeksforGeeks    </h1>               <h2>        HTML Input readonly Attribute    </h2>       <label>Input:               <!--A readonly input-->        <input type="text" name="value" value =             "This input field is readonly" readonly>     </label> </body>   </html>                    
Output:
Supported Browsers: The browser supported by <input> readonly attribute are listed below:
Apple Safari 1.0
Google Chrome 1.0
Firefox 1.0
Opera 1.0
Internet Explorer 6.0
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the importance of SwingUtilities class in Java?

In Java, after swing components displayed on the screen, they can be operated by only one thread called Event Handling Thread. We can write our code in a separate block and can give this block reference to Event Handling thread. The SwingUtilities class has two important static methods, invokeAndWait() and invokeLater() to use to put references to blocks of code onto the event queue.
public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException
public static void invokeLater(Runnable doRun)
The parameter doRun is a reference to an instance of Runnable interface. In this case, the Runnable interface will not be passed to the constructor of a Thread. The Runnable interface is simply being used as a means to identify the entry point for the event thread. Just as a newly spawned thread will invoke run(), the event thread will invoke run() method when it has processed all the other events pending in the queue. An InterruptedException is thrown if the thread that called invokeAndWait() or invokeLater() is interrupted before the block of code referred to by target completes. An InvocationTargetException is thrown if an uncaught exception is thrown by the code inside the run() method.
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
public class SwingUtilitiesTest {
   public static void main(String[] args) {
      final JButton button = new JButton("Not Changed");
      JPanel panel = new JPanel();
      panel.add(button);
      JFrame f = new JFrame("InvokeAndWaitMain");
      f.setContentPane(panel);
      f.setSize(300, 100);
      f.setVisible(true);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      System.out.println(Thread.currentThread().getName()+" is going into sleep for 3 seconds");
      try {
         Thread.sleep(3000);
      } catch(Exception e){ }
      //Preparing code for label change
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println(Thread.currentThread().getName()+"is going into sleep for 10 seconds");
            try {
               Thread.sleep(10000);
            } catch(Exception e){ }
          button.setText("Button Text Changed by "+ Thread.currentThread().getName());
          System.out.println("Button changes ended");
      }
    };
      System.out.println("Component changes put on the event thread by main thread");
          try {
            SwingUtilities.invokeAndWait(r);
         } catch (InvocationTargetException | InterruptedException e) {
            e.printStackTrace();
         }
      System.out.println("Main thread reached end");
   }
}
jQuery load() with Examples

The load() method in jQuery is used to load data from a server and puts the returned data into the selected element
The syntax is as follows −
$(selector).load(url,data,function(response,status,xhr))
Above, URL is the URL to be loaded. The data parameter is the data to send to the server, whereas the callback function runs when the load() completes.
Let us now see an example to implement the jQuery load() method −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("button").click(function(){
         $("div").load("new.txt");
      });
   });
</script>
</head>
<body>
<div>
<p>Demo text...</p>
</div>
<button>Load Content from server</button>
</body>
</html>
This will produce the following output −
Click the above button to load content from “new.txt” −
The content visible above is the new.txt file.
__file__ (A Special variable) in Python - GeeksforGeeks

08 Aug, 2021
A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a “Special way”. This Special way depends on the variable that is being used. 
Note: For more information, refer to Dunder or magic methods in Python 
__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system. The import system can choose to leave the variable empty when there is no semantic meaning, that is when the module/file is imported from the database. This attribute is a String. This can be used to know the path of the module you are using. To understand the usage of __file__ consider the following example. 
Example: Let’s create a module named HelloWorld and store it as a .py file. 
python
# Creating a module named# HelloWorld def hello():    print("This is imported from HelloWorld")     # This code is improved by gherson283
Now let’s create another file named GFG.py that imports the above-created module to show the use of __file__ variable. 
python
# Importing the above# created moduleimport HelloWorld  # Calling the method# created inside the moduleHelloWorld.hello() # printing the __file__# variableprint(HelloWorld.__file__)
Output: 
 
gherson283
python-utility
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()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Program to calculate area of Circumcircle of an Equilateral Triangle

A circumcircle is a circle that inscribes a regular polygon inside it. The triangle that is inscribed inside a circle is an equilateral triangle. Area of circumcircle of can be found using the following formula,
Area of circumcircle = “(a * a * (丌 / 3))”
Code Logic, The area of circumcircle of an equilateral triangle is found using the mathematical formula (a*a*(丌/3)). The value of 丌 in this code is coded as 3.14. The expression is evaluated into a float value.
 Live Demo
#include <stdio.h>
#include <math.h>
int main(){
   int a = 5;
   float area;
   float pie = 3.14;
   printf("Program to calculate area of Circumcircle of an Equilateral Triangle\n");
   printf("The side of the triangle is %d \n", a);
   area = ((pie/3)*a*a);
   printf("The area of of Circumcircle of an Equilateral Triangle is %f \n", area);
   return 0;
}
Program to calculate area of Circumcircle of an Equilateral Triangle
The side of the triangle is 5
The area of circle inscribed inside a square is 19.625000
How to echo print statements while executing an SQL script?

To perform echo print statements while executing SQL scripts, use the following syntax.
The syntax is as follows −
SELECT ‘anyStringValue as’ ‘;
The query is as follows −
mysql> select 'This is a SQL Script' AS' ';
The following is the output −
+----------------------+
|                      |
+----------------------+
| This is a SQL Script |
+----------------------+
1 row in set, 1 warning (0.00 sec)
You can add dynamic data to your status like insert, update and delete with the help of concat() function. The query is as follows −
mysql> select concat ("Inserted ", row_count(), " rows successfully") AS '';
The following is the output −
+-------------------------------+
|                               |
+-------------------------------+
| Inserted -1 rows successfully |
+-------------------------------+
1 row in set (0.00 sec)
React Native - Text Input

In this chapter, we will show you how to work with TextInput elements in React Native.
The Home component will import and render inputs.
import React from 'react';
import Inputs from './inputs.js'

const App = () => {
   return (
      <Inputs />
   )
}
export default App
We will define the initial state.
After defining the initial state, we will create the handleEmail and the handlePassword functions. These functions are used for updating state.
The login() function will just alert the current value of the state.
We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder.
import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'

class Inputs extends Component {
   state = {
      email: '',
      password: ''
   }
   handleEmail = (text) => {
      this.setState({ email: text })
   }
   handlePassword = (text) => {
      this.setState({ password: text })
   }
   login = (email, pass) => {
      alert('email: ' + email + ' password: ' + pass)
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Email"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleEmail}/>
            
            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Password"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handlePassword}/>
            
            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.login(this.state.email, this.state.password)
               }>
               <Text style = {styles.submitButtonText}> Submit </Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   }
})
Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box.
Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Predicate.not() Method in Java with Examples - GeeksforGeeks

05 Feb, 2021
In order to negate an existing predicate, the Predicate.not() static method added to Java 11. The Predicate class is present in java.util.function package.
Syntax:
negate = Predicate.not( positivePredicate );
Parameters:
Predicate whose negate is required
Return Type: Return type not() method is Predicate.
Approach:
Create one predicate and initialize the conditions to it.Create another predicate to create negate and assign it with the not() method.
Create one predicate and initialize the conditions to it.
Create another predicate to create negate and assign it with the not() method.
Below is the implementation of the above approach:
Java
// Implementation of Predicate.not() method in Javaimport java.util.Arrays;import java.util.List;import java.util.function.Predicate;import java.util.stream.Collectors;  public class GFG {    public static void main(String[] args)    {        List<Integer> list            = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);          // creating a predicate for negation        Predicate<Integer> even = i -> i % 2 == 0;          // creating a predicate object which        // is negation os supplied predicate        Predicate<Integer> odd = Predicate.not(even);          // filtering the even number using even predicate        List<Integer> evenNumbers            = list.stream().filter(even).collect(                Collectors.toList());          // filtering the odd number using odd predicate        List<Integer> oddNumbers            = list.stream().filter(odd).collect(                Collectors.toList());        // Print the Lists        System.out.println(evenNumbers);        System.out.println(oddNumbers);    }}
Output:
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
What is the correct way of using <br>, <br/>, or <br /> in HTML?

In HTML, the <br> tag is used for line break. It is an empty tag i.e. no need to add an end tag. Writing <br> tag is perfectly fine.
Let’s see the usage of other br tags i.e. <br/> or <br />,
In HTML, use <br> tag.
In XHTML, the valid way is to use <br/> or <br></br> as mentioned in the XHTML guidelines.
According to w3 guidelines, a space should be included before the trailing / and > of empty elements, for example, <br />. These guidelines are for XHTML documents to render on existing HTML user agents.
You can try to run the following code to learn the perfect usage of <br> tag
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML br Tag</title>
   </head>
   <body>
      <p>This is before the line break<br>
         and this after the line break.
      </p>
   </body>
</html>
What is the difference between checked and unchecked exceptions in Java?

A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.
If you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {
   public static void main(String args[]) {
      File file = new File("E://file.txt");
      FileReader fr = new FileReader(file);
   }
}
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
    FileReader fr = new FileReader(file);
                    ^
1 error
1 quick tip for pulling data from a Pandas dataframe using SQL queries | by George Seif | Towards Data Science

Want to be inspired? Come join my Super Quotes newsletter. 😎
The Pandas library is awesome for anyone that uses Python to analyse their data.
It’s very easy to use, quite fast when applied properly, and flexible in its capabilities. With Pandas, a lot of the functions that would have normally required more work, for example retrieving some basic statistics about your data, are just a single function call away!
Still, sometimes we’re more comfortable with one tool over another. If you’re used to looking through your data on Excel, Tableau, or SQL, then switching to Pandas is still a bit of a jump.
There’s a great Python library for helping smooth over that transition if you’re coming from a background of SQL: Pandasql.
Pandasql allows you to write SQL queries for querying your data from a pandas dataframe. This allows you to get around the normal requirement of having to learn a lot of Python in Pandas. Instead, you can simply write your regular SQL query within a function call and run it on a Pandas dataframe to retrieve your data!
We can install the Pandasql with a quick pip:
pip install pandasql
Let’s start working with an actual dataset. We’ll load in the iris flowers dataset using the seaborn library:
import pandasqlimport seaborn as snsdata = sns.load_dataset('iris')
Normally, if we wanted to retrieve the first 20 items in our dataframe, we’d do something like this with pandas:
data.head(20)
With pandasql we can write out our standard SQL query in the exact same way we normally do when running it on an SQL database. Just pass the name of the pandas dataframe as the name of the table you are parsing and the data will be retrieved:
sub_data = pandasql.sqldf("SELECT * FROM data LIMIT 20;", globals())print(sub_data)
The regular filtering operations that we can do with WHERE in SQL are also applicable. Let’s pull all the data where petal_length is greater than 5 using pandas first:
sub_data = data[data["petal_length"] > 5.0]
To do it in SQL, wecertain rows simply add our WHERE call to do the same filtering:
sub_data = pandasql.sqldf("SELECT * FROM data WHERE petal_length > 5.0;", globals())
We can of course, always select only the columns we want as well:
sub_data = pandasql.sqldf("SELECT petal_width, petal_length FROM data WHERE petal_length > 5.0;", globals())
And that’s how you can use SQL queries to retrieve data from a pandas dataframe.
Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
MongoDB query for exact match on multiple document fields

For exact match, set the values to be matched inside MongoDB $in(). Let us first create a collection with documents −
> db.demo422.insertOne({"Name":"Chris","Marks":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4059822da45b30346e1")
}
> db.demo422.insertOne({"Name":"Chris","Marks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a40a9822da45b30346e2")
}
> db.demo422.insertOne({"Name":"David","Marks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4149822da45b30346e3")
}
> db.demo422.insertOne({"Name":"Sam","Marks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a41e9822da45b30346e4")
}
> db.demo422.insertOne({"Name":"David","Marks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a4239822da45b30346e5")
}
Display all documents from a collection with the help of find() method −
> db.demo422.find();
This will produce the following output −
{ "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 }
{ "_id" : ObjectId("5e73a40a9822da45b30346e2"), "Name" : "Chris", "Marks" : 56 }
{ "_id" : ObjectId("5e73a4149822da45b30346e3"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e73a41e9822da45b30346e4"), "Name" : "Sam", "Marks" : 45 }
{ "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }
Following is the query to get records with exact match on multiple document fields −
> db.demo422.find({'$and': [{'Name': {'$in': ['Chris', 'David']}, 'Marks': {'$in': [34,89]}}]});
This will produce the following output −
{ "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 }
{ "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }
How to set cookies to expire in 30 minutes in JavaScript?

You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.
You can try to run the following example to set cookies to expire in 30 minutes
Live Demo
<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               var now = new Date();
               var minutes = 30;
               now.setTime(now.getTime() + (minutes * 60 * 1000));
               cookievalue = escape(document.myform.customer.value) + ";"

               document.cookie="name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         Enter name: <input type="text" name="customer"/>
         <input type="button" value="Set Cookie" onclick="WriteCookie()"/>
      </form>
   </body>
</html>
Modular Arithmetic - GeeksforGeeks

04 May, 2020
Modular arithmetic is the branch of arithmetic mathematics related with the “mod” functionality. Basically, modular arithmetic is related with computation of “mod” of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other. Here we will discuss briefly about all modular arithmetic operations.
Quotient Remainder Theorem :It states that, for any pair of integers a and b (b is positive), there exists two unique integers q and r such that:
a = b x q + rwhere 0 <= r < b
Example:If a = 20, b = 6then q = 3, r = 220 = 6 x 3 + 2
Modular Addition :Rule for modular addition is:
(a + b) mod m = ((a mod m) + (b mod m)) mod m
Example:
(15 + 17) % 7
= ((15 % 7) + (17 % 7)) % 7
= (1 + 3) % 7
= 4 % 7
= 4

Same rule is for modular subtraction. We don’t require much modular subtraction but it can also be done in same way.
Modular Multiplication :Rule for modular multiplication is:
(a x b) mod m = ((a mod m) x (b mod m)) mod m
Example:
(12 x 13) % 5
= ((12 % 5) x (13 % 5)) % 5
= (2 x 3) % 5
= 6 % 5
= 1

Modular Division :Modular division is totally different from modular addition, subtraction and multiplication. It also does not exist always.
(a / b) mod m is not equal to ((a mod m) / (b mod m)) mod m.

This is calculated using following formula:
(a / b) mod m = (a x (inverse of b if exists)) mod m
Modular Inverse :The modular inverse of a mod m exists only if a and m are relatively prime i.e. gcd(a, m) = 1.Hence, for finding inverse of a under modulo m,if (a x b) mod m = 1 then b is modular inverse of a.Example:a = 5, m = 7(5 x 3) % 7 = 1hence, 3 is modulo inverse of 5 under 7.
Modular Exponentiation :Finding a^b mod m is the modular exponentiation. There are two approaches for this – recursive and iterative.Example:
a = 5, b = 2, m = 7
(5 ^ 2) % 7 = 25 % 7 = 4

Below are some more important concepts related to Modular Arithmetic
Euler’s Totient Function
Compute n! under modulo p
Wilson’s Theorem
How to compute mod of a big number?
Find value of y mod (2 raised to power x)
Recent Articles on Modular Arithmetic.
Modular Arithmetic
Engineering Mathematics
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Univariate, Bivariate and Multivariate data and its analysis
Mathematics | Graph Isomorphisms and Connectivity
Activation Functions
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Set Notations in LaTeX
Properties of Boolean Algebra
Mathematics | Euler and Hamiltonian Paths
Mathematics | Graph Theory Basics - Set 1
Betweenness Centrality (Centrality Measure)
C# Cast method

To cast elements, use the Cast() method.
The following is our list.
List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" };
Now, cast and use the Cast() method with substring() method to display the first two letters of every string in the list.
IEnumerable<string> res = myList.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
Let us see the complete example.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };
      // getting first 2 letters from every string
      IEnumerable<string> res = list.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
      foreach (string str in res)
      Console.WriteLine(str);
   }
}
ke
mo
jo
mo
numpy.ndarray.resize() function – Python

11 Jun, 2020
numpy.ndarray.resize() function change shape and size of array in-place.
Syntax : numpy.ndarray.resize(new_shape, refcheck = True)
Parameters :new_shape :[tuple of ints, or n ints] Shape of resized array.refcheck :[bool, optional] If False, reference count will not be checked. Default is True.
Return : None
Code #1 :
# Python program explaining# numpy.ndarray.resize() function        # importing numpy as geek import numpy as geek     arr = geek.array([[0, 1], [2, 3]])  # this function change the shape and size# of the array & return Nonegfg = arr.resize((2, 1))  print (gfg)
Output :
None

 Code #2 :
# Python program explaining# numpy.ndarray.resize() function        # importing numpy as geek import numpy as geek     arr = geek.array([[0, 1], [2, 3]], order = 'F')  # this function change the shape and size# of the array & return Nonegfg = arr.resize((2, 1))   print (gfg)
Output :
None

Python numpy-ndarray
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
Introduction To PYTHON
Python OOPs Concepts
Python | os.path.join() method
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
Python | datetime.timedelta() function
How to run multiple npm scripts in parallel?

09 Feb, 2021
As there is no straightforward way provided by npm to run multiple scripts in parallel, We can try coming up with a solution in the following way:
Create a basic React App project on the Localhost server and at the same time, we want to run the build operation of the project. Now what we can do is we can make use of the npm-run-all package, which will make it easy for us to host the project on the Localhost server, and also we can run the optimized build for production simultaneously.
Approach 1(npm-run all package): We can use the” npm-run all” package to run different scripts at the same time. First, we have to install the package itself by using the command.
npm install npm-run-all — save-dev
After installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously.
Now, our next step would be to open up a terminal on Mac or command prompt on Windows and “cd” into the project directory and type the command “./node_modules/.bin/npm-run-all build start ” and press Enter.
In the local installation case which we did, npm-run-all will be installed into our project’s node_modulesdirectory. PATH environment variable does not include there, so we have to use
./node_modules/.bin/npm-run-all 
(or $(npm bin)/npm-run-all)  to run npm-run-all command.
Console Output:
Build operation executed successfully
The app is hosted successfully on the server
Therefore, we can now see that our app is successfully hosted on a local server, and the build operation executed perfectly with the help of a single package “npm-run-all”.
Browser Output:
Approach 2 (Using Concurrently package): In this approach, we will be using the Concurrently package . Using this package we can combine different script commands such as “npm run start” and “npm run build ” into a single script and then run it in the command line.
First, install the package in your project directory using this command :
npm install concurrently --save
Again after installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build”  that we need in order to host the project on the server and to run the build operation simultaneously. 
Now we have to include a dev script inside the scripts in the package.json file which will hold our different commands combined.
  With –kill-others switch, all commands are killed if one dies.
We can follow this to create our own dev script :
"dev": "concurrently \"command1 arg\" \"command2 arg\""
Now we can simply run the whole command by simply using  :
npm run dev
Console output:
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js crypto.verify() Function

24 Sep, 2021
The crypto.verify()  is a method of the inbuilt module of node.js crypto that is used to verify the signature of data that is hashed using a different kind of hashing functions Like SHA256 algorithm etc.
Syntax:
crypto.verify(algorithm, data, publicKey, signature)
Parameters:
algorithm:  It is a string-type value. A signature can be verified by applying the name of signature algorithms, like ‘SHA256’. The algorithm must be the same in which the signature was created.
data: The data argument must be an instance of the buffer,  Typed Array, or Data View.
key: It should be the public key of the key object. If you have not any public key then you can create private and public keys using crypto.generateKeyPairSync() method.
signature: The signature argument must be an instance of Buffer, Typed Array, or Data View.
Returned value: This function returns a boolean value. Return True if a signature is verified else false.
Example:
Filename: index.js
Javascript
// Importing Required Modulesconst crypto = require('crypto');const buffer = require('buffer'); // Creating a private keyconst { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {  modulusLength: 2048,});// Using Hashing Algorithmconst algorithm = "SHA256"; // Converting string to bufferconst data = Buffer.from("I Love GeeksForGeeks"); // Sign the data and returned signature in bufferconst signature = crypto.sign(algorithm, data , privateKey); // Verifying signature using crypto.verify() functionconst isVerified = crypto.verify(algorithm, data, publicKey, signature); // Printing the resultconsole.log(`Is signature verified: ${isVerified}`);
Run index.js using the below command:
node index.js
Output:
Reference:https://nodejs.org/api/crypto.html#crypto_crypto_verify_algorithm_data_key_signature
 
anikaseth98
Node.js-crypto-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery focus() with Example

The focus() method in jQuery is used to trigger the focus event. The focus event occurs when an element gets focus.
The syntax is as follows −
$(selector).focus()
Let us now see an example to implement the jQuery focus() method −
<!DOCTYPE html>
<html>
<head>
<style>
   .demo {
      color: blue;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("#btn").click(function(){
         $("input").focus();
         $("p").html("focus event triggered");
      });
   });
</script>
</head>
<body>
<h2>Student Details</h2>
Student Name: <input type="text"><br>
<br><br>
<button id="btn">Trigger Event</button>
<p class="demo"></p>
</body>
</html>
This will produce the following output −
Above, click “Trigger Event” to trigger the focus event −
Taking Screenshots using pyscreenshot in Python

05 Sep, 2020
Python offers multiple libraries to ease our work. Here we will learn how to take a screenshot using Python. Python provides a module called pyscreenshot for this task. It is only a pure Python wrapper, a thin layer over existing backends. Performance and interactivity are not important for this library.
Install the package pyscreenshot using the below command in your command prompt.
pip install pyscreenshot
Here we will learn the simplest way of taking a screenshot using pyscreenshot module. Here we will use the function show() to view the screenshot. 
Python3
# Program to take screenshot  import pyscreenshot  # To capture the screenimage = pyscreenshot.grab()  # To display the captured screenshotimage.show()  # To save the screenshotimage.save("GeeksforGeeks.png")
Output:
Full Screenshot
Here is the simple Python program to capture the part of the screen. Here we need to provide the pixel positions in the grab() function. We need to pass the coordinates in the form of a tuple. 
Python3
# Program for partial screenshot  import pyscreenshot  # im=pyscreenshot.grab(bbox=(x1,x2,y1,y2))image = pyscreenshot.grab(bbox=(10, 10, 500, 500))  # To view the screenshotimage.show()  # To save the screenshotimage.save("GeeksforGeeks.png")
Output:
Partial Screenshot
Important Points:
We need to install pillow (PIL) package before installing pyscreenshot package.
Here show() function works as print i.e. It displays the captured screenshot.
We need to pass the coordinates in tuple.
We can save the screenshot to a file or PIL image memory.
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert Character String to Variable Name in R

09 May, 2021
In this article we will discuss how to convert a character string to the variable name in the R programming language i.e. we are going to assign the character string to the variable as the variable name
We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function.
Syntax: assign(“variable_name”,value)
Parameter:
variable_name is the name of the value
value is the variable.
Example:
R
# assign variable name to 3 valueassign("variable_name",3)  # print variable nameprint(variable_name)
Output:
[1] 3
We can also create a vector with a group of variables and assign a single variable name.
Example:
R
# create 5 variables at a timeassign("vector1",c(1,2,3,4,5))  # print variable nameprint(vector1)
Output:
[1] 1 2 3 4 5
This function allows you to call any R function. It allows using a list to hold the arguments of the function along with passing of single arguments.
Syntax:
do.call(“=”,list(“variable_name”, value))
Where “=” is an assign operator
The variable name is the named assigned to the value and value is the input value/variable.
Example:
R
do.call("=",list("a", 1))  print(a)
Output:
[1] 1
Example:
R
do.call("=",list("a", c(1,2,3,4,5)))  print(a)
Output:
[1] 1 2 3 4 5 
Picked
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Volatile Table in Teradata?

11 Aug, 2021
Volatile tables are as same as simple tables but with a small difference i.e. they are volatile in nature. 
Like a simple table, the volatile table is also formed by the user and can only be used until the user is logged into. Once the user is logged off or disconnects, the Teradata manager automatically drops the table from the session.
After dropping the table by Teradata manager, the data and definition inserted in the volatile table will be erased automatically.
Suppose, you are the user and working with the Teradata database and you have to form a couple of tables in the same database. The first option is you have to create simple tables in the same database and drop them after use.
The second option is you can create volatile tables whose data and definition are automatically dropped by the Teradata database after you logged off from the database and that will be the more smart way. 
We will follow the below syntax for volatile table syntax.
Syntax:
CREATE [SET | MULTISET] VOLATILE TABLE TABEL_NAME 
(
COLUMN1 DATATYPE;
COLUMN2 DATATYPE;
.
.
.
COLUMN_N datatype)
<INDEX_DEFINITION>
ON COMMIT [DELETE|PRESERVE] ROWS;

Example:
The following example will create a volatile table of the name ‘geek’.
CREATE VOLATILE TABLE GEEK
(
ROLLNO INT,
FIRST_NAME VARCHAR(15),
LAST_NAME VARCHAR(15)
)
PRIMARY INDEX (ROLLNO)
ON COMMIT PRESERVE ROWS;

Here, you can clearly see the last line written as ON COMMIT PRESERVE ROWS this line will preserve the data after inserting it by you.
The default value is ON COMMIT DELETE ROWS.
Data insertion in the volatile table:
Let’s insert some data in the volatile table.
INSERT INTO GEEK VALUES (1,'Aman','Goyal');
INSERT INTO GEEK VALUES (2,'Pritam','Soni');
INSERT INTO GEEK VALUES (3,'Swati','Jain');

Select data from the volatile table:
We will run the select statement into the volatile table.
SELECT * FROM GEEK ORDER BY ROLLNO;
Output:
At last, if we disconnect from the current session and after re-logging, run the same select statement again, we will find that the table student does not exist anymore in the database.
SELECT * FROM GEEK ORDER BY ROLLNO;
*** Failure 3807 Object 'GEEK' does not exist.
Statement# 1, Info =0
*** Total elapsed time was 1 second
Picked
SQL-Query
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
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?