code-rag-bench/online-tutorials huggingface dataset:
Python | Delete elements with frequency atmost K

15 Apr, 2019
There are many methods that can be employed to perform the deletion in the list. Be it remove function, pop function and many other functions. But most of the times, we usually don’t deal with the simple deletion, but with certain constraints. This article discusses certain ways in which we can delete only those elements which occurs less than K times.
Method #1 : Using list comprehension + count()The idea applied here is to construct a new list using list comprehension and insert only those elements which occur more than K times. The count operation is done with the help of count function.
# Python3 code to demonstrate# remove elements less than and equal K # using list comprehension + count()  # initializing listtest_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]  # printing original listprint("The original list : " + str(test_list))  # initializing KK = 2  # using list comprehension + count()# remove elements less than K res = [ i for i in test_list if test_list.count(i) > K]  # print resultprint("The list removing elements less than and equal K  : " + str(res))
The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K  : [3, 2, 3, 3, 2, 2, 2]

 
Method #2 : Using Counter() + list comprehensionThis problem can be efficiently solved using the Counter function that precomputes the count of each elements in list so that the decision to keep or reject a particular element takes lesser time.
# Python3 code to demonstrate# remove elements less than and equal K # using Counter() + list comprehensionfrom collections import Counter  # initializing listtest_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]  # printing original listprint("The original list : " + str(test_list))  # initializing KK = 2  # using Counter() + list comprehension# remove elements less than K freq = Counter(test_list)res = [ele for ele in test_list if freq[ele] > K]  # print resultprint("The list removing elements less than and equal K  : " + str(res))
The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K  : [3, 2, 3, 3, 2, 2, 2]

Marketing
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Argument Coercion in C/C++ - GeeksforGeeks

26 Dec, 2018
Argument coercion is a feature of function prototypes by which the compiler implicitly converts the datatype of the arguments passed during the function call to match the datatype in the definition of the function.
It follows Argument promotion rules. Therefore a lower datatype maybe converted into a higher datatype but vice-versa is not true. This is because when a higher datatype is converted to a lower datatype it can result into loss or truncation of data.
The Promotion hierarchy for fundamental datatypes in C++ is:
Example: Take for Example the code given below consists of an add function that expects double arguments. But even when integer arguments are passed it works correctly. In case long double arguments are passed the code will give an error.
#include <iostream>using namespace std;  double add(double a, double b){    return a + b;}  int main(){    // Passing double arguments, as expected    cout << "Sum = " << add(2.4, 8.5) << endl;      // Passing int arguments, when double is expected    // This will lead to Argument Coercion    cout << "Sum = " << add(16, 18) << endl;      return 0;}
C-Data Types
cpp-data-types
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Executable Comments in Java - GeeksforGeeks

18 Apr, 2019
A comment is a statement that is not executed by the compiler or the interpreter, but before the lexical transformation of the program in the compiler, the contents of the program are encoded into ASCII to make the processing easier. Consider this program:
class Main{      public static void main(String[] args) {        // The comment below is magic..        // \u000d System.out.println("Geek Comment Executed!");    }}
This code will be executed and compiled successfully to produce the output.Output
Geek Comment Executed!

This successfully produces this output because java compiler before lexical transformation parses the Unicode character \u000d as a new line and the program gets transformed into:
class Main{          public static void main(String[] args) {        // The comment below is magic        //        System.out.println("Geek Comment Executed!");    }}
The Unicode character Shifts the print statement to the next line which is then executed like a normal java program. So, the question arises why the translation of Unicode escapes happens before any other source code processing?
1. Java source code can be written in any encoding which allows a wide range of characters in string, literal and comments.1. It makes processing by ASCII-based tools easier.2. This guarantees java Platform dependence which is the independence from supported character sets.3. This helps in documenting code in non-Latin languages.
Being able to write any Unicode character anywhere in the file is a neat feature, The fact that it can interfere with the semantics in such subtle ways is just a side-effect.
Let’s consider this java program:
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d
Output:
Hello World

This unicode program is converted into its representative values to produce “Hello World”Reference–https://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed?newsletter=1&nlcode=222379%7C1266
Akanksha_Rai
java-puzzle
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Data Structures | Heap | Question 1 - GeeksforGeeks

07 Nov, 2019
What is the time complexity of Build Heap operation. Build Heap is used to build a max(or min) binary heap from a given array. Build Heap is used in Heap Sort as a first step for sorting.(A) O(nLogn)(B) O(n^2)(C) O(Logn)(D) O(n)Answer: (D)Explanation: Following is algorithm for building a Heap of an input array A.
BUILD-HEAP(A) 
    heapsize := size(A); 
    for i := floor(heapsize/2) downto 1 
        do HEAPIFY(A, i); 
    end for 
END
Although the worst case complexity looks like O(nLogn), upper bound of time complexity is O(n). See following links for the proof of time complexity.
Time Complexity of building a heapQuiz of this Question
Data Structures
Data Structures-Heap
Heap Quizzes
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Tree Traversals | Question 4
Data Structures | Graph | Question 9
Data Structures | Stack | Question 1
Binary Search Tree | Set 3 (Iterative Delete)
Program to create Custom Vector Class in C++
Encryption and Decryption of String according to given technique
Data Structures | Hash | Question 5
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Data Structures | Tree Traversals | Question 5
Data Structures | Tree Traversals | Question 8
Python - Find all duplicate characters in string - GeeksforGeeks

19 Feb, 2021
Given a string, find all the duplicate characters which are similar to each others.
Let’s look at the example.Examples:
Input : hello
Output : l

Input : geeksforgeeeks
Output : e g k s

We have discussed a solution in below post.Print all the duplicates in the input string
We can solve this problem quickly using python Counter() method. Approach is very simple.
1) First create a dictionary using Counter method having strings as keys and their frequencies as values.2) Declare a temp variable.3) Print all the indexes from the keys which have value greater than 1.
from collections import Counter  def find_dup_char(input):      # now create dictionary using counter method    # which will have strings as key and their     # frequencies as value    WC = Counter(input)    j = -1                # Finding no. of  occurrence of a character    # and get the index of it.    for i in WC.values():        j = j + 1        if( i > 1 ):            print WC.keys()[j],  # Driver programif __name__ == "__main__":    input = 'geeksforgeeks'    find_dup_char(input)
Output:
e g k s

YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Find duplicates in a string using Counter method | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Z8Zc84SoXiY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Python string-programs
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
LinkedList set() Method in Java - GeeksforGeeks

10 Dec, 2018
The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method.
Syntax:
LinkedList.set(int index, Object element)

Parameters: This function accepts two parameters as shown in the above syntax and described below.
index: This is of integer type and refers to the position of the element that is to be replaced from the linked list.
element: It is the new element by which the existing element will be replaced and is of the same object type as the linked list.
Return Value: The method returns the previous value from the linked list that is replaced with the new value.
Below program illustrate the Java.util.LinkedList.set() method:
// Java code to illustrate set()import java.io.*;import java.util.LinkedList;  public class LinkedListDemo {    public static void main(String args[])    {        // Creating an empty LinkedList        LinkedList<String> list = new LinkedList<String>();          // Use add() method to add elements in the list        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");          // Displaying the linkedlist        System.out.println("LinkedList:" + list);                  // Using set() method to replace Geeks with GFG        System.out.println("The Object that is replaced is: " + list.set(2, "GFG"));                  // Using set() method to replace 20 with 50        System.out.println("The Object that is replaced is: " + list.set(4, "50"));                  // Displaying the modified linkedlist        System.out.println("The new LinkedList is:" + list);    }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new LinkedList is:[Geeks, for, GFG, 10, 50]

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
C library function - isgraph()

The C library function int isgraph(int c) checks if the character has graphical representation.
The characters with graphical representations are all those characters that can be printed except for whitespace characters (like ' '), which is not considered as isgraph characters.
Following is the declaration for isgraph() function.
int isgraph(int c);
c − This is the character to be checked.
c − This is the character to be checked.
This function returns non-zero value if c has a graphical representation as character, else it returns 0.
The following example shows the usage of isgraph() function.
#include <stdio.h>
#include <ctype.h>

int main () {
   int var1 = '3';
   int var2 = 'm';
   int var3 = ' ';
    
   if( isgraph(var1) ) {
      printf("var1 = |%c| can be printed\n", var1 );
   } else {
      printf("var1 = |%c| can't be printed\n", var1 );
   }
   
   if( isgraph(var2) ) {
      printf("var2 = |%c| can be printed\n", var2 );
   } else {
      printf("var2 = |%c| can't be printed\n", var2 );
   }
   
   if( isgraph(var3) ) {
      printf("var3 = |%c| can be printed\n", var3 );
   } else {
      printf("var3 = |%c| can't be printed\n", var3 );
   }
   
   return(0);
}
Let us compile and run the above program to produce the following result −
var1 = |3| can be printed
var2 = |m| can be printed
var3 = | | can't be printed


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
\nrightarrow - Tex Command

\nrightarrow - Used to create nrightarrow symbol.
{ \nrightarrow}
\nrightarrow command draws nrightarrow symbol.

\nrightarrow

↛



\nrightarrow

↛


\nrightarrow

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
PHP | preg_replace() Function - GeeksforGeeks

26 Jul, 2019
The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )
Parameters: This function accepts five parameters as mention above and describe below.
$pattern: This parameter contains the string element which is used to search the content and it can be a string or array of string.
$replacement: It is mandatory parameter which specifies the string or an array with strings to replace.
$subject: The string or an array with strings to search and replace.
$limit: This parameter specifies the maximum possible replacements for each pattern.
$count: It is optional parameter. This variable will be filled with the number of replacements done.
Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.
Below programs illustrate the preg_replace() function in PHP:
Program 1:
<?php  // PHP program to illustrate // preg_replace function  $string = 'November 01, 2018';$pattern = '/(\w+) (\d+), (\d+)/i';$replacement = '${1} 02, $3';  // print output of functionecho preg_replace($pattern, $replacement, $string);?>
November 02, 2018

Program 2 :
<?php  // PHP program to illustrate // preg_replace function$subject = array('1', 'GFG', '2','Geeks', '3', 'GCET', 'Contribute', '4'); $pattern = array('/\d/', '/[a-z]/', '/[1a]/'); $replace = array('X:$0', 'Y:$0', 'Z:$0');   // Print Result return by functionecho "preg_replace returns\n";print_r(preg_replace($pattern, $replace, $subject)); ?>
preg_replace returns
Array
(
    [0] => X:Z:1
    [1] => GFG
    [2] => X:2
    [3] => GY:eY:eY:kY:s
    [4] => X:3
    [5] => GCET
    [6] => CY:oY:nY:tY:rY:iY:bY:uY:tY:e
    [7] => X:4
)

Program 3:
<?php  // PHP program to illustrate // preg_replace function$count = 0;  // Display result after replace and count echo preg_replace(array('/\d/', '/\s/'),        '*', 'Geeks 4 Geeks', -1, $count);echo "\n" . $count;?>
Geeks***Geeks
3

Reference: http://php.net/manual/en/function.preg-replace.php
Akanksha_Rai
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Google Search Automation with Python Selenium

We can perform Google search automation with Selenium webdriver in Python. First of all, we shall locate the Google search box with the help of any of the locators like id, css, xpath, class, or name.
Then simulate the action of pressing the ENTER key with the help of Keys.ENTER/Keys.RETURN. To perform this operation, we have to use the method send_keys and then pass the parameter – Keys.RETURN /Keys.ENTER. Also, we have to add the statement - from selenium.webdriver.common.keys import Keys to use the Keys class.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.google.com/")
#identify search box
m = driver.find_element_by_name("q")
#enter search text
m.send_keys("Tutorialspoint")
time.sleep(0.2)
#perform Google search with Keys.ENTER
m.send_keys(Keys.ENTER)
What are the differences between current_window_handle and window_handles methods in Selenium with python?

There are differences between current_window_handle and window_handles methods in Selenium. Both are methods to handle multiple windows. They differences are listed below −
current_window_handleThis method fetches the handle of the present window. Thus it deals with the window in focus at the moment. It returns the window handle id as a string value.
current_window_handle
This method fetches the handle of the present window. Thus it deals with the window in focus at the moment. It returns the window handle id as a string value.
Syntax −
driver.current_window_handle
window_handlesThis method fetches all the handle ids of the windows that are currently open. The collection of window handle ids is returned as a set data structure.
window_handles
This method fetches all the handle ids of the windows that are currently open. The collection of window handle ids is returned as a set data structure.
Syntax −
driver.window_handles
w = driver.window_handles[2]
The above code gives the handle id of the second window open in the present session.
Code Implementation with current_window_handle
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com/windows")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Click Here").click()
#prints the window handle in focus
print(driver.current_window_handle)
#to close the browser
driver.quit()
Code Implementation with window_handles.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com/windows")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Click Here").click()
#prints the window handle in focus
print(driver.current_window_handle)
#to fetch the all handle ids of opened windows
chwnd = driver.window_handles;
# count the number of open windows in console
print("Total Windows : "+chwnd.size());
#to close the browser
driver.quit()
First-Fit Allocation in Operating Systems - GeeksforGeeks

28 Aug, 2020
For both fixed and dynamic memory allocation schemes, the operating system must keep list of each memory location noting which are free and which are busy. Then as new jobs come into the system, the free partitions must be allocated.
These partitions may be allocated by 4 ways:
1. First-Fit Memory Allocation
2. Best-Fit Memory Allocation
3. Worst-Fit Memory Allocation
4. Next-Fit Memory Allocation 
These are Contiguous memory allocation techniques.
First-Fit Memory Allocation:This method keeps the free/busy list of jobs organized by memory location, low-ordered to high-ordered memory. In this method, first job claims the first available memory with space more than or equal to it’s size. The operating system doesn’t search for appropriate partition but just allocate the job to the nearest memory partition available with sufficient size.
As illustrated above, the system assigns J1 the nearest partition in the memory. As a result, there is no partition with sufficient space is available for J3 and it is placed in the waiting list.
Advantages of First-Fit Memory Allocation:It is fast in processing. As the processor allocates the nearest available memory partition to the job, it is very fast in execution.
Disadvantages of First-Fit Memory Allocation :It wastes a lot of memory. The processor ignores if the size of partition allocated to the job is very large as compared to the size of job or not. It just allocates the memory. As a result, a lot of memory is wasted and many jobs may not get space in the memory, and would have to wait for another job to complete.
sarthakdandriyal3199
kakashi01
memory-management
Operating Systems-Memory Management
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Normal Forms in DBMS
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Semaphores in Process Synchronization
LRU Cache Implementation
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Introduction of Deadlock in Operating System
How to Create a vector of specific type and length in R ?

05 Apr, 2021
In this article, we will see how to create a vector of specified type and length in R programming language. To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector.
Syntax:
vector(class of the data object, length of the vector)
There is a very straightforward approach for this.
Steps –
Create vector of required type
Also pass the size to it
Here we can also check the type and size of the vector so created
Implementation combined with this approach paints a better picture.
Example 1:
R
# Create a vector of type integer, numeric class and length 5a <- vector( "integer" , 5 )b <- vector( "numeric" , 5 )  # Printing vector aprint(a)  # Printing the data type of the vector print(typeof(a))  # Printing the length of vector aprint(length(a))  # Printing vector bprint(b)  # Printing the data type of the vector bprint(typeof(b))  # Printing the length of vector bprint(length(b))
Output:
[1] 0 0 0 0 0
[1] “integer”
[1] 5
[1] 0 0 0 0 0
[1] “double”
[1] 5
Example 2:
R
# Create a vector of type logical and length 5a <- vector( "logical" , 5 )  # Printing vector aprint(a)  # Printing the data type of the vector print(typeof(a))  # Printing the length of vector aprint(length(a))
Output:
[1] FALSE FALSE FALSE FALSE FALSE
[1] “logical”
[1] 5
Example 3:
R
# Create a vector of type character and length 5a <- vector( "character" , 5 )  # Printing vector aprint(a)  # Printing the data type of the vector print(typeof(a))  # Printing the length of vector aprint(length(a))
Output:
[1] “” “” “” “” “”
[1] “character”
[1] 5
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Slim Framework | Installation and Configuration

10 May, 2022
Slim is a lightweight, easy to use and fast PHP framework used to develop the powerful website quickly with ease. Like other PHP frameworks, slim also supports routers, middlewares, bodyparser, page templates, encrypted cookies and much more. Prerequisites:
PHP installation on windowsEnvironment Setup To Run the ProjectComposer Software to install slim
PHP installation on windows
Environment Setup To Run the Project
Composer Software to install slim
Installation:
Go to your directory where XAMPP is installed and open htdocs folder. (In my case it is C:\xampp\htdocs).Open command prompt and navigate to current working directory as your current directory. Enter the command
Go to your directory where XAMPP is installed and open htdocs folder. (In my case it is C:\xampp\htdocs).
Open command prompt and navigate to current working directory as your current directory. 
Enter the command
mkdir project_name && cd project_name
This command will create a project folder with project_name and set the present working directory to it. Now enter the command
This command will create a project folder with project_name and set the present working directory to it. 
Now enter the command
composer require slim/slim:3.* 
(Here 3.* refers to version number) This will install the slim framework in the current directory. Now enter the command
(Here 3.* refers to version number) This will install the slim framework in the current directory. 
Now enter the command
notepad index.php
and click on yes. It will create a new file index.php and will open it for editing. Now type the following code in the file 
and click on yes. It will create a new file index.php and will open it for editing. 
Now type the following code in the file 
CPP
<?php require 'vendor/autoload.php'; $app = new \Slim\App;$app->get('/', function () {  echo 'Welcome to my slim app';});$app->run();?>
It is the code for our first slim application. Save the file and close it.Open xampp control panel and run the apache server.Now open a web browser and go to url -> http://localhost:81/project_name/ As you can see our first app is running on the server successfully.  You have successfully installed slim and have created your first app with that.
It is the code for our first slim application. 
Save the file and close it.
Open xampp control panel and run the apache server.
Now open a web browser and go to url -> http://localhost:81/project_name/ As you can see our first app is running on the server successfully.  You have successfully installed slim and have created your first app with that.
varshagumber28
how-to-install
PHP-Misc
Installation Guide
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to convert seconds into hours, minutes and seconds

28 Jan, 2019
Given an integer n (in seconds), convert it into hours, minutes and seconds.
Examples:
Input : 12345
Output : 3:25:45

Input : 3600
Output : 1:00:00

Approach #1 : Naive
This approach is simply a naive approach to get the hours, minutes and seconds by simple mathematical calculations.
# Python Program to Convert seconds# into hours, minutes and seconds  def convert(seconds):    seconds = seconds % (24 * 3600)    hour = seconds // 3600    seconds %= 3600    minutes = seconds // 60    seconds %= 60          return "%d:%02d:%02d" % (hour, minutes, seconds)      # Driver programn = 12345print(convert(n))
3:25:45

 Approach #2 : Alternate to the Naive approach
By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations.
# Python Program to Convert seconds# into hours, minutes and seconds  def convert(seconds):    min, sec = divmod(seconds, 60)    hour, min = divmod(min, 60)    return "%d:%02d:%02d" % (hour, min, sec)      # Driver programn = 12345print(convert(n))
3:25:45

 
Approach #3 : Using timedelta (Object of datetime module)
Datetime module provides timedelta object which represents a duration, the difference between two dates or times. datetime.timedelta can be used to represent seconds into hours, minutes and seconds format.
# Python Program to Convert seconds# into hours, minutes and secondsimport datetime  def convert(n):    return str(datetime.timedelta(seconds = n))      # Driver programn = 12345print(convert(n))
3:25:45

 Approach #4 : Using time.strftime()
time.strftime() gives more control over formatting. The format and time.gmtime() is passed as argument. gmtime is used to convert seconds to special tuple format that strftime() requires.
# Python Program to Convert seconds# into hours, minutes and seconds  import time  def convert(seconds):    return time.strftime("%H:%M:%S", time.gmtime(n))      # Driver programn = 12345print(convert(n))
03:25:45

date-time-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pass the value from child process to parent process

06 Dec, 2019
Prerequisite: Pipe() and Fork() BasicWrite a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process.
Examples: Suppose we have an array a[]={1, 2, 3, 4, 5} in child process, then output should be 1 2 3 4 5.
Input:  1 2 3 4 5
Output: 1 2 3 4 5

// C program for passing value from// child process to parent process#include <pthread.h>#include <stdio.h>#include <sys/types.h>#include <unistd.h> #include <stdlib.h> #include <sys/wait.h>#define MAX 10  int main(){    int fd[2], i = 0;  pipe(fd);  pid_t pid = fork();     if(pid > 0) {      wait(NULL);        // closing the standard input       close(0);        // no need to use the write end of pipe here so close it      close(fd[1]);          // duplicating fd[0] with standard input 0      dup(fd[0]);       int arr[MAX];        // n stores the total bytes read successfully      int n = read(fd[0], arr, sizeof(arr));      for ( i = 0;i < n/4; i++)           // printing the array received from child process          printf("%d ", arr[i]);   }   else if( pid == 0 ) {      int arr[] = {1, 2, 3, 4, 5};        // no need to use the read end of pipe here so close it      close(fd[0]);          // closing the standard output      close(1);            // duplicating fd[0] with standard output 1      dup(fd[1]);        write(1, arr, sizeof(arr));  }     else {      perror("error\n"); //fork()  }} 
Steps for executing above code:
To compile, write gcc program_name.c
To run, write ./a.out
nidhi_biet
Processes & Threads
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File Allocation Methods
Memory Management in Operating System
Different approaches or Structures of Operating Systems
Logical and Physical Address in Operating System
Segmentation in Operating System
Structures of Directory in Operating System
Difference between Internal and External fragmentation
Process Table and Process Control Block (PCB)
Introduction of System Call
Deadlock Detection And Recovery
Python | Create a digital clock using Tkinter

28 Apr, 2022
As we know Tkinter is used to create a variety of GUI (Graphical User Interface) applications. In this article we will learn how to create a Digital clock using Tkinter.  
Prerequisites: -> Python functions -> Tkinter basics (Label Widget) -> Time module  
 
How to Create a Digital Clock Using Python? | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersHow to Create a Digital Clock Using Python? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1INA9AmaDtQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Using Label widget from Tkinter and time module : In the following application, we are going to use Label widget and also going to use time module which we will use to retrieve system’s time.Below is the implementation:  
Python3
# importing whole modulefrom tkinter import * from tkinter.ttk import *  # importing strftime function to# retrieve system's timefrom time import strftime  # creating tkinter windowroot = Tk()root.title('Clock')  # This function is used to # display time on the labeldef time():    string = strftime('%H:%M:%S %p')    lbl.config(text = string)    lbl.after(1000, time)  # Styling the label widget so that clock# will look more attractivelbl = Label(root, font = ('calibri', 40, 'bold'),            background = 'purple',            foreground = 'white')  # Placing clock at the centre# of the tkinter windowlbl.pack(anchor = 'center')time()  mainloop()
Output:  
 
 
anikaseth98
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript SyntaxError – Invalid regular expression flag “x”

24 Jul, 2020
This JavaScript exception invalid regular expression flag occurs if the flags, written after the second slash in RegExp literal, are not from either of (g, i, m, s, u, or y).
Message:
SyntaxError: Syntax error in regular expression (Edge) 
SyntaxError: invalid regular expression flag "x" (Firefox)
SyntaxError: Invalid regular expression flags (Chrome)

Error Type:
SyntaxError

Cause for Error: Somewhere in the code, There are regular expression flags that are not valid.
Example 1: This example has valid RegExp flags.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        var patt = /GeeksforGeeks/i;        var str = 'This is GeeksforGeeks';        document.write(str.match(patt));    </script></body></html>
Output:
GeeksForGeeks

Example 2: In this example, After second slash ‘GFG’ is used as a flag which is invalid.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        var patt = /Geek/GFG;        var str = 'This is GeeksforGeeks';        document.write(str.match(patt));    </script></body></html>
Output(in console):
SyntaxError: Invalid regular expression flags

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
GATE | GATE-CS-2017 (Set 1) | Question 15 - GeeksforGeeks

28 Jun, 2021
The following functional dependencies hold true for the relational schema R{V, W, X, Y, Z}:
V -> W
VW -> X
Y -> VX
Y -> Z

Which of the following is irreducible equivalent for this set of functional dependencies?
(A) A(B) B(C) C(D) DAnswer: (A)Explanation: Given
V -> W
VW -> X
Y -> VX
Y -> Z
We need to find the minimal cover of these FDs
Option B. W->X can  not implied by the given FDs, so incorrect
Option C. Y->X can be implied from Y->V and V->X, hence redundant
Option D. W->X can  not implied by the given FDs, so incorrect
Option A. Minimal cover of dependencies that can be extracted out as
V -> WV -> XY -> VY -> Z
V -> W
V -> X
Y -> V
Y -> Z
Therefore, option A is most appropriate.
Alternate Solution
Irreducible equivalent functional dependency is minimal cover.Given,
  {V → W, VW → X, Y → VX, Y → Z}

W extraneous from VW, since we have V → W,
= {V → W, V → X, Y → VX, Y → Z}

X extraneous from VX, since we have V → X,
=  {V → W, V → X, Y → V, Y → Z}

This explanation is contributed by Mithlesh UpadhyayQuiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
Tryit Editor v3.7

Tryit: Bottom tooltip with top arrow
How to calculate the Percentage of a column in Pandas ? - GeeksforGeeks

28 Jul, 2020
A Percentage is calculated by the mathematical formula of dividing the value by the sum of all the values and then multiplying the sum by 100. This is also applicable in Pandas Dataframes. Here, the pre-defined sum() method of pandas series is used to compute the sum of all the values of a column.
Syntax: Series.sum()
Return: Returns the sum of the values.
Formula: 
df[percent] = (df['column_name'] / df['column_name'].sum()) * 100

Example 1: 
Python3
# Import required librariesimport pandas as pdimport numpy as np   # Dictionarydf1 = {     'Name': ['abc', 'bcd', 'cde',             'def', 'efg', 'fgh',             'ghi'],     'Math_score': [52, 87, 49,                   74, 28, 59,                   48]}   # Create a DataFramedf1 = pd.DataFrame(df1,                    columns = ['Name',                             'Math_score'])  # Calculating Percentagedf1['percent'] = (df1['Math_score'] /                   df1['Math_score'].sum()) * 100  # Show the dataframedf1
Output:  
Example 2: 
Python3
# Import pandas libraryimport pandas as pd   # Dictionarydf1 = {     'Name': ['abc', 'bcd', 'cde',             'def', 'efg', 'fgh',             'ghi'],      'Math_score': [52, 87, 49,                    74, 28, 59,                    48],       'Eng_score': [34, 67, 25,                     89, 92, 45,                    86]}   # Create a DataFramedf1 = pd.DataFrame(df1,                    columns = ['Name',                   'Math_score','Eng_score'])  # Calculate Percentagedf1['Eng_percent'] = (df1['Eng_score'] /                       df1['Eng_score'].sum()) * 100# Show the dataframedf1
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Multi Threading Models in Process Management - GeeksforGeeks

31 May, 2021
Multi threading-It is a process of multiple threads executes at same time.
Many operating systems support kernel thread and user thread in a combined way. Example of such system is Solaris. Multi threading model are of three types.  
Many to many model.
Many to one model.
one to one model.
Many to Many Model 
In this model, we have multiple user threads multiplex to same or lesser number of kernel level threads. Number of kernel level threads are specific to the machine, advantage of this model is if a user thread is blocked we can schedule others user thread to other kernel thread. Thus, System doesn’t block if a particular thread is blocked. 
It is the best multi threading model.
 
Many to One Model 
In this model, we have multiple user threads mapped to one kernel thread. In this model when a user thread makes a blocking system call entire process blocks. As we have only one kernel thread and only one user thread can access kernel at a time, so multiple threads are not able access multiprocessor at the same time. 
The thread management is done on the user level so it is more efficient.
 
One to One Model In this model, one to one relationship between kernel and user thread. In this model multiple thread can run on multiple processor. Problem with this model is that creating a user thread requires the corresponding kernel thread. 
As each user thread is connected to different kernel , if any user thread makes a blocking system call, the other user threads won’t be blocked.
 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
akshittrivedi1005
Processes & Threads
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Program for Round Robin scheduling | Set 1
Introduction of Deadlock in Operating System
Introduction of Operating System - Set 1
CPU Scheduling in Operating Systems
Disk Scheduling Algorithms
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Preemptive and Non-Preemptive Scheduling
Scala Set intersect() method with example - GeeksforGeeks

18 Oct, 2019
The intersect() method is utilized to compute the intersection between two sets.
Method Definition: def intersect(that: Set[A]): Set[A]
Return Type: It returns a set containing the elements present in both the sets.
Example #1:
// Scala program of intersect() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(1, 2, 3, 4, 5)                   val s2 = Set(11, 12, 13, 4, 5)                   // Applying intersect method         val s3 = s1.intersect(s2)                   s3.foreach(x => println(x))    } } 
5
4

Example #2:
// Scala program of intersect() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(1, 2, 3, 4, 5)                   val s2 = Set(11, 2, 3, 4, 5)                   // Applying intersect method         val s3 = s1.intersect(s2)                   s3.foreach(x => println(x))    } } 
5
2
3
4

Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Operators in Scala
Scala Constructors
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Map get() method with example
Scala String substring() method with example
Scala String replace() method with example
Lambda Expression in Scala
Break statement in Scala
How to declare Block-Scoped Variables in JavaScript?

To declare block scoped variables, we use the keyword let and const introduced in ES2015.
Following is the code showing declaring black scoped variables in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Declaring block scoped variables</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to declare and display block scoped variables</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");{
      let a = 22;
      const b = 44;
      sampleEle.innerHTML = "let a = " + a + "<br>";
      sampleEle.innerHTML += "const b = " + b + "<br>";
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      try {
         a + b;
      }
      catch (err) {
         resEle.innerHTML = "a+b = " + err;
      }
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
Matplotlib.figure.Figure.set_frameon() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_frameon() method figure module of matplotlib library is used to set the width of the figure in inches.
Syntax: set_frameon(self, b)
Parameters: This method accept the following parameters that are discussed below:
b : This parameter contains the boolean value.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_frameon() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np         fig = plt.figure()        ax = Subplot(fig, 111) fig.add_subplot(ax)    fig.set_frameon(True)     fig.suptitle("""matplotlib.figure.Figure.set_frameon()function Example\n\n""", fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np           fig = plt.figure(figsize =(7, 6))         ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])      xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))     fig.set_frameon(False)     fig.suptitle("""matplotlib.figure.Figure.set_frameon()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python