code-rag-bench/online-tutorials huggingface dataset:
Hadoop Tutorial

02 Mar, 2021
Big Data is a collection of data that is growing exponentially, and it is huge in volume with a lot of complexity as it comes from various resources. This data may be structured data, unstructured or semi-structured. So to handle or manage it efficiently, Hadoop comes into the picture.
Hadoop is a framework written in Java programming language that works over the collection of commodity hardware. Before Hadoop, we are using a single system for storing and processing data. Also, we are dependent on RDBMS which only stores the structured data. To solve the problem of such huge complex data, Hadoop provides the best solution. So let’s get started.
Basics
Installation and Environment Setup
Components of Hadoop
Cluster, Rack & Schedulers
HDFS
MapReduce
MapReduce Programs
Hadoop Streaming
Hadoop File and Commands
Misc
  
What is Big Data?
What is Unstructured Data?
What is Semi-Structured Data?
5V’s of Big Data
Hadoop – Solution to Big Data
Evolution of Hadoop
Different Versions of Hadoop
RDBMS vs Hadoop
Hadoop Architecture
Hadoop 2.x vs Hadoop 3.x
Hadoop – Ecosystem
How to Install Hadoop in Linux?
Installing and Setting Up Hadoop in Windows 10
Installing Single Node Cluster Hadoop on Windows
Configuring Eclipse with Apache Hadoop
Hadoop Distributed File System(HDFS)
MapReduce
YARN
Hadoop Cluster
Hadoop – Cluster, Properties and its Types
Hadoop – Rack and Rack Awareness
Hadoop – Schedulers and Types of Schedulers
Hadoop – Different Modes of Operation
Various Filesystems in Hadoop
Why a Block in HDFS is so Large?
Daemons and Their Features
File Blocks and Replication Factor
Data Read Operation
Map Reduce in Hadoop
MapReduce Architecture
Mapper In MapReduce
Reducer in Map-Reduce
MapReduce Job Execution
Hadoop MapReduce – Data Flow
Job Initializations in MapReduce
How does Job run on MapReduce?
How MapReduce Completes a Task?
Weather Data Analysis For Analyzing Hot And Cold Days
Finding The Average Age of Male and Female Died in Titanic Disaster
How to Execute Character Count Program in MapReduce Hadoop?
What is Hadoop Streaming?
Hadoop Streaming Using Python – Word Count Problem
Hadoop – File Permission and ACL(Access Control List)
Hadoop – copyFromLocal Command
Hadoop – getmerge Command
Hadoop Version 3.0 – What’s New?
Top 7 Reasons to Learn Hadoop
Top 10 Hadoop Analytics Tools For Big Data
Top 5 Recommended Books To Learn Hadoop
Features of Hadoop Which Makes It Popular
Hadoop vs Spark vs Flink
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Insert after every Nth element in a list

10 Dec, 2020
Sometimes we need to perform a single insertion in python, this can be easily done with the help of the insert function. But sometimes, we require to insert in a repeated manner after every n numbers, for that there can be numerous shorthands that can be quite handy. Lets discuss certain ways in which this can be done.
Method #1 : Using join() + enumerate()We can use the join function to join each of nth substring with the digit K and enumerate can do the task of performing the selective iteration of list.
# Python3 code to demonstrate # inserting K after every Nth number# using join() + enumerate()  # initializing listtest_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r',                            'g', 'e', 'e', 'k', 's']  # printing original listprint ("The original list is : " + str(test_list))  # initializing k k = 'x'  # initializing NN = 3  # using join() + enumerate()# inserting K after every Nth number res = list(''.join(i + k * (N % 3 == 2)            for N, i in enumerate(test_list)))  # printing result print ("The lists after insertion : " +  str(res))
The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’]
 Method #2 : Using itertools.chain()This method also has the ability to perform a similar task using an iterator and hence an improvement in the performance. This function performs a similar task but uses chain method to join the n substrings.
# Python3 code to demonstrate # inserting K after every Nth number# using itertool.chain()from itertools import chain  # initializing listtest_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r',                            'g', 'e', 'e', 'k', 's']  # printing original listprint ("The original list is : " + str(test_list))  # initializing k k = 'x'  # initializing NN = 3  # using itertool.chain()# inserting K after every Nth number res = list(chain(*[test_list[i : i+N] + [k]             if len(test_list[i : i+N]) == N             else test_list[i : i+N]             for i in range(0, len(test_list), N)]))  # printing result print ("The lists after insertion : " + str(res))
The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’]
Marketing
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
iomanip setfill() function in C++ with Examples

11 Oct, 2019
The setfill() method of iomaip library in C++ is used to set the ios library fill character based on the character specified as the parameter to this method.
Syntax:
setfill(char c)

Parameters: This method accepts c as a parameter which is the character argument corresponding to which the fill is to be set.
Return Value: This method does not returns anything. It only acts as stream manipulators.
Example 1:
// C++ code to demonstrate// the working of setfill() function  #include <iomanip>#include <ios>#include <iostream>  using namespace std;  int main(){      // Initializing the integer    int num = 50;      cout << "Before setting the fill char: \n"         << setw(10);    cout << num << endl;      // Using setfill()    cout << "Setting the fill char"         << " setfill to *: \n"         << setfill('*')         << setw(10);    cout << num << endl;      return 0;}
Before setting the fill char: 
        50
Setting the fill char setfill to *: 
********50

Example 2:
// C++ code to demonstrate// the working of setfill() function  #include <iomanip>#include <ios>#include <iostream>  using namespace std;  int main(){      // Initializing the integer    int num = 50;      cout << "Before setting the fill char: \n"         << setw(10);    cout << num << endl;      cout << "Setting the fill"         << " char setfill to $: \n"         << setfill('$')         << setw(10);    cout << num << endl;      return 0;}
Before setting the fill char: 
        50
Setting the fill char setfill to $: 
$$$$$$$$50

Reference: http://www.cplusplus.com/reference/iomanip/setfill/
CPP-Functions
cpp-input-output
cpp-manipulators
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
Inheritance in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Substring in C++
C++ Pointer to an Array

It is most likely that you would not understand this chapter until you go through the chapter related C++ Pointers.
So assuming you have bit understanding on pointers in C++, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration −
double balance[50];

balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance −
double *p;
double balance[10];

p = balance;

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above −
#include <iostream>
using namespace std;
 
int main () {
   // an array with 5 elements.
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;

   p = balance;
 
   // output each array element's value 
   cout << "Array values using pointer " << endl;
   
   for ( int i = 0; i < 5; i++ ) {
      cout << "*(p + " << i << ") : ";
      cout << *(p + i) << endl;
   }
   cout << "Array values using balance as address " << endl;
   
   for ( int i = 0; i < 5; i++ ) {
      cout << "*(balance + " << i << ") : ";
      cout << *(balance + i) << endl;
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using balance as address
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50

In the above example, p is a pointer to double which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Binary Search using pthread - GeeksforGeeks

26 Dec, 2017
Binary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discard the half which has zero probability of having the key. On dividing we check the mid point for the key and uses the lower half if key is less than mid point and upper half if key is greater than mid point. Binary search has time complexity of O(log(n)).
Binary search can also be implemented using multi-threading where we utilizes the cores of processor by providing each thread a portion of list to search for the key.
Number of threads depends upon the number of cores your processor has and its better to create one thread for each core.
Examples:
Input :  list = 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220
         key = 7
Output : 7 found in list

Input :  list = 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220
         key = 111
Output : 111 not found in list

Note – It is advised to execute the program in Linux based system.Compile in linux using following code:
g++ -pthread program_name.cpp

// CPP Program to perform binary search using pthreads#include <iostream>using namespace std;  // size of array#define MAX 16  // maximum number of threads#define MAX_THREAD 4  // array to be searchedint a[] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };  // key that needs to be searchedint key = 110;bool found = false;int part = 0;  void* binary_search(void* arg){      // Each thread checks 1/4 of the array for the key    int thread_part = part++;    int mid;      int low = thread_part * (MAX / 4);    int high = (thread_part + 1) * (MAX / 4);      // search for the key until low < high    // or key is found in any portion of array    while (low < high && !found)  {          // normal iterative binary search algorithm        mid = (high - low) / 2 + low;          if (a[mid] == key)  {            found = true;            break;        }          else if (a[mid] > key)            high = mid - 1;        else            low = mid + 1;    }}    // Driver Codeint main(){    pthread_t threads[MAX_THREAD];      for (int i = 0; i < MAX_THREAD; i++)        pthread_create(&threads[i], NULL, binary_search, (void*)NULL);      for (int i = 0; i < MAX_THREAD; i++)        pthread_join(threads[i], NULL);      // key found in array    if (found)        cout << key << " found in array" << endl;      // key not found in array    else        cout << key << " not found in array" << endl;      return 0;}
Output:
110 found in array

Binary Search
Divide and Conquer
Searching
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Search In JavaScript
Find a Fixed Point (Value equal to index) in a given array
Convex Hull using Divide and Conquer Algorithm
Binary Search (bisect) in Python
Multiply two polynomials
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
Program to find largest element in an array
How to count duplicates in Pandas Dataframe? - GeeksforGeeks

28 Jul, 2020
Let us see how to count duplicates in a Pandas DataFrame. Our task is to count the number of duplicate entries in a single column and multiple columns.
Under a single column : We will be using the pivot_table() function to count the duplicates in a single column. The column in which the duplicates are to be found will be passed as the value of the index parameter. The value of aggfunc will be ‘size’.
# importing the moduleimport pandas as pd   # creating the DataFramedf = pd.DataFrame({'Name' : ['Mukul', 'Rohan', 'Mayank',                              'Sundar', 'Aakash'],                   'Course' : ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'],                   'Location' : ['Saharanpur', 'Meerut', 'Agra',                                  'Saharanpur', 'Meerut']})  # counting the duplicatesdups = df.pivot_table(index = ['Course'], aggfunc ='size')  # displaying the duplicate Seriesprint(dups)
Output :
Across multiple columns : We will be using the pivot_table() function to count the duplicates across multiple columns. The columns in which the duplicates are to be found will be passed as the value of the index parameter as a list. The value of aggfunc will be ‘size’.
# importing the moduleimport pandas as pd   # creating the DataFramedf = pd.DataFrame({'Name' : ['Mukul', 'Rohan', 'Mayank',                              'Sundar', 'Aakash'],                   'Course' : ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'],                   'Location' : ['Saharanpur', 'Meerut', 'Agra',                                  'Saharanpur', 'Meerut']})  # counting the duplicatesdups = df.pivot_table(index = ['Course', 'Location'], aggfunc ='size')  # displaying the duplicate Seriesprint(dups)
Output
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
array::empty() in C++ STL - GeeksforGeeks

26 Mar, 2018
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays.
empty() function is used to check if the array container is empty or not.
Syntax :
arrayname.empty()
Parameters :
No parameters are passed.
Returns :
True, if array is empty
False, Otherwise

Examples:
Input  : myarray{1, 2, 3, 4, 5};
         myarray.empty();
Output : False

Input  : myarray{};
         myarray.empty();
Output : True

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// Non Empty array example// CPP program to illustrate// Implementation of empty() function#include <array>#include <iostream>using namespace std;  int main(){    array<int, 5> myarray{ 1, 2, 3, 4 };    if (myarray.empty()) {        cout << "True";    }    else {        cout << "False";    }    return 0;}
Output :
False

// Empty array example// CPP program to illustrate// Implementation of empty() function#include <array>#include <iostream>using namespace std;  int main(){    array<int, 0> myarray;    if (myarray.empty()) {        cout << "True";    }    else {        cout << "False";    }    return 0;}
Output :
True

cpp-array
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
std::string class in C++
Destructors in C++
C++ Library - <complex>

It implements the complex class to contain complex numbers in cartesian form and several functions and overloads to operate with them.
Following is the declaration for std::complex.
template< class T >
class complex;
T − Type of both the real and imaginary components of the complex number.
 Print
 Add Notes
 Bookmark this page
Difference between Confusion and Diffusion - GeeksforGeeks

03 Jun, 2019
Confusion and diffusion area unit the properties for creating a secure cipher. Each Confusion and diffusion area unit wont to stop the secret writing key from its deduction or ultimately for preventing the first message.
Confusion is employed for making uninformed cipher text whereas diffusion is employed for increasing the redundancy of the plain text over the foremost a part of the cipher text to create it obscure. The stream cipher solely depends on confusion, or else, diffusion is employed by each stream and block cipher.
Confusion = Substitution
a --> b
Caesar Cipher 


Diffusion = Transposition or Permutation
abcd --> dacb
          DES 
Let’s see the difference b/w Confusion and Diffusion:
cryptography
Computer Networks
Difference Between
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
GSM in Wireless Communication
Multiple Access Protocols in Computer Network
Stop and Wait ARQ
Difference between BFS and DFS
Class method vs Static method in Python
Stack vs Heap Memory Allocation
Difference between Process and Thread
Difference between var, let and const keywords in JavaScript
ASP Server.URLEncode Method - GeeksforGeeks

02 Mar, 2021
The ASP Server.URLEncode method is used to apply URL encoding rules to convert to a specified string. Below are given the URLEncode converts characters as follows: 
Spaces ( ) are converted to plus signs (+).
Non-alphanumeric characters are escaped to their hexadecimal representation.
Syntax: 
Server.URLEncode(string)
Parameter Values: It contains a string value that specifies the string to be encoded. 
Example: 
ASP
<%response.write(Server.URLEncode("https://www.geeksforgeeks.org"))%>
Output:  
https%3A%2F%2Fwww%2Egeeksforgeeks%2Eorg
ASP-Basics
ASP-Methods
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
Difference Between PUT and PATCH Request
How to execute PHP code using command line ?
How to redirect to another page in ReactJS ?
How to iterate through a dictionary in Python?

There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list.
>>> D1 = {1:'a', 2:'b', 3:'c'} 
>>> for k in D1.keys():
   print (k, D1[k])
1 a
2 b
3 c
There is also items() method of dictionary object which returns list of tuples, each tuple having key and value. Each tuple is then unpacked to two variables to print one dictionary item at a time.
>>> D1={1:'a', 2:'b', 3:'c'} 
>>> for k, v in D1.items():
   print (k, v)
1 a
2 b
3 c
Java Program for Iterative Merge Sort - GeeksforGeeks

12 Jan, 2018
Following is a typical recursive implementation of Merge Sort that uses last element as pivot.
// Recursive Java Program for merge sort import java.util.Arrays;public class GFG{    public static void mergeSort(int[] array)    {        if(array == null)        {            return;        }         if(array.length > 1)        {            int mid = array.length / 2;             // Split left part            int[] left = new int[mid];            for(int i = 0; i < mid; i++)            {                left[i] = array[i];            }                         // Split right part            int[] right = new int[array.length - mid];            for(int i = mid; i < array.length; i++)            {                right[i - mid] = array[i];            }            mergeSort(left);            mergeSort(right);             int i = 0;            int j = 0;            int k = 0;             // Merge left and right arrays            while(i < left.length && j < right.length)            {                if(left[i] < right[j])                {                    array[k] = left[i];                    i++;                }                else                {                    array[k] = right[j];                    j++;                }                k++;            }            // Collect remaining elements            while(i < left.length)            {                array[k] = left[i];                i++;                k++;            }            while(j < right.length)            {                array[k] = right[j];                j++;                k++;            }        }    }    // Driver program to test above functions.    public static void main(String[] args)    {        int arr[] = {12, 11, 13, 5, 6, 7};        int i=0;        System.out.println("Given array is");         for(i=0; i<arr.length; i++)            System.out.print(arr[i]+" ");         mergeSort(arr);         System.out.println("\n");        System.out.println("Sorted array is");         for(i=0; i<arr.length; i++)            System.out.print(arr[i]+" ");    }} // Code Contributed by Mohit Gupta_OMG
Please refer complete article on Iterative Merge Sort for more details!
Merge Sort
Java Programs
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Write Data into Excel Sheet using Java?
Python | Convert string to DateTime and vice-versa - GeeksforGeeks

30 Jun, 2020
Write a Python program to convert a given string to datetime and vice-versa.
Program to convert string to DateTime using strptime() function.
Examples:
Input : Dec 4 2018 10:07AM 
Output : 2018-12-04 10:07:00

Input : Jun 12 2013 5:30PM 
Output : 2013-06-12 17:30:00

strptime() is available in datetime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format.
Syntax:
datetime.strptime(date_string, format)
The arguments date_string and format should be of string type.
import datetime   # Function to convert string to datetimedef convert(date_time):    format = '%b %d %Y %I:%M%p' # The format    datetime_str = datetime.datetime.strptime(date_time, format)       return datetime_str   # Driver codedate_time = 'Dec 4 2018 10:07AM'print(convert(date_time))
Output:
2018-12-04 10:07:00
 Program to convert DateTime to stringExamples:
Input : 2018-12-04 10:07:00  
Output : Dec 4 2018 10:07:00AM 

Input : 2013-06-12 17:30:00Jun 12 2013 5:30PM 
Output : Jun 12 2013 5:30:00PM 

Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string.
Syntax:
datetime_object.strftime(format_str)
Another similar function is available in time module which converts a tuple or struct_time object to a string as specified by the format argument.
import time  # Function to convert string to datetimedef convert(datetime_str):    datetime_str = time.mktime(datetime_str)          format = "%b %d %Y %r" # The format    dateTime = time.strftime(format, time.gmtime(datetime_str))    return dateTime  # Driver codedate_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0)print(convert(date_time))
Output:
Dec 04 2018 10:07:00 AM
Akanksha_Rai
Python string-programs
python-string
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
sum() function in Python
Create a Pandas DataFrame from Lists
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Check that the String does not contain certain characters in Java

Let’s say the following is our string with special characters.
String str = "test*$demo";
Check for the special characters.
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
Now, if the bool value “val” is true, that would mean the special characters are in the string.
if (val == true)
System.out.println("Special characters are in the string.");
 Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String []args) {
      String str = "test*$demo";
      System.out.println("String: "+str);
      Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
      Matcher match = pattern.matcher(str);
      boolean val = match.find();
      if (val == true)
         System.out.println("Special characters are in the string.");
      else
         System.out.println("Special characters are not in the string.");
   }
}
String: test*$demo
Special characters are in the string.
The following is another example with a different input.
 Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
      Matcher match = pattern.matcher(str);
      boolean val = match.find();
      if (val == true)
         System.out.println("Special characters are in the string.");
      else
      System.out.println("Special characters are not in the string.");
   }
}
String: testdemo
Special characters are not in the string...
How to display mean inside boxplot created by using boxplot function in R?

A boxplot shows the median as a measure of center along with other values but we might want to compare the means as well. Therefore, showing mean with a point is likely to be preferred if we want to compare many boxplots. This can be done by using points(mean(“Vector_name”)), if we are plotting the columns of an R data frame then we will reference them instead of vector name.
Consider the below data and the boxplot −
 Live Demo
x<-runif(100,2,5)
boxplot(x)
Adding mean point to the boxplot −
points(mean(x),col="red")
map emplace() in C++ STL

In this article we will be discussing the working, syntax and examples of map::emplace() function in C++ STL.
Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.
The map::emplace( ) is a function which comes under <map> header file. This function constructs and inserts an element into the associated map container.
emplace() inserts the new element if the key of the element which is to be emplaced is unique. The insertion only happens if there is no element with the same key of the value which is to be inserted. This function works the same as insert() which copies and moves the existing object into the container.
If the element is successfully inserted the size of the container is increased by 1
map_name.emplace(Args&& args);
This function accepts the following parameter −
args − The arguments or values which we want to be emplaced or inserted.
If the insertion is successful then the function returns the iterator pointing to the new element which is inserted. Else it returns the iterator to equivalent value which is already present in the container.
map<char, int> newmap;
emplace( ‘a’, 1);
a
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.emplace(4, 50);
   TP_Map.emplace(2, 30);
   TP_Map.emplace(1, 10);
   TP_Map.emplace(1, 20);
   TP_Map.emplace(1, 30);
   cout<<"TP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++)
      cout << i->first << "\t" << i->second << endl;
   return 0;
}
TP Map is:
MAP_KEY    MAP_ELEMENT
1             10
2             30
4             50
Program to design parking system in Python

Suppose you want to design a parking system. A parking lot has three different kinds of parking spaces − big, medium, and small. And there are fixed number of slots for each size. Make a class called OurParkingSystem with of two methods −
constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class.
constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class.
addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot.
addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot.
The three slots big, medium, or small, are represented by 1, 2, and 3 respectively. The constraint is a car can only park in a parking space if carType is matched. If there is no space available, return false, otherwise park the car in that size space and return true.
If there are 2 spaces for big car, no space for medium car and 1 space for small car, then constructor call will be like OurParkingSystem(2, 0, 1), and if we call addCar like −
addCar(3) − add one small car and return true
addCar(2) − No space to add medium car so return false
addCar(3) − No space to add a new small car so return false
addCar(1) − add one big car and return true
addCar(1) − add another big car and return true
addCar(1) − No space for another big car so return false
To solve this, we will follow these steps −
Define a function constructor() . This will take big, medium, small
Define a function constructor() . This will take big, medium, small
sp := a list like [0,big,medium,small]
sp := a list like [0,big,medium,small]
Define a function addCar() . This will take carType
Define a function addCar() . This will take carType
if sp[carType] > 0, thensp[carType] := sp[carType] - 1return True
if sp[carType] > 0, then
sp[carType] := sp[carType] - 1
sp[carType] := sp[carType] - 1
return True
return True
return False
return False
Let us see the following implementation to get better understanding −
 Live Demo
class OurParkingSystem:
   def __init__(self, big, medium, small):
      self.sp = [0,big,medium,small]

   def addCar(self, carType):
      if(self.sp[carType] >0 ):
         self.sp[carType] -= 1
         return True
      return False

ps = OurParkingSystem(2, 0, 1)
print(ps.addCar(3))
print(ps.addCar(2))
print(ps.addCar(3))
print(ps.addCar(1))
print(ps.addCar(1))
print(ps.addCar(1))
ps.addCar(3)
ps.addCar(2)
ps.addCar(3)
ps.addCar(1)
ps.addCar(1)
ps.addCar(1)
True
False
False
True
True
False
PostgreSQL - SELECT Database

This chapter explains various methods of accessing the database. Assume that we have already created a database in our previous chapter. You can select the database using either of the following methods −
Database SQL Prompt
OS Command Prompt
Assume you have already launched your PostgreSQL client and you have landed at the following SQL prompt −
postgres=#

You can check the available database list using \l, i.e., backslash el command as follows −
postgres-# \l
                             List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges   
-----------+----------+----------+---------+-------+-----------------------
 postgres  | postgres | UTF8     | C       | C     | 
 template0 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 testdb    | postgres | UTF8     | C       | C     | 
(4 rows)

postgres-# 
Now, type the following command to connect/select a desired database; here, we will connect to the testdb  database.
postgres=# \c testdb;
psql (9.2.4)
Type "help" for help.
You are now connected to database "testdb" as user "postgres".
testdb=# 
You can select your database from the command prompt itself at the time when you login to your database. Following is a simple example −
psql -h localhost -p 5432 -U postgress testdb
Password for user postgress: ****
psql (9.2.4)
Type "help" for help.
You are now connected to database "testdb" as user "postgres".
testdb=# 
You are now logged into PostgreSQL testdb and ready to execute your commands inside testdb. To exit from the database, you can use the command \q.

    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
MongoDB query to sort by the sum of specified object inside inner array?

To sort by the sum of specified object inside inner array, use matchalongwithsort. Let us create a collection with documents −
> db.demo189.insertOne(
...   {
...      "_id" : 100,
...      "List" : [
...         {
...            "Value" : 10
...         },
..         .{
...            "Value" : 20
...         },
...         {
...            "Value" : 10
...         }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 100 }
> db.demo189.insertOne(
...   {
...      "_id" : 101,
...      "List" : [
...         {
...            "Value" : 10
...         },
...         {
...            "Value" : 10
...         },
...         {
...            "Value" : 10
...         }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo189.find();
This will produce the following output −
{ "_id" : 100, "List" : [ { "Value" : 10 }, { "Value" : 20 }, { "Value" : 10 } ] }
{ "_id" : 101, "List" : [ { "Value" : 10 }, { "Value" : 10 }, { "Value" : 10 } ] }
Following is the query to sort by the sum of specified object inside inner array − 
> db.demo189.aggregate([
...   { "$unwind" : "$List" },
...   { "$group" : {
...      "_id" : "$_id",
...      "total" : {
...         "$sum" : {
...            "$cond" : {
...               "if" : { "$eq" : [ "$List.Value", 10 ] },
...                  "then" : 1,
...               "else" : 0
...            }
...         }
...      },
...      "List" : {
...         "$push" : {
...            "Value" : "$List.Value"
...         }
...      }
...   }},
...   { "$sort" : { "total" : -1 } },
...   { "$project" : {
...      "List" : 1
...   }}
...])
This will produce the following output −
{ "_id" : 101, "List" : [ { "Value" : 10 }, { "Value" : 10 }, { "Value" : 10 } ] }
{ "_id" : 100, "List" : [ { "Value" : 10 }, { "Value" : 20 }, { "Value" : 10 } ] }
Factorial of a large number

In computers, variables are stored in memory locations. But the size of the memory location is fixed, so when we try to find the factorial of some greater value like 15! or 20! the factorial value exceeds the memory range and returns wrong results.
For calculation of large numbers, we have to use an array to store results. In each element of the array, is storing different digits of the result. But here we cannot multiply some number with the array directly, we have to perform manual multiplication process for all digits of the result array.
Input:
A big number: 50
Output:
Factorial of given number is:
30414093201713378043612608166064768844377641568960512000000000000
multiply(x, multiplicand)
Input: The number x, and the large multiplicand as an array.
Output: Result after multiplication.
Begin
   carry := 0
   for all digits i of multiplicand, do
      prod := i*x+carry
      i := prod mod 10
      carry := prod / 10
   done

   while carry ≠ 0, do
      insert (carry mod 10) at the end of multiplicand array
      carry := carry/10
   done
End
factorial(n)
Input: The number n.
Output: Find factorial of n.
Begin
   define result array.
   insert 1 in the result

   for i := 2 to n, do
      multiply(i, result)
   done

   reverse the result
   return result
End
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void multiply(int x, vector<int>&multiplicand) {    //multiply multiplicand with x
   int carry = 0;     // Initialize carry to 0
   vector<int>::iterator i;

   for (i=multiplicand.begin(); i!=multiplicand.end(); i++) {   //multiply x with all digit of multiplicand
      int prod = (*i) * x + carry;
      *i = prod % 10;       //put only the last digit of product
      carry  = prod/10;    //add remaining part with carry  
   }

   while (carry) {    //when carry is present
      multiplicand.push_back(carry%10);
      carry = carry/10;
   }
}

void factorial(int n) {
   vector<int> result;
   result.push_back(1);    //at first store 1 as result

   for (int i=2; i<=n; i++)
      multiply(i, result);   //multiply numbers 1*2*3*......*n

   cout << "Factorial of given number is: "<<endl;

   reverse(result.begin(), result.end());

   vector<int>::iterator it;    //reverse the order of result

   for(it = result.begin(); it != result.end(); it++)
      cout << *it;
}

int main() {
   factorial(50);
}
Factorial of given number is:
30414093201713378043612608166064768844377641568960512000000000000
Data Structures and Algorithms | Set 14 - GeeksforGeeks

05 Jul, 2018
Following questions have been asked in GATE CS 2008 exam.
1. We have a binary heap on n elements and wish to insert n more elements (not necessarily one after another) into this heap. The total time required for this is(A) Θ(logn)(B) Θ(n)(C) Θ(nlogn)(D) Θ(n2)
The worst case time complexity for insertion in a binary heap is O(Logn) (Refer Wiki). So inserting n elements in a heap of size n should take Θ(nlogn) time.But choice (B) seems to be more appropriate answer. One of the solution of O(n) complexity can be to take the ‘n’ elements of the heap and other ‘n’ elements together and construct heap in O(2n) = O(n). Thanks to pankaj for suggesting this solution.
2. The Breadth First Search algorithm has been implemented using the queue data structure. One possible order of visiting the nodes of the following graph is
(A) MNOPQR(B) NQMPOR(C) QMNPRO(D) QMNPOR
Answer (C)
3. Consider the following functions:
  f(n)   = 2^n
  g(n)   = n!
  h(n)   = n^logn 
Which of the following statements about the asymptotic behaviour of f(n), g(n), and h(n) is true?(A) f(n) = O(g(n)); g(n) = O(h(n))(B) f(n) = Ω(g(n)); g(n) = O(h(n))(C) g(n) = O(f(n)); h(n) = O(f(n))(D) h(n) = O(f(n)); g(n) = Ω(f(n))
Answer (D)
According to order of growth: h(n) < f(n) < g(n) (g(n) is asymptotically greater than f(n) and f(n) is asymptotically greater than h(n) )
We can easily see above order by taking logs of the given 3 functions
   lognlogn < n < log(n!)  (logs of the given f(n), g(n) and h(n)).
Note that log(n!) = Θ(nlogn)
4. The minimum number of comparisons required to determine if an integer appears more than n/2 times in a sorted array of n integers is(A) Θ(n)(B) Θ(logn)(C) Θ(log*n)(D) Θ(n)
Answer (B)
Please see the post Check for Majority Element in a sorted array for details.
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-2008
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
Differences between TCP and UDP
Semaphores in Process Synchronization
Difference between Process and Thread
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 1
Operating Systems | Set 1
Computer Networks | Set 2
Database Management Systems | Set 1
How to convert a String representation of a Dictionary to a dictionary in Python?

Dictionary object is easily convertible to string by str() function.
>>> D1={'1':1, '2':2, '3':3}
>>> D1
{'1': 1, '2': 2, '3': 3}
>>> str(D1)
"{'1': 1, '2': 2, '3': 3}"
To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function.
>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> s
"{'1': 1, '2': 2, '3': 3}"
>>> D2=eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}
Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.
>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> import ast
>>> D2=ast.literal_eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}
Setting the name of the axes in Pandas DataFrame - GeeksforGeeks

23 Jan, 2019
There are multiple operations which can be performed over the exes in Pandas. Let’s see how to operate on row and column index with examples.
For link to the CSV file used in the code, click here.
Code #1 : We can reset the name of the DataFrame index by using df.index.name attribute.
# importing pandas as pdimport pandas as pd  # read the csv file and create DataFramedf = pd.read_csv('nba.csv')  # Visualize the dataframeprint(df)
Output :
# set the index namedf.index.name = 'Index_name'  # Print the DataFrameprint(df)
Output :
 
Code #2 : We can reset the name of the DataFrame index by using df.rename_axis() function.
# importing pandas as pdimport pandas as pd  # read the csv file and create DataFramedf = pd.read_csv('nba.csv')  # reset the index namedf.rename_axis('Index_name', axis = 'rows')  # Print the DataFrameprint(df)
Output :
Code #1 : We can reset the name of the DataFrame column axes by using df.rename_axis() function.
# importing pandas as pdimport pandas as pd  # read the csv file and create DataFramedf = pd.read_csv('nba.csv')  # Visualize the dataframeprint(df)
Output :
As we can see in the output, column axes of the df DataFrame does not have any name. So, we will set the name using df.rename_axis() function.
# set the name of column axesdf.rename_axis('Column_Index_name', axis = 'columns')  # Print the DataFrameprint(df)
Output :
Python pandas-dataFrame
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
What are the differences between JavaScript Primitive Data Types and Objects?

Before beginning with the difference, let’s learn what are Primitive Datatypes. Primitive defines immutable values and introduced recently by ECMAScript standard.
JavaScript allows you to work with three primitive data types,
Numbers, eg. 3, 310.20 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as the object.After datatypes, let us discuss about Objects:
Objects 
In JavaScript, objects are considered a collection of properties. Identify properties using key values. It has two types:
Data Property 
It associates a key with a value.Let’s say we take an example of a string with primitive data type and object: 
For Primitive Datatype,
var str = "Demo string!";
For Object,
var str = new String("Demo string!");
Accessor Property
It associates a key with accessor functions. This is to store a value.
Python IMDbPY – Getting released year of movie from movie object - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can get the released year of movie from the movie object, we can get movie object with the help of search_movie and get_movie method to find movies.
search_movie method returns list and each element of list work as a dictionary similarly get_movie method return a movie object which work as dictionary i.e. they can be queried by giving the key of the data, here key will be year.
Syntax : movie[‘year’]
Here movie is the imdb Movie object
Return : It returns integer which is the release year
Below is the implementation
# importing the moduleimport imdb   # creating instance of IMDbia = imdb.IMDb()   # getting the movie with idsearch = ia.get_movie("0111161")  # getting movie yearyear = search['year']  # printing movie name and yearprint(search['title'] + " : " + str(year))
Output :
The Shawshank Redemption : 1994
Another example
# importing the moduleimport imdb   # creating instance of IMDbia = imdb.IMDb()   # getting the movie with namesearch = ia.search_movie("3 Idiots")  # getting movie yearyear = search[0]['year']  # printing movie name and yearprint(search[0]['title'] + " : " + str(year))
Output :
3 Idiots : 2009
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Lolcode - Loops

Loops are used in programming languages to execute a set of statements multiple times. For example, if you want to print the digit 5 for five times, then instead of writing the VISIBLE “5” statement five times, you can run a loop with single VISIBLE “5” statement for five times.
Simple loops are represented with IM IN YR <label> and IM OUTTA YR <label>. Loops defined in this way are infinite loops and they should be terminated with a GTFO break statement.
Iteration loops have the following structure−
IM IN YR <label> <any_operation> YR <any_variable> [TIL|WILE <expression>]
   <code block to execute inside the loop multiple times>
IM OUTTA YR <label>

Please note that inside the function body, UPPIN (increment by one), NERFIN (decrement by one), or any unary function can be used.
The TIL keyword calculates the expression as a TROOF: if it evaluates as FAIL, the loop continues once more, if it evaluates as WIN, then the loop execution stops, and continues after the matching IM OUTTA YR statement.
The WILE keyword is the opposite of TIL keyword, if the expression is WIN, execution continues, otherwise the loop exits.
HAI 1.2
I HAS A VAR ITZ 0
IM IN YR LOOPY UPPIN YR VAR TIL BOTH SAEM VAR AN 10
   VISIBLE SUM OF VAR AN 1
IM OUTTA YR LOOPY
KTHXBYE
When the above code is compiled on any LOLCODE compiler, or on our online codingground, this will produce the following output.
sh-
4.3$ lci main.lo
1

2

3

4

5

6

7

8

9

10

 Print
 Add Notes
 Bookmark this page