code-rag-bench/online-tutorials huggingface dataset:
Python – Adjacent elements in List

When it is required to display adjacent elements in list, a method is defined that uses enumerate and a simple iteration to determine the result.
Below is a demonstration of the same −
def find_adjacent_elements(my_list):
   my_result = []
   for index, ele in enumerate(my_list):
      if index == 0:
         my_result.append((None, my_list[index + 1]))
      elif index == len(my_list) - 1:
         my_result.append((my_list[index - 1], None))
      else:
         my_result.append((my_list[index - 1], my_list[index + 1]))
   return my_result

my_list = [13, 37, 58, 12, 41, 25, 48, 19, 23]

print("The list is:")
print(my_list)

print("The result is :")
print(find_adjacent_elements(my_list))
The list is:
[13, 37, 58, 12, 41, 25, 48, 19, 23]
The result is :
[(None, 37), (13, 58), (37, 12), (58, 41), (12, 25), (41, 48), (25, 19), (48, 23), (19, None)]
A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list.
A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list.
An empty list is created.
An empty list is created.
The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined.
The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined.
If index value is 0, the element in first index is appended to the empty list.
If index value is 0, the element in first index is appended to the empty list.
If index is equal to length of list minus 1, the element in previous index is appended to empty list.
If index is equal to length of list minus 1, the element in previous index is appended to empty list.
Otherwise, both the previous and next elements are appended to the empty list.
Otherwise, both the previous and next elements are appended to the empty list.
Outside the method, a list is defined and displayed on the console.
Outside the method, a list is defined and displayed on the console.
The method is called by passing the required parameter.
The method is called by passing the required parameter.
The output is displayed on the console.
The output is displayed on the console.
Find the percentage of a student on basis of marks and add percent sign (%) to the result in SQL

Let us first create a table −
mysql> create table DemoTable
(
   Marks int
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(65);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(67);
Query OK, 1 row affected (0.33 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Marks |
+-------+
| 88    |
| 65    |
| 98    |
| 45    |
| 67    |
+-------+
5 rows in set (0.00 sec)
Following is the query to calculate percentage of the student in the basis of marks in 5 subjects. The result would be in percentage; therefore, we will also add percent sign (%) to the calculation −
mysql> select concat(round(SUM(Marks)*100/500),'%') from DemoTable;
This will produce the following output −
+---------------------------------------+
| concat(round(SUM(Marks)*100/500),'%') |
+---------------------------------------+
| 73%                                   |
+---------------------------------------+
1 row in set (0.00 sec)
Python 3 - Tkinter Toplevel

Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
Here is the simple syntax to create this widget −
w = Toplevel ( option, ... )

options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The background color of the window.
bd
Border width in pixels; default is 0.
cursor
The cursor that appears when the mouse is in this window.
class_
Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection = 0 if you don't want that behavior.
font
The default font for text inserted into the widget.
fg
The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
height
Window height.
relief
Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants.
width
The desired width of the window.
Toplevel objects have these methods −
deiconify()
Displays the window, after using either the iconify or the withdraw methods.
frame()
Returns a system-specific window identifier.
group(window)
Adds the window to the window group administered by the given window.
iconify()
Turns the window into an icon, without destroying it.
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
iconify()
Turns the window into an icon, without destroying it.
state()
Returns the current state of the window. Possible values are normal, iconic, withdrawn and icon.
transient([master])
Turns the window into a temporary(transient) window for the given master or to the window's parent, when no argument is given.
withdraw()
Removes the window from the screen, without destroying it.
maxsize(width, height)
Defines the maximum size for this window.
minsize(width, height)
Defines the minimum size for this window.
positionfrom(who)
Defines the position controller.
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
sizefrom(who)
Defines the size controller.
title(string)
Defines the window title.
Try following example yourself −
# !/usr/bin/python3
from tkinter import *

root = Tk()
root.title("hello")
top = Toplevel()
top.title("Python")
top.mainloop()
When the above code is  executed, it produces the following result −

    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 fix the incorrect datetime value while inserting in a MySQL table?

To avoid the incorrect datetime value error, you can use the STR_TO_DATE() method.
As we know the datetime format is YYYY-MM-DD and if you won’t insert in the same format, the error would get generated.
Let us see what actually lead to this error. For this, let us create a new table. The query to create a table is as follows
mysql> create table CorrectDatetimeDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > ArrivalTime datetime
   - > );
Query OK, 0 rows affected (0.63 sec)
The occurs when we try to include a date with an incorrect datetime format
mysql> insert into CorrectDatetimeDemo(ArrivalTime) values('18/02/2019 11:15:45');
ERROR 1292 (22007): Incorrect datetime value: '18/02/2019 11:15:45' for column 'ArrivalTime' at row 1
To avoid the above error, you can use STR_TO_DATE().
The syntax is as follows
INSERT INTO yourTableName(yourDateTimeColumnName) VALUES (STR_TO_DATE('yourDateTimeValue','%d/%m/%Y %H:%i:%s'));
Now, let us insert the datetime again with the correct format as shown in the above syntax.
The query is as follows
mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('18/02/2019 11:15:45','%d/%m/%Y %H:%i:%s'));
Query OK, 1 row affected (0.21 sec)

mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('15/01/2017 10:10:15','%d/%m/%Y %H:%i:%s'));
Query OK, 1 row affected (0.16 sec)

mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('12/04/2016 15:30:35','%d/%m/%Y %H:%i:%s'));
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from CorrectDatetimeDemo;
The following is the output
+----+---------------------+
| Id | ArrivalTime         |
+----+---------------------+
|  1 | 2019-02-18 11:15:45 |
|  2 | 2017-01-15 10:10:15 |
|  3 | 2016-04-12 15:30:35 |
+----+---------------------+
3 rows in set (0.00 sec)
Difference between 1NF and 2NF in DBMS

21 Aug, 2021
1. First Normal Form (1NF) : For any relation to be in the first normal form (1NF), the relation should not contain any composite or multi-valued attribute. So a relation will be in first normal form if it contains atomic values. The relation should contain only single valued attributes. Thus a relation that is in the first normal form must follow the following rules: 
There should be no repeating groups or elements in the relation, i.e., it should contain only single valued attributes.
There should be a unique name to be specified for each attribute within the table.
It should not contain any composite attributes.
Example: Consider the following relation:  
This relation is in 1NF as it does not contain any multi-valued or composite attributes. 
2. Second Normal Form (2NF) : The basic concept of second normal form is full functional dependency. It is thus applicable to the relations which contain composite keys(where the primary key consists of more than one attributes).So any relation which contains a single attribute primary key is always in 2NF (second normal form). Thus the relation which contains a composite primary key in order to be in 2NF should not contain any partial dependency. Partial dependency occurs when any non prime attribute is dependent on any of the proper subsets of the candidate key .Thus every non prime attribute should be dependent on whole of the every candidate key in the relation. Thus a relation is in 2NF if:  
It is in 1NF(first normal form).
It does not contain any partial dependency.
Example: Consider the functional dependencies for the relation R(X, Y, E, F).  
{XY->EF, E->F} 
We thus find the closure of (XY) which is {X, Y, E, F} Since its closure contains all the attributes in the relation thus XY is the candidate key.For each functional dependency, i.e., XY->EF: It does not contain any partial dependency as the non prime attributes depend on the whole of candidate key. E->F: It does not contain any partial dependency as here the non prime attributes depend on each other only. 
Difference between 1NF and 2NF :  
surinderdawra388
Picked
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Trigger | Student Database
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
related_name – Django Built-in Field Validation

01 Nov, 2020
The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don’t specify a related_name, Django automatically creates one using the name of your model with the suffix _set.
Syntax:
field_name = models.Field(related_name="name")

Explanation:
Illustration of related_name=”name”  using an Example. Consider a project named suorganizer(start up organizer) having an app named organizer.
Refer to the following articles to check how to create a project and an app in Django.

      How to Create a Basic Project using MVT in Django ?
      How to Create an App in Django ?


Enter the following code into models.py file of organizer app.
Python
from django.db import models  # Create your models here.   class Tag(models.Model):    name = models.CharField(max_length = 31)    def __str__(self):             return self.name.title()   class Post(models.Model):      title = models.CharField(max_length = 63)      tags = models.ManyToManyField(Tag, related_name ='blog_posts')     def __str__(self):                  return self.title    
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command.
Python manage.py shell


Now let us try to create instance of Tag and Post using None.
# importing required model
from organizer.models import Tag, Post

# creating instance of Tag model
r = Tag.objects.create(name ="django")
r.save()

# creating instance of Post model
s = Post.objects.create(title ="About django")
s.save()

# accessing objects
t = Tag.objects.get(name ="django")
p = Post.objects.get(title ="About django")

# method1--adding tag to post using post object
p.tags.add(t)

# method2--adding tag to post using tag object
# which is possible with related_name
t.blog_posts.add(p)

Let us check in admin interface if the instance of model is created.
1. Tag object:
2.Post object
In Django we only ever specify symmetric relations in a single place. The related_name parameter is what defines the other side of a relation. Concretely, given a Post instance p, the tags associated with this post are accessible via p.tags.  However, given a Tag instance t, we had not explicitly defined a variable to access Post objects. Thanks to the related_name option, we may now access the list of blog posts related to the tag t via the blog posts attribute, as in t.blog_posts. The   related _name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Tag model, Django would have created a post_set attribute, allowing access via t.post_set in our example. The formula Django uses is the name of the model followed by the string_set. The related name parameter thus simply overrides Django’s default rather than providing new behavior. 
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array concat() operation

08 Jan, 2020
Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together.
Syntax:  Array.concat()

Parameter:  Arrays to be combined

Return:  Append the two arrays

Code #1 : Example for concat() method
# Ruby code for concat() method# adding elements at the end  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [5, 4, nil, 1, 88, 9]  # declaring arrayc = [18, 22, nil, 40, 50, 6]  # COMBINING TWO ARRAYSputs "combining a and b : #{a.concat(b)}\n\n"  puts "combining c and b : #{b.concat(c)}\n\n"  puts "combining a and c : #{c.concat(a)}\n\n"
Output :
combining a and b : [18, 22, 33, nil, 5, 6, 5, 4, nil, 1, 88, 9]

combining c and b : [5, 4, nil, 1, 88, 9, 18, 22, nil, 40, 50, 6]

combining a and c : [18, 22, nil, 40, 50, 6, 18, 22, 33, nil, 5, 6, 5, 4, nil, 1, 88, 9]


Code #2 : Example for concat() method
# Ruby code for concat() method# adding elements at the end  # declaring arraya = ["abc", "xyz", "dog"]  # declaring arrayb = ["cow", "cat", "dog"]  # declaring arrayc = ["cat", "1", "dog"]  # COMBINING TWO ARRAYSputs "combining a and b : #{a.concat(b)}\n\n"  puts "combining c and b : #{b.concat(c)}\n\n"  puts "combining a and c : #{c.concat(a)}\n\n"
Output :
combining a and b : ["abc", "xyz", "dog", "cow", "cat", "dog"]

combining c and b : ["cow", "cat", "dog", "cat", "1", "dog"]

combining a and c : ["cat", "1", "dog", "abc", "xyz", "dog", "cow", "cat", "dog"]

Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pandas Dataframe.to_numpy() – Convert dataframe to Numpy array

27 Feb, 2020
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of Dataframe.to_numpy() method.
Syntax: Dataframe.to_numpy(dtype = None, copy = False)
Parameters:dtype: Data type which we are passing like str.copy: [bool, default False] Ensures that the returned value is a not a view on another array.
Returns:numpy.ndarray
To get the link to csv file, click on nba.csv
Example 1: Changing the DataFrame into numpy array by using a method DataFrame.to_numpy(). Always remember that when dealing with lot of data you should clean the data first to get the high accuracy. Although in this code we use the first five values of Weight column by using .head() method.
# importing pandasimport pandas as pd    # reading the csv  data = pd.read_csv("nba.csv")       data.dropna(inplace = True)   # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head())   # using to_numpy() functionprint(gfg.to_numpy())
Output:
[[180.]
 [235.]
 [185.]
 [235.]
 [238.]]
Example 2: In this code we are just giving the parameters in the same code. So we provide the dtype here.
# importing pandasimport pandas as pd    # read csv file  data = pd.read_csv("nba.csv")       data.dropna(inplace = True)   # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head())   # providing dtypeprint(gfg.to_numpy(dtype ='float32'))
Output:
[[180.]
 [235.]
 [185.]
 [235.]
 [238.]]
Example 3: Validating the type of the array after conversion.
# importing pandas import pandas as pd    # reading csv  data = pd.read_csv("nba.csv")       data.dropna(inplace = True)   # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head())   # using to_numpy()print(type(gfg.to_numpy()))
Output:
<class 'numpy.ndarray'>
Python pandas-dataFrame
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
How to create buttons in Jupyter?

24 Feb, 2021
In this article, we will learn How to create an interactive button in Jupyter using Python Program. An Interactive Button is a button which when clicked by a user performs a specific function. For the following task, we need the ipywidgets library module. ipywidgets, also known as jupyter-widgets or simply widgets, are interactive HTML widgets for Jupyter notebooks and the IPython kernel.
If your console does not have the module, you can install it by using the following command:
pip install ipywidgets
In most cases, installing the Python ipywidgets package will also automatically configure classic Jupyter Notebook and JupyterLab 3.0 to display ipywidgets. 
Example 1: Creating a simple button.
Syntax: widgets.Button(description=’My Button’)
Code:
Python3
# import moduleimport ipywidgets as widgets  # creating buttonwidgets.Button(description = 'My Button')
Output:
Example 2: 
Here, we will create an interactive button that will help us to select a random language from a list of given Languages.
interact_manual(): Automatically creates a User Interface Control for exploring code and data interactively.
choice(): Returns a randomly selected element from the specified sequence.
Code:
Python3
import ipywidgets as widgetsfrom ipywidgets import interact, interact_manual, fixed  from random import choice  def lang():  langSelect = ["English","Deustche","Espanol","Italiano","한국어","日本人"]  print(choice(langSelect))    interact_manual(lang)
Output:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Grouping list values into dictionary

26 Aug, 2019
Sometimes, while working with data, we can be encountered with a situation in which we have list of list and we need to group it’s 2nd index with the common initial element in lists. Let’s discuss way in which this problem can be solved.
Method : Using defaultdict() + loop + dict()
The defaultdict can be used to initialize the group elements and loop can be used to group the values together and conversion to dictionary can be done using dict().
# Python3 code to demonstrate working of# Grouping list values into dictionary# Using defaultdict() + loop + dict()from collections import defaultdict  # initializing listtest_list = [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]]  # printing original listprint("The original list is : " + str(test_list))  # Grouping list values into dictionary# Using defaultdict() + loop + dict()temp = defaultdict(list)for key, val in test_list:    temp[key].append(val)res = dict((key, tuple(val)) for key, val in temp.items())  # printing resultprint("The grouped dictionary is :  " + str(res))
The original list is : [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]]
The grouped dictionary is :  {'Gfg': (1, 2), 'best': (4, ), 'is': (3, 5)}

 
Python dictionary-programs
Python
Python Programs
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 program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Replace Character Value with NA in R

29 Sep, 2021
In this article, we are going to see how to replace character value with NA in R Programming Language.
We can replace a character value with NA in a vector and in a dataframe.
In a vector, we can replace it by using the indexing operation.
Syntax:
vector[vector == “character”] <- NA 
R
# create a vector with 10 charactersvector = c("a", "d", "A", "g", "S",           "S", "t", "S", "e", "S") # store actual vector in finalfinal = vector # replace character S with NAfinal[final == "S"] <- NA # display final vectorprint(final)
Output:
 [1] "a" "d" "A" "g" NA  NA  "t" NA  "e" NA
Replace character value with NA in dataframe.
Syntax:
dataframe[dataframe== “character”] <- NA
R
# create a dataframe with 10 charactersdata = data.frame("a", "d", "A", "g", "S",                  "S", "t", "S", "e", "S") # store actual dataframe in finalfinal = data # replace character A with NAfinal[final == "A"] <- NA # display final dataframeprint(final)
Output:
  X.a. X.d. X.A. X.g. X.S. X.S..1 X.t. X.S..2 X.e. X.S..3
1    a    d <NA>    g    S      S    t      S    e      S
anikakapoor
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
MongoDB query with case insensitive search?

For case, insensitive search, use regex in find() method. Following is the syntax −
db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}});
To understand the above syntax, let us create a collection with documents −
> db.demo572.insertOne({"CountryName":"US"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1")
}
> db.demo572.insertOne({"CountryName":"UK"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2")
}
> db.demo572.insertOne({"CountryName":"Us"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3")
}
> db.demo572.insertOne({"CountryName":"AUS"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4")
}
> db.demo572.insertOne({"CountryName":"us"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5")
}
Display all documents from a collection with the help of find() method −
> db.demo572.find();
This will produce the following output −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f17581e9acd78b427f2"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f20581e9acd78b427f4"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
Following is the query for case insensitive search −
> db.demo572.find({"CountryName" : { '$regex':/^US$/i}});
This will produce the following output −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
Group all documents with common fields in MongoDB?

For this, use the $addToSet operator. Let us first create a collection with documents −
> db.findDocumentWithCommonFieldsDemo.insertOne(
   {
      "UserId":1,
      "UserName":"Carol"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8ebebf3115999ed51200")
}
> db.findDocumentWithCommonFieldsDemo.insertOne(
   {
      "UserId":2,
      "UserName":"David"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8ebebf3115999ed51201")
}
>
> db.findDocumentWithCommonFieldsDemo.insertOne(
   {
      "UserId":1,
      "UserName":"Sam"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8ebebf3115999ed51202")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentWithCommonFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdf8ebebf3115999ed51200"), "UserId" : 1, "UserName" : "Carol" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51201"), "UserId" : 2, "UserName" : "David" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51202"), "UserId" : 1, "UserName" : "Sam" }
Following is the query to find all documents with common fields in MongoDB −
> db.findDocumentWithCommonFieldsDemo.aggregate({$group : {_id : "$UserId", "UserDetails": {$addToSet : "$UserName"}}});
This will produce the following output −
{ "_id" : 2, "UserDetails" : [ "David" ] }
{ "_id" : 1, "UserDetails" : [ "Sam", "Carol" ] }
How to get the top 3 salaries from a MySQL table with record of Employee Salaries?

For this, use LIMIT and OFFSET. Let us first create a table −
mysql> create table DemoTable867(EmployeeSalary int);
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable867 values(63737);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable867 values(899833);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable867 values(23644);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable867 values(89393);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable867 values(534333);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable867 values(889322);
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable867;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 63737          |
| 899833         |
| 23644          |
| 89393          |
| 534333         |
| 889322         |
+----------------+
6 rows in set (0.00 sec)
Here is the query to get first highest salary −
mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 899833         |
+----------------+
1 row in set (0.02 sec)
Here is the query to get second highest salary −
mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1 OFFSET 1;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 889322         |
+----------------+
1 row in set (0.00 sec)
Following is the query to get third highest salary −
mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1 OFFSET 2;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 534333         |
+----------------+
1 row in set (0.00 sec)
Integrating Python with MySQL. A data analyst or data scientist get... | by Sanjana Ramankandath | Towards Data Science

A data analyst or data scientist get lots of opportunity to work on Python and SQL. Python with its enormous library support provides data analyst with a magic wand to manipulate and visualize data. Likewise SQL helps us store millions of records and establish relationships with other tables for optimal data management. There are scenarios that require a Python program to directly load data into a back-end database. For example, if a data frame is dynamically modified periodically or at random instances, uploading the csv file for each data update into the database is not feasible. In this post, we will go through how to integrate a Python program with MySQL database.
First, I created a small dataset in Python. It has two columns, first column stores index and second column stores time stamp.
from datetime import datetime # Current date time in local system col_1 = col_1+1 col_2 = datetime.now()print('ID:',col_1)print('Timestamp:',col_2)
Creating a table in MySQL
Meanwhile we can create a table in MySQL db which will be used to store the data that we generated in the first step. It is also possible to create a table in MySQL from python itself. As this is a one time process, it will be easier to create the table in the database directly.
#Create table called details.create table `details`(Id int(20)  not null,Time datetime null );
Connecting Python to MySQL
First we need to import the mysql.connector package, if it is not available then we need to install it using below code
pip install mysql.connector#or!pip install mysql.connector
We need to import the error code from mysql.connector. This will be helpful for identifying the issues, if any, while inserting into the DB.Some of the errors that one might encounter will be primary key null error and duplicate entries (if the table is set with a primary key).
We need to specify our MySQL credentials in the code. We first open a connection to the MySQL server and store the variable connection object in the variable cnct. We then create a new cursor, using the connection's cursor() method.
We will store the insert statement in the variable sql_query and the data in variable info is used to replace the %s markers in the query .
The execute statement will execute the query which is stored in the variable sql_query
Once the above code is executed, let’s check the database to see if the data is loaded dynamically.
Wonderful!! The data has been loaded.
Now lets see how the data is loaded into the database, if I ran the code 5 times.
Each time you run the code or job , the database will be dynamically loaded and refreshed.
Conclusion
Similarly we can perform any operation like creating database or tables, insert, update, delete and select operations from the Python interface itself and it will be reflected in the MySQL database.
This integration will prove useful for scenarios that involve ever changing data. For example, data that is scraped often from website or fetching live data from Twitter or Facebook feeds.
Jupyter notebook is available on Github.
JavaScript - Array pop() Method

Javascript array  pop() method removes the last element from an array and returns that element.
Its syntax is as follows −
array.pop();

Returns the removed element from the array.
Try the following example.
<html>
   <head>
      <title>JavaScript Array pop Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var numbers = [1, 4, 9];
         
         var element = numbers.pop();
         document.write("element is : " + element ); 
         
         var element = numbers.pop();
         document.write("<br />element is : " + element );
      </script>      
   </body>
</html>
element is : 9
element is : 4  


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Passing NULL to printf in C - GeeksforGeeks

02 Jun, 2017
Consider the following C code snippet.
char* p = NULL;
printf("%s", p);

What should be the output of the above program?The print expects a ‘\0’ terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior.
According to Section 7.1.4(of C99 or C11) : Use of library functions
If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.
Some compilers may produce null while others Segmentation Fault. GCC prints (null).
// Effect of passing null pointers to ( %s ) // printf in C#include <stdio.h>  int main(){   char* p = NULL;   printf( "%s", p);   return 0;}
Output in GCC:
(null)
Note that the above program may cause undefined behavior as per C standard.
 
This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Pointers
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Understanding "extern" keyword in C
Storage Classes in C
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++
Node Jimp | resize - GeeksforGeeks

19 Feb, 2021
Introduction The resize() function is an inbuilt function in Nodejs | Jimp which resizes the image to a set width and height using a 2-pass bilinear algorithm. Syntax:  
resize(w, h, mode, cb)
Parameter:  
w – This parameter stores the width of the image.
h – This parameter stores the height of the image.
mode – This is optional parameter which stores the scaling method.
cb – This is optional parameter which is invoked when compilation is complete.
Input Images:  
 
npm init -y
npm install jimp --save
Example 1:  
javascript
// npm install --save jimp// import jimp library to the environmentvar Jimp = require('jimp'); // User-Defined Function to read the imagesasync function main() {    const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png');// rotate Function having rotation as 55    image.resize(323, 421)    .write('resize1.png');} main();    console.log("Image Processing Completed");
Output:  
Example 2: With cb (optional parameters)  
javascript
//npm install --save jimp//import jimp library to the environmentvar Jimp = require('jimp'); //User-Defined Function to read the imagesasync function main() {    const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185333/gfg111.png');//rotate Function having rotation angle as 99, mode and callback function  image.resize(1024, 768, Jimp.RESIZE_BEZIER, function(err){      if (err) throw err;  })      .write('resize2.png');} main();  console.log("Image Processing Completed");
Output:  
Reference: https://www.npmjs.com/package/jimp 
mridulmanochagfg
Image-Processing
Node-Jimp
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Express.js express.Router() Function
How to read and write Excel file in Node.js ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns

To create a DataFrame with the levels of the MultiIndex as columns, use the to_frame() method in Pandas.
At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
Create a DataFrame with the levels of the MultiIndex as columns using to_frame() −
dataFrame = multiIndex.to_frame()

Following is the code −
import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# display the MultiIndex
print("The Multi-index...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)

# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
dataFrame = multiIndex.to_frame()

# Display the DataFrame
print("\nThe DataFrame...\n",dataFrame)
This will produce the following output −
The Multi-index...
MultiIndex([(1,  'John'),
            (2,   'Tim'),
            (3, 'Jacob'),
            (4, 'Chris')],
            names=['ranks', 'student'])

The levels in Multi-index...
   [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]

The DataFrame...
                ranks  student
ranks  student
1      John        1   John
2      Tim         2   Tim
3      Jacob       3   Jacob
4      Chris       4   Chris
How can we add/insert a JRadioButton to a JTable cell in Java?


A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. We can add or insert a radio button to a JTable cell by customizing the TableCellRenderer interface and the DefaultCellEditor class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class JTableRadioButtonTest extends JFrame {
   private DefaultTableModel dtm;
   private ButtonGroup bg;
   private JTable table;
   private JScrollPane jsp;
   public JTableRadioButtonTest() {
      setTitle("JTableRadioButton Test");
      dtm = new DefaultTableModel();
      dtm.setDataVector(new Object[][] {{"Course 1",new JRadioButton("Java")},{"Course 1",new               JRadioButton("Python")}, {"Course 1",new JRadioButton("Scala")}, {"Course 2",new                     RadioButton("Selenium")}, {"Course 2",new JRadioButton("Java Script")}},new Object[]                 {"Course","Technology"});
      table = new JTable(dtm) {
         public void tableChanged(TableModelEvent tme) {
            super.tableChanged(tme);
            repaint();
         }
      };
      bg = new ButtonGroup();
      bg.add((JRadioButton)dtm.getValueAt(0,1));
      bg.add((JRadioButton)dtm.getValueAt(1,1));
      bg.add((JRadioButton)dtm.getValueAt(2,1));
      bg.add((JRadioButton)dtm.getValueAt(3,1));
      bg.add((JRadioButton)dtm.getValueAt(4,1));
      table.getColumn("Technology").setCellRenderer(new RadioButtonRenderer());
      table.getColumn("Technology").setCellEditor(new RadioButtonEditor(new JCheckBox()));
      jsp = new JScrollPane(table);
      add(jsp, BorderLayout.NORTH);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTableRadioButtonTest();
   }
}
class RadioButtonRenderer implements TableCellRenderer {
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,        boolean hasFocus, int row, int column) {
      if (value==null) return null;
         return (Component)value;
   }
}
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
   private JRadioButton button;
   public RadioButtonEditor(JCheckBox checkBox) {
      super(checkBox);
   }
   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
      if (value==null) return null;
      button = (JRadioButton)value;
      button.addItemListener(this);
      return (Component)value;
   }
   public Object getCellEditorValue() {
      button.removeItemListener(this);
      return button;
   }
   public void itemStateChanged(ItemEvent e) {
      super.fireEditingStopped();
   }
}
Design and Analysis Binary Search

In this chapter, we will discuss another algorithm based on divide and conquer method.
Binary search can be performed on a sorted array. In this approach, the index of an element x is determined if the element belongs to the list of elements. If the array is unsorted, linear search is used to determine the position.
In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed.
Algorithm: Binary-Search(numbers[], x, l, r)
if l = r then  
   return l  
else 
   m := ⌊(l + r) / 2⌋ 
   if x ≤ numbers[m]  then 
      return Binary-Search(numbers[], x, l, m) 
   else 
      return Binary-Search(numbers[], x, m+1, r) 

Linear search runs in O(n) time. Whereas binary search produces the result in O(log n) time
Let T(n) be the number of comparisons in worst-case in an array of n elements.
Hence,
T(n)={0ifn=1T(n2)+1otherwise
Using this recurrence relation T(n)=logn.
Therefore, binary search uses O(logn) time.
In this example, we are going to search element 63.

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Find Numbers with Even Number of Digits in Python

Suppose we have a list of numbers. We have to count the numbers that has even number of digit count. So if the array is like [12,345,2,6,7896], the output will be 2, as 12 and 7896 has even number of digits
To solve this, we will follow these steps −
Take the list and convert each integer into string
if the length of string is even, then increase count and finally return the count value
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def findNumbers(self, nums):
      str_num = map(str, nums)
      count = 0
      for s in str_num:
         if len(s) % 2 == 0:
            count += 1
      return count
ob1 = Solution()
print(ob1.findNumbers([12,345,2,6,7897]))
[12,345,2,6,7897]
2
Time Series - Auto Regression

For a stationary time series, an auto regression models sees the value of a variable at time ‘t’ as a linear function of values ‘p’ time steps preceding it. Mathematically it can be written as −
yt=C+φ1yt−1+φ2Yt−2+...+φpyt−p+εt
 
Where,‘p’ is the auto-regressive trend parameter
εt is white noise, and
yt−1,yt−2...yt−p denote the value of variable at previous time periods.
The value of p can be calibrated using various methods. One way of finding the apt value of ‘p’ is plotting the auto-correlation plot.
Note − We should separate the data into train and test at 8:2 ratio of total data available prior to doing any analysis on the data because test data is only to find out the accuracy of our model and assumption is, it is not available to us until after predictions have been made. In case of time series, sequence of data points is very essential so one should keep in mind not to lose the order during splitting of data.
An auto-correlation plot or a correlogram shows the relation of a variable with itself at prior time steps. It makes use of Pearson’s correlation and shows the correlations within 95% confidence interval. Let’s see how it looks like for ‘temperature’ variable of our data.
In [141]:
split = len(df) - int(0.2*len(df))
train, test = df['T'][0:split], df['T'][split:]

In [142]:
from statsmodels.graphics.tsaplots import plot_acf

plot_acf(train, lags = 100)
plt.show()

All the lag values lying outside the shaded blue region are assumed to have a csorrelation.

    16 Lectures 
     2 hours 

 Malhar Lathkar

    21 Lectures 
     2.5 hours 

 Sasha Miller

    19 Lectures 
     1 hours 

 Sasha Miller

    94 Lectures 
     13 hours 

 Abhishek And Pukhraj

    12 Lectures 
     2 hours 

 Prof. Paul Cline, Ed.D

    11 Lectures 
     1 hours 

 Prof. Paul Cline, Ed.D
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2016 (Set 1) | Question 11 - GeeksforGeeks

11 Oct, 2021
Let p, q, r, s represent the following propositions.
p: {8, 9, 10, 11, 12}
q: x is a composite number
r: x is a perfect square
s: x is a prime number
 Note : This question was asked as Numerical Answer Type.(A) 8(B) 9(C) 11(D) 12Answer: (C)Explanation: (p ⇒ q) will give {8, 9, 10, 12}¬r will give {8, 10, 11, 12}¬s will give {8, 9, 10, 12}(¬r ∨ ¬s) will give {8, 9, 10, 11, 12}(p ⇒ q) ∧ (¬r ∨ ¬s) will give {8, 9, 10, 12}¬((p ⇒ q) ∧ (¬r ∨ ¬s)) will give 11.
Thus, C is the correct option.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGate PYQ's on Propositional and First order Logic with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0033:10 / 41:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ID4_2ewAGE0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | Gate IT 2007 | Question 30
GATE | GATE CS 2021 | Set 1 | Question 47