code-rag-bench/online-tutorials huggingface dataset:
How to serialize a Python class?

Object serialization and deserialization are a routine aspect of any non-trivial Python program. Saving to a file, reading a configuration file, responding to an HTTP request, all involve object serialization and deserialization. 
Serialization and deserialization involve various schemes, formats and protocols to stream Python objects and to get them back later intact. Serialization schemes, formats or protocols you choose determine how fast your program runs and how secure it is.
Lets use a dictionary of python objects to serialize. Class is also a Python object. We use a Python module named pickle and its method pickle.dumps(object).
foo = dict(int_list=[3, 4, 5],  text='Hello World', number=9.99, boolean=False, none=None)
import cPickle as pickle

print pickle.dumps(foo)

print pickle.dumps(foo, protocol=pickle.HIGHEST_PROTOCOL)
Permutations and Sum | Practice | GeeksforGeeks

Given a number N , calculate total number of permutations of it and also the sum of all permutations including that number itself.
 
Example 1:
Input: N = 5
Output: 1 5
Explanation: There is only one permutation
of 5 and sum of this permutaion is 5.

Example 2:
Input: N = 12
Output: 2 33
Explanation: Permutations of 12 are 12 and 21.
Sum of these permutations are = 12 + 21 = 33.

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function permutation() which takes N as input parameter ans returns a list that contains total number of permutations and sum of all these permutations including the number iteself.
 
Expected Time Complexity: O(K!) where K = log10N
Expected Space Complexity: O(1)

Constraints:
1 <= N <= 105
0
Nikita Chhillar11 months ago
Nikita Chhillar
vector<int> permutaion(int N) {        // Code here        string s = to_string(N);
        sort(s.begin(), s.end());        int cnt = 0;        int tot = 0;        do{            tot += stoi(s);            cnt++;        }while(next_permutation(s.begin(), s.end()));        vector<int>res;        res.push_back(cnt);        res.push_back(tot);        return res;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
table.unpack() function in Lua programming

When we want to return multiple values from a table, we make use of the table.unpack() function. It takes a list and returns multiple values.
table.unpack{x,y,z,....}
The table.unpack() function provides us with all the values that are passed to it as an argument, but we can also specify which value we want by following the example shown below −
 Live Demo
a, b = table.unpack{1,2,3}
print(a, b)
In the above example, even though the table.unpack() function contains different values, namely 1, 2 and 3, we only are storing the first two values, i.e., a and b and the value 3 will be discarded.
1 2
It should be noted that if we don’t pass any value then all the values that are present in the list will be returned from the table.unpack() function. Consider the example shown below −
 Live Demo
print(table.unpack{1,2,3})
1   2   3
We can also ignore elements and select a specific index or positioned element from the list, consider the example shown below −
 Live Demo
_, b = table.unpack{-1,-2}
print(b)
-2
Do local variables in Java have default values?

No, local variables do not have default values. Once we create a local variable we must initialize it before using it.
Since the local variables in Java are stored in stack in JVM there is a chance of getting the previous value as default value. Therefore, In Java default values for local variables are not allowed.
public class Sample {
   public static void main(String args[] ){
      int data;
      System.out.println(data);
   }
}
C:\Sample>javac Sample.java
Sample.java:4: error: variable data might not have been initialized
   System.out.println(data);
                      ^
1 error
SQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.
Note: Be careful before dropping a database. Deleting 
a database will result in loss of complete information stored in the database!
The following SQL statement drops the existing database "testDB":
Tip: Make sure you have admin privilege before dropping any database. Once a 
database is dropped, you can check it in the list of databases with the 
following SQL command: SHOW DATABASES;
Write the correct SQL statement to delete a database named testDB.
;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to convert all the records in a MySQL table from uppercase to lowercase?

Convert all the records in a MySQL table from uppercase to lowercase using UPDATE command along with LOWER() method.
Let us first create a table −
mysql> create table DemoTable
   (
   Id varchar(100),
   StudentFirstName varchar(20),
   StudentLastName varchar(20),
   StudentCountryName varchar(10)
   );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('STU-101','John','Smith','US');
Query OK, 1 row affected (0.59 sec)
mysql> insert into DemoTable values('STU-102','John','Doe','UK');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('STU-103','David','Miller','AUS');
Query OK, 1 row affected (0.19 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+------------------+-----------------+--------------------+
| Id      | StudentFirstName | StudentLastName | StudentCountryName |
+---------+------------------+-----------------+--------------------+
| STU-101 | John             | Smith           | US                 |
| STU-102 | John             | Doe             | UK                 |
| STU-103 | David            | Miller          | AUS                |
+---------+------------------+-----------------+--------------------+
3 rows in set (0.00 sec)
Here is the query to change the case on every field in a MySQL table in a single call.
mysql> update DemoTable
set Id=lower(Id),
StudentFirstName=lower(StudentFirstName),
StudentLastName=lower(StudentLastName),
StudentCountryName=lower(StudentCountryName);
Query OK, 3 rows affected (0.22 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Display all records from the table using select statement to check the changes done in the above query −
mysql> select *from DemoTable;
This will produce the following output −
+---------+------------------+-----------------+--------------------+
| Id      | StudentFirstName | StudentLastName | StudentCountryName |
+---------+------------------+-----------------+--------------------+
| stu-101 | john             | smith           | us                 |
| stu-102 | john             | doe             | uk                 |
| stu-103 | david            | miller          | aus                |
+---------+------------------+-----------------+--------------------+
3 rows in set (0.00 sec)
Swing Examples - Show Input Dialog with List Box

Following example showcase how to get user input from a list in a dialog in swing based application.
We are using the following APIs.
JOptionPane − To create a standard dialog box.
JOptionPane − To create a standard dialog box.
JOptionPane.showInputDialog() − To show the message alert with input options.
JOptionPane.showInputDialog() − To show the message alert with input options.
options − To set the inputs to the list.
options − To set the inputs to the list.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JLabel label = new JLabel();
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
           String[] options = {"Red", "Green", "Blue"}; 
 
           String result = (String)JOptionPane.showInputDialog(
               frame,
               "Select one of the color", 
               "Swing Tester",            
               JOptionPane.PLAIN_MESSAGE,
               null,            
               options, 
               options[0] 
            );
            if(result == "Red" || result == "Green" || result == "Blue"){
               label.setText("You selected:" + result);
            }else {
               label.setText("None selected");
            }
         }
      });

      panel.add(button);
      panel.add(label);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
} 
 Print
 Add Notes
 Bookmark this page
HTML | <input type="date"> - GeeksforGeeks

18 Nov, 2021
The HTML <input type=”date”> is used to define a date picker or control field. The value will be the year, month and day. Syntax:  
<input type="date"> 
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML Input type = "Date" </title>    <style>        h1 {            color: green;        }                 h2 {            font-family: Impact;        }                 body {            text-align: center;        }    </style></head> <body>     <h1>GeeksforGeeks</h1>    <h2>HTML <input type="date"></h2>     <input type="date"           id="test"           value="2019-07-02T25:32Z"> </body> </html>
Output:  
Supported Browsers:  
Google Chrome 20.0
Firefox 57.0
Edge 12.0
Opera 10.1
Apple Safari 14.1
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to convert date and time with different timezones in Python?

The easiest way in Python date and time to handle timezones is to use the pytz module. This library allows accurate and cross platform timezone calculations. pytz brings the Olson tz database into Python. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).
Before you use it you'll need to install it using −
$ pip install pytz
You can use the pytz library as follows −
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))
This will give the output −
2018-01-03 07:05:50 UTC+0000
2018-01-03 12:35:50 IST+0530
What is the maximum value of float in Python?

In sys module, a struct sequence (tuple of named elements) called float_info has been defined. In this structure, an element max returns maximum representable finite float number.
>>> import sys
>>> sys.float_info.max
   1.7976931348623157e+308
Data Structures and Algorithms | Set 7 - GeeksforGeeks

27 Mar, 2017
Following questions have been asked in GATE CS 2006 exam.
1. In a binary max heap containing n numbers, the smallest element can be found in time (GATE CS 2006)(A) 0(n)(B) O(logn)(C) 0(loglogn)(D) 0(1)
Answer (A)In a max heap, the smallest element is always present at a leaf node. So we need to check for all leaf nodes for the minimum value. Worst case complexity will be O(n)
         12
        /  \
      /      \
    8         7
   / \        / \
 /     \    /     \
2      3   4       5
2. A scheme for storing binary trees in an array X is as follows. Indexing of X starts at 1 instead of 0. the root is stored at X[1]. For a node stored at X[i], the left child, if any, is stored in X[2i] and the right child, if any, in X[2i+1]. To be able to store any binary tree on n vertices the minimum size of X should be. (GATE CS 2006)(A) log2n(B) n(C) 2n + 1(D) 2^n — 1
Answer (D)For a right skewed binary tree, number of nodes will be 2^n – 1. For example, in below binary tree, node ‘A’ will be stored at index 1, ‘B’ at index 3, ‘C’ at index 7 and ‘D’ at index 15.
A
 \
   \
    B
      \
        \
         C
           \
             \
              D
3. Which one of the following in place sorting algorithms needs the minimum number of swaps? (GATE CS 2006)(A) Quick sort(B) Insertion sort(C) Selection sort(D) Heap sort
Answer (C)For selection sort, number of swaps required is minimum ( Θ(n) ).
4. An element in an array X is called a leader if it is greater than all elements to the right of it in X. The best algorithm to find all leaders in an array (GATE CS 2006)(A) Solves it in linear time using a left to right pass of the array(B) Solves it in linear time using a right to left pass of the array(C) Solves it using divide and conquer in time 8(nlogn)(D) Solves it in time 8(n2)
Answer (B)Please see this post for explanation.
5. Consider a weighted complete graph G on the vertex set {v1, v2, ..vn} such that the weight of the edge (vi, vj) is 2|i-j|. The weight of a minimum spanning tree of G is: (GATE CS 2006)(A) n — 1(B) 2n — 2(C) nC2(D) 2
Answer (B)Minimum spanning tree of such a graph is
v1
  \
    v2
      \
       v3
         \
          v4
            .
              .
                .
                 vn
 
Weight of the minimum spanning tree= 2|2 – 1| + 2|3 – 2| + 2|4 – 3| + 2|5 – 4| .... + 2| n – (n-1) |= 2n – 2
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect or you want to share more information about the topics discussed above.
GATE-CS-2006
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Semaphores in Process Synchronization
Types of Network Topology
Computer Networks | Set 1
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 2
Database Management Systems | Set 1
Koa.js - Error Handling

Error handling plays an important part in building web applications. Koa uses middleware for this purpose as well.
In Koa, you add a middleware that does try { yield next } as one of the first middleware. If we encounter any error downstream, we return to the associated catch clause and handle the error here. For example −
var koa = require('koa');
var app = koa();

//Error handling middleware
app.use(function *(next) {
   try {
      yield next;
   } catch (err) {
      this.status = err.status || 500;
      this.body = err.message;
      this.app.emit('error', err, this);
   }
});

//Create an error in the next middleware
//Set the error message and status code and throw it using context object

app.use(function *(next) {
   //This will set status and message
   this.throw('Error Message', 500);
});

app.listen(3000);
We have deliberately created an error in the above code and are handling the error in our first middleware's catch block. This is then emitted to our console as well as sent as the response to our client. Following is the error message we get when we trigger this error.
InternalServerError: Error Message
   at Object.module.exports.throw 
      (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23)
   at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13)
   at next (native)
   at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19)
   at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
   at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10)
   at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63)
   at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29)
   at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7)
   at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5

Right now any request sent to the server will result in this error.
 Print
 Add Notes
 Bookmark this page
Hash Functions and Hash Tables

Hashing is the process of generating a value from a text or a list of numbers using a mathematical function known as a hash function.There are many hash functions that use numeric numeric or alphanumeric keys. Different hash functions are given below:
The following are some of the Hash Functions −
This is the easiest method to create a hash function. The hash function can be described as −
h(k) = k mod n
Here, h(k) is the hash value obtained by dividing the key value k by size of hash table n using the remainder. It is best that n is a prime number as that makes sure the keys are distributed with more uniformity.
An example of the Division Method is as follows −
k=1276
n=10
h(1276) = 1276 mod 10
= 6
The hash value obtained is 6
A disadvantage of the division method id that consecutive keys map to consecutive hash values in the hash table. This leads to a poor performance.
The hash function used for the multiplication method is −
h(k) = floor( n( kA mod 1 ) )
Here, k is the key and A can be any constant value between 0 and 1. Both k and A are multiplied and their fractional part is separated. This is then multiplied with n to get the hash value.
An example of the Multiplication Method is as follows −
k=123
n=100
A=0.618033
h(123) = 100 (123 * 0.618033 mod 1)
= 100 (76.018059 mod 1)
= 100 (0.018059)
= 1
The hash value obtained is 1
An advantage of the multiplication method is that it can work with any value of A, although some values are believed to be better than others.
The mid square method is a very good hash function. It involves squaring the value of the key and then extracting the middle r digits as the hash value. The value of r can be decided according to the size of the hash table.
An example of the Mid Square Method is as follows −
Suppose the hash table has 100 memory locations. So r=2 because two digits are required to map the key to memory location.
k = 50
k*k = 2500
h(50) = 50

The hash value obtained is 50
A hash table is a data structure that maps keys to values. It uses a hash function to calculate the index for the data key and the key is stored in the index.
An example of a hash table is as follows −
The key sequence that needs to be stored in the hash table is −
35 50 11 79 76 85
The hash function h(k) used is:
h(k) = k mod 10
Using linear probing, the values are stored in the hash table as −
The Mito JupyterLab Extension — A Spreadsheet that Generates Python | by Roman Orac | Towards Data Science

Mito allows you to pass your dataframes or CSV files into a spreadsheet interface. It has the feel of Excel, but each edit generates the equivalent Python in the code cell below. At its best, this can be a really fast way to get your data analysis done.
In case you’ve missed my other articles about Mito:
Mito — A Spreadsheet that Generates Python
Here are the full installation instructions.
To install the Mito package, run these commands in your terminal:
python -m pip install mitoinstallerpython -m mitoinstaller install
Then open a notebook in Jupyter Lab and call a mitosheet:
import mitosheetmitosheet.sheet()
The Mitosheet can be called at any point in your analysis. You can pass in dataframes to the mitosheet as an argument in the sheet call.
mitosheet.sheet(df)
You can install pass in data from your local files with the import button.
Mito offers a range of features that allow the users to clean, wrangle and explore their data. Each of these features generates the equivalent Python in the code cell below.
Within Mito, you can:
Filter
Pivot
Merge
Graph
Look at summary statistics
Use Spreadsheet Formulas
and more...
For each of these edits, Mito generates Pandas code in the code cell below, that the user can carry forward in their analysis or send to a colleague.
Here is what it looks like to make a pivot table with Mito:
Example generated pivot table code looks like this (the code is auto-documented):
# Pivoted ramen_ratings_csv into df3unused_columns = ramen_ratings_csv.columns.difference(set(['Style']).union(set(['Brand'])).union(set({'Style'})))tmp_df = ramen_ratings_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table(    index=['Style'],    columns=['Brand'],    values=['Style'],    aggfunc={'Style': ['count']})# Flatten the column headerspivot_table.columns = [flatten_column_header(col) for col in pivot_table.columns.values]
Here is the process for looking at summary statistics about a column:
Getting the syntax correct for python data visualizations can be a time-consuming process. Mito allows you to generate graphs in a point and click environment and then gives you the equivalent code for those graphs.
Once you create a graph, click the copy graph code button:
Then paste the code in any code cell. Mito allows for a reproducible visualization process.
Mito is a fast way to generate Python code, especially for those familiar with Excel. It saves a lot of time on going to Stack Overflow or Google for correct syntax.
Mito is definitely worth a try, though it will be even more valuable as they introduce more graph types and a better ability for bulk editing (bulk column deletion, renaming etc.).
If you enjoy reading these stories, why not become a Medium paying member? It is $5 per month, and you will get unlimited access to 10000s of stories and writers. If you sign up using my link, I will earn a small commission.
Can we remove _id from MongoDB query result?

To remove _id from MongoDB result, you need to set 0 for _id field. Following is the syntax
db.yourCollectionName.find({},{_id:0});
To understand it, let us create a collection with documents. Following is the query
> db.removeIdDemo.insertOne({"UserName":"John","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb4042d66697741252440")
}
> db.removeIdDemo.insertOne({"UserName":"Mike","UserAge":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb40c2d66697741252441")
}
> db.removeIdDemo.insertOne({"UserName":"Sam","UserAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb4162d66697741252442")
}
> db.removeIdDemo.insertOne({"UserName":"Carol","UserAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb4222d66697741252443")
}
Following is the query to display all documents from a collection with the help of find() method
> db.removeIdDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9bb4042d66697741252440"),
   "UserName" : "John",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c9bb40c2d66697741252441"),
   "UserName" : "Mike",
   "UserAge" : 27
}
{
   "_id" : ObjectId("5c9bb4162d66697741252442"),
   "UserName" : "Sam",
   "UserAge" : 34
}
{
   "_id" : ObjectId("5c9bb4222d66697741252443"),
   "UserName" : "Carol",
   "UserAge" : 29
}
Following is the query to remove _id from Mongo result
> db.removeIdDemo.find({},{_id:0});
This will produce the following output
{ "UserName" : "John", "UserAge" : 23 }
{ "UserName" : "Mike", "UserAge" : 27 }
{ "UserName" : "Sam", "UserAge" : 34 }
{ "UserName" : "Carol", "UserAge" : 29 }
Count the number of duplicates in R - GeeksforGeeks

07 Apr, 2021
In this article, we will see how to find out the number of duplicates in R Programming language. 
It can be done with two methods:
Using duplicated() function.
Using algorithm.
Method 1: Using duplicated()
Here we will use duplicated() function of R and dplyr functions.
Approach:
Insert the “library(tidyverse)” package to the program.
Create a data frame or a vector.
Use the duplicated() function and check for the duplicate data.
Syntax: duplicated(x)
Parameters: x: Data frame or a vector
Example 1: Finding duplicate in vector.
Let’s first create a vector and find the position of the duplicate elements in x.
R
x <- c(1, 1, 4, 5, 4, 6)  duplicated(x)
Extract the duplicate elements in x.
R
x <- c(1, 1, 4, 5, 4, 6)  duplicated(x)x[duplicated(x)]
Here we can see all the elements which are duplicated.
Example 2: Finding duplicate in Dataframe.
Let’s now create a data frame.
R
data <- data.frame(  emp_id = c (1,1,2,4,5,6,6),    emp_name = c("Rick","Dan","Michelle",               "Ryan","Gary","x" , "y"))  display(data)
Here we have a data frame and some items are duplicated, so we have to find the duplicated elements in this data frame.
We will check which column has the duplicated data.
R
duplicated(data$emp_id)
So now find out in emp_id column how many duplicated elements are there.
R
data <- data.frame(  emp_id = c (1, 1, 2, 4, 5, 6, 6),    emp_name = c("Rick", "Dan", "Michelle",               "Ryan", "Gary", "x" , "y"))  duplicated[(data$emp_id), ]
We can see all the duplicated elements in column emp_id.
Method 2: Using algorithm.
Lets us assume we have a data frame with duplicate data, and we have to find out the number of duplicates in that data frame.
R
data <- data.frame(  emp_id = c (1,1,2,4,5,6,6),    emp_name = c("Rick","Dan","Michelle","Ryan","Gary","x" , "y"))  sum(table(data$emp_id)-1)
Output:
We can see clearly we have calculated the number of duplicates in the data frame.
Picked
R-Functions
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Program to check whether the given number is Buzz Number or not in C++

Given with a number ‘n’ and the task is to determine whether the given positive integer is a buzz number or not and display the result as an output.
For being a buzz number there are two conditions either of which must be true −
Number should end with digit 7 e.g. 27, 657, etc.
Number should end with digit 7 e.g. 27, 657, etc.
Number should be divisible by 7 e.g 63, 49, etc.
Number should be divisible by 7 e.g 63, 49, etc.
Input
number: 49
Output
it’s a buzz number
Explanation − since the number is divisible by 7 so it’s a buzz number
Input
number: 29
Output
it’s not a buzz number
Explanation − since the number is neither divisible by 7 nor end with digit 7 so it’s not a buzz number
Input the number to check for the condition
Input the number to check for the condition
Check whether the number is ending with digit 7 or divisible by 7
Check whether the number is ending with digit 7 or divisible by 7
If the condition holds true print its a buzz number
If the condition holds true print its a buzz number
If the condition doesn’t holds true print its not a buzz number
If the condition doesn’t holds true print its not a buzz number
Start
Step 1→ declare function to check if a number is a buzz number of not
   bool isBuzz(int num)
      return (num % 10 == 7 || num % 7 == 0)
Step 2→ In main()
   Declare int num = 67
   IF (isBuzz(num))
      Print "its a buzz Number\n"
   End
   Else
      Print "its not a buzz Number\n"
   End
Stop
 Live Demo
#include <cmath>
#include <iostream>
using namespace std;
// function to check if its a buzz number
bool isBuzz(int num){
   return (num % 10 == 7 || num % 7 == 0);
}
int main(){
   int num = 67;
   if (isBuzz(num))
      cout << "its a buzz Number\n";
   else
      cout << "its not a buzz Number\n";
}
If run the above code it will generate the following output −
its a buzz Number
Construct a complete binary tree from given array in level order fashion in C++

Suppose we have an array A[], with n elements. We have to construct the binary tree from the array in level order traversal. So the elements from the left in the array will be filled in the tree level-wise starting from level 0. So if the array is like A = [1, 2, 3, 4, 5, 6], then the tree will be like below:
If we see closer, we can find that when the parent is present at index i, then its two children will be at index (2i + 1), and (2i + 2). Thus we can insert left and right nodes using its parent nodes. The first element of the array will be the root of the tree.
 Live Demo
#include <iostream>
using namespace std;
class Node {
   public:
   int data;
   Node* left, * right;
};
Node* getNode(int data) {
   Node* node = new Node;
   node->data = data;
   node->left = node->right = NULL;
   return node;
}
Node* insertLevelWise(int arr[], Node* root, int i, int n) {
   if (i < n) {
      Node* temp = getNode(arr[i]);
      root = temp;
      root->left = insertLevelWise(arr, root->left, 2 * i + 1, n);
      root->right = insertLevelWise(arr, root->right, 2 * i + 2, n);
   }
   return root;
}
void inorderTrav(Node* root) {
   if (root != NULL){
      inorderTrav(root->left);
      cout << root->data <<" ";
      inorderTrav(root->right);
   }
}
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   Node* root = insertLevelWise(arr, root, 0, n);
   cout << "Inorder traversal of created tree: ";
   inorderTrav(root);
}
Inorder traversal of created tree: 4 2 5 1 6 3
Set the Date and Time with Gregorian Calendar in Java

To work with the GregorianCalendar class, import the following package.
import java.util.GregorianCalendar;
Create a Date object.
Date d = new Date();
Now, create an object and set the time using the setTime() method.
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d);
The following is an example.
 Live Demo
import java.util.Date;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String[] a) {
      Date d = new Date();
      GregorianCalendar cal = new GregorianCalendar();
      cal.setTime(d);
      System.out.println(d);
   }
}
Mon Nov 19 16:11:31 UTC 2018
Calculate inner, outer, and cross products of matrices and vectors using NumPy - GeeksforGeeks

29 Aug, 2020
Let’s discuss how to find the inner, outer, and cross products of matrices and vectors using NumPy in Python.
Inner Product of Vectors and Matrices
To find the inner product of the vectors and matrices, we can use the inner() method of NumPy.Syntax:
numpy.inner(arr1, arr2)
Code : 
Python3
# Python Program illustrating# numpy.inner() methodimport numpy as np  # Vectorsa = np.array([2, 6])b = np.array([3, 10])print("Vectors :")print("a = ", a)print("\nb = ", b)  # Inner Product of Vectorsprint("\nInner product of vectors a and b =")print(np.inner(a, b))  print("---------------------------------------")  # Matricesx = np.array([[2, 3, 4], [3, 2, 9]])y = np.array([[1, 5, 0], [5, 10, 3]])print("\nMatrices :")print("x =", x)print("\ny =", y)  # Inner product of matricesprint("\nInner product of matrices x and y =")print(np.inner(x, y))
Output :  
 
Outer Product of Vectors and Matrices
The outer product of the vectors and matrices can be found using the outer() method of NumPy.Syntax:
numpy.outer(a, b, out = None)
Code : 
Python3
# Python Program illustrating # numpy.outer() method import numpy as np  # Vectorsa = np.array([2, 6])b = np.array([3, 10])print("Vectors :")print("a = ", a)print("\nb = ", b)  # Outer product of vectors print("\nOuter product of vectors a and b =")print(np.outer(a, b))  print("------------------------------------")  # Matricesx = np.array([[3, 6, 4], [9, 4, 6]])y = np.array([[1, 15, 7], [3, 10, 8]])print("\nMatrices :")print("x =", x)print("\ny =", y)  # Outer product of matricesprint("\nOuter product of matrices x and y =")print(np.outer(x, y))
Output :  
 
Cross Product of Vectors and Matrices
To find the cross product of the vectors and matrices, we can use the cross() method of NumPy.
Syntax:
numpy.cross(a, b)
Code : 
Python3
# Python Program illustrating # numpy.cross() method import numpy as np  # Vectorsa = np.array([3, 6])b = np.array([9, 10])print("Vectors :")print("a = ", a)print("\nb = ", b)  # Cross product of vectors print("\nCross product of vectors a and b =")print(np.cross(a, b))  print("------------------------------------")  # Matricesx = np.array([[2, 6, 9], [2, 7, 3]])y = np.array([[7, 5, 6], [3, 12, 3]])print("\nMatrices :")print("x =", x)print("\ny =", y)  # Cross product of matricesprint("\nCross product of matrices x and y =")print(np.cross(x, y))
Output :  
 
Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Copy Constructor in C++

The copy constructor is a type of constructor. It creates an object and initializes it with an object of the same class. If the copy constructor is not defined in the class, the compiler itself defines one. A copy constructor is a must for a class that has pointer variables or dynamic memory allocations.
A program that demonstrates a copy constructor is as follows.
 Live Demo
#include<iostream>
using namespace std;
class Demo {
   private:
   int num1, num2;
   public:
   Demo(int n1, int n2) {
      num1 = n1;
      num2 = n2;
   }
   Demo(const Demo &n) {
      num1 = n.num1;
      num2 = n.num2;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};
int main() {
   Demo obj1(10, 20);
   Demo obj2 = obj1;
   obj1.display();
   obj2.display();
   return 0;
}
num1 = 10
num2 = 20

num1 = 10
num2 = 20
In the above program, the class Demo contains a normal parameterized constructor and a copy constructor. In addition to these, there is a function that displays the values of num1 and num2. These are given as follows.
class Demo {
   private:
   int num1, num2;
   public:
   Demo(int n1, int n2) {
      num1 = n1;
      num2 = n2;
   }
   Demo(const Demo &n) {
      num1 = n.num1;
      num2 = n.num2;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};
In the function main(), the class object obj1 is initialized using a parameterized constructor. The object obj2 is initialized using a copy constructor and the values of obj1 are copied into obj2. Finally the values of obj1 and obj2 are displayed. This is given below.
Demo obj1(10, 20);
Demo obj2 = obj1;
obj1.display();
obj2.display();
Python - Convert list to Single Dictionary Key Value list - GeeksforGeeks

03 Jul, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to convert the list into a dictionary, which has single key, the Kth element of list, and others as it’s list value. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [6, 5, 3, 2], K = 1Output : {5 : [6, 3, 2]}
Input : test_list = [6, 5, 3, 2], K = 2Output : {5 : [6, 5, 2]}
Method #1 : Using loopThis is one of the ways in which this task can be performed. In this, we create a key initially and then append values except K index to create dictionary list.
# Python3 code to demonstrate working of # Convert list to Single Dictionary Key Value list# Using loop  # initializing listtest_list = [5, 6, 3, 8, 9]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = 3  # Convert list to Single Dictionary Key Value list# Using loopres = {test_list[K] : []}for idx in range(len(test_list)):    if idx != K:        res[test_list[K]].append(test_list[idx])  # printing result print("Records after conversion : " + str(res))
The original list is : [5, 6, 3, 8, 9]
Records after conversion : {8: [5, 6, 3, 9]}

 
Method #2 : Using list slicingThis is yet another one liner in which this task can be performed. In this, we slice out the list on Kth index and assign as values in dictionary.
# Python3 code to demonstrate working of # Convert list to Single Dictionary Key Value list# Using loop  # initializing listtest_list = [5, 6, 3, 8, 9]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = 3  # Convert list to Single Dictionary Key Value list# Using loopres = {test_list[K] : test_list[:K] + test_list[K + 1:]}  # printing result print("Records after conversion : " + str(res))
The original list is : [5, 6, 3, 8, 9]
Records after conversion : {8: [5, 6, 3, 9]}

Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
MySQL Tryit Editor v1.0

SELECT * FROM Customers
ORDER BY Country, CustomerName;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How do we access class attributes using dot operator in Python?

A class attribute is an attribute of the class rather than an attribute of an instance of the class.
In the code below class_var is a class attribute, and i_var is an instance attribute: All instances of the class have access to class_var, which can also be accessed as a property of the class itself −
class MyClass (object):
    class_var = 2

    def __init__(self, i_var):
        self.i_var = i_var

foo = MyClass(3)
baz = MyClass(4)
print (foo.class_var, foo.i_var)
print (baz.class_var, baz.i_var)
This gives the output
(2, 3)
(2, 4)
Construct ∈-NFA of Regular Language L = (0+1)*(00+ 11)

The ε transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ
ε-NFA is defined in five tuple
{Q, q0, Σ, δ, F}
Where,
δ − Q × (Σ∪ε)→2Q
δ − Q × (Σ∪ε)→2Q
Q − Finite set of states
Q − Finite set of states
Σ − Finite set of the input symbol
Σ − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ − Transition function
δ − Transition function
NFA is defined in 5 tuple representation
{Q, q0, Σ, δ, F}
Where,
δ − Q X Σ→ 2Q
δ − Q X Σ→ 2Q
Q − Finite set of states
Q − Finite set of states
Σ, − Finite set of the input symbol
Σ, − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ − Transition function
δ − Transition function
NFA and NFA with epsilon both are almost the same; the only difference is their transition function.
Let’s consider the given language L = 0(0+1)*1
Rules for construction of ε-NFA are as follows −
Step 1 − NFA with epsilon for 0+ is given below −
Step 2 − NFA with epsilon for 0* is given below −
Step 3 − NFA with epsilon for (0+1) is given below −
The above transition diagram accepts either 0 or 1 as input. Those two paths lead to the final state.
Step 4 − NFA with epsilon for 01 is given below −
For concatenation 0 must be followed by 1.
Step 5 −
ε-NFA for L = (0+1)*(00 + 11)
L = (0+1)*(00 + 11) is divided into two parts: (0+1)* and (00+11).
First construct the first part and then second part finally concatenate two parts to get the result.
First part − (0+1)*
With the help of step 3 we can easily construct (0+1)* as shown below −
Second part − (00+11)
The second part can be easily drawn with the help of step 4.
In step 4, consider 1 and 0 both are either 00 or 11. Both strings are connected by + sign.
The final NFA with epsilon move is as follows −
Concatenate the first and second part,
Difference between Primary key and Super key - GeeksforGeeks

16 Apr, 2020
Prerequisite – Keys in Relational Model1. Super Key:Super Key is an attribute (or set of attributes) that is used to uniquely identifies all attributes in a relation. All super keys can’t be candidate keys but its reverse is true. In a relation, number of super keys are more than number of candidate keys.
Example:We have a given relation R(A, B, C, D, E, F) and we shall check for being super keys by following given dependencies:
Functional dependencies         Super key
AB->CDEF                         YES
CD->ABEF                         YES
CB->DF                           NO
D->BC                            NO 
By Using key AB we can identify rest of the attributes (CDEF) of the table. Similarly Key CD. But, by using key CB we can only identifies D and F not A and E. Similarly key D.
2. Primary Key:Candidate key is a set of attributes (or attribute) which uniquely identify the tuples in a relation or table. There can be more than one candidate key in relation out of which one can be chosen as the primary key.
Example:
Student{Stud_No, Stud_name, Stud_phone, 
             Stud_state, Stud_country, Stud_age} 
Here we can see the two candidate keys Stud_No and Stud_phone. STUD_No can be chosen as the primary key (only one out of many candidate keys).
Difference between Super Key and Primary Key:
Picked
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
CTE in SQL
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Third Normal Form (3NF)
Second Normal Form (2NF)
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Differences between TCP and UDP
Difference between Process and Thread
Max Consecutive Ones II in C++

Suppose we have a binary array; we have to find the maximum number of consecutive 1s in this array if we can flip at most one 0.
So, if the input is like [1,0,1,1,0], then the output will be 4 because if we flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.
To solve this, we will follow these steps −
ret := 1, n := size of nums
ret := 1, n := size of nums
if not n is non-zero, then −return 0
if not n is non-zero, then −
return 0
return 0
j := 0, zero := 0
j := 0, zero := 0
for initialize i := 0, when i < n, update (increase i by 1), do −if nums[i] is same as 0, then −(increase zero by 1)while (j <= i and zero > 1), do −if nums[j] is same as 0, then −(decrease zero by 1)(increase j by 1)ret := maximum of ret and (i - j + 1)
for initialize i := 0, when i < n, update (increase i by 1), do −
if nums[i] is same as 0, then −(increase zero by 1)
if nums[i] is same as 0, then −
(increase zero by 1)
(increase zero by 1)
while (j <= i and zero > 1), do −if nums[j] is same as 0, then −(decrease zero by 1)(increase j by 1)
while (j <= i and zero > 1), do −
if nums[j] is same as 0, then −(decrease zero by 1)
if nums[j] is same as 0, then −
(decrease zero by 1)
(decrease zero by 1)
(increase j by 1)
(increase j by 1)
ret := maximum of ret and (i - j + 1)
ret := maximum of ret and (i - j + 1)
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findMaxConsecutiveOnes(vector<int<& nums) {
      int ret = 1;
      int n = nums.size();
      if (!n)
         return 0;
      int j = 0;
      int zero = 0;
      for (int i = 0; i < n; i++) {
         if (nums[i] == 0) {
            zero++;
         }
         while (j <= i && zero > 1) {
            if (nums[j] == 0) {
               zero--;
            }
            j++;
         }
         ret = max(ret, i - j + 1);
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int< v = {1,0,1,1,1,0,1,1};
   cout << (ob.findMaxConsecutiveOnes(v));
}
{1,0,1,1,1,0,1,1}
6