code-rag-bench/online-tutorials huggingface dataset:
ISNULL() Function in SQL Server - GeeksforGeeks

21 Jan, 2021
ISNULL() :
This function in SQL Server is used to return the value given, in case the stated expression is NULL. Moreover, in case the given expression is not NULL then it returns the stated expression.
Features :
This function is used to find the given value, in case the expression given is NULL.
This function is used to find the given expression, in case the expression given is not NULL.
This function comes under Advanced Functions.
This function accepts two parameters namely expression, and value.
Syntax :
ISNULL(expression, value)
Parameter :
This method accepts two parameters.
expression –The specified expression which is to be checked if it’s NULL or not.
value –The specified value which is to be returned, in case the expression is NULL.
Returns :
It returns the value given, in case the stated expression is NULL else it returns the stated expression if the given expression is not NULL.
Example-1 :
Using ISNULL() function and getting the output.
SELECT ISNULL('gfg', 'Geeks');
Output :
gfg
Here, the expression is returned as the given value is not NULL.
Example-2 :
Using ISNULL() function and getting the output.
SELECT ISNULL(NULL, 'Geeks');
Output :
Geeks
Here, the expression is NULL so, the specified value is returned as output.
Example-3 :
Using ISNULL() function and getting the output using a variable.
DECLARE @exp VARCHAR(50);
SET @exp = 'geeksforgeeks';
SELECT ISNULL(@exp, 150);
Output :
geeksforgeeks
Example-4 :
Using ISNULL() function and getting the output using variables.
DECLARE @exp VARCHAR(50);
DECLARE @val VARCHAR(50);
SET @exp = NULL;
SET @val = 'GFG';
SELECT ISNULL(@exp, @val);
Output :
GFG
Application :
This function is used to find the value given, in case the stated expression is NULL else it finds the stated expression if the given expression is not NULL.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
Displaying horizontal bar graphs using Matplotlib

In this program, we will plot a bar graph using the matplotlib library. The most important Step in solving matplotlib related problems using the matplotlib library is importing the matplotlib library. The syntax is:
import matplotlib.pyplot as plt
Pyplot is a collection of command style functions that make Matplotlib work like MATLAB. We will use the function barh() for plotting the horizontal bar charts
Step 1: Define a list of values.
Step 2: Use the barh() function in the matplotlib.pyplot library and define different parameters like height width, etc.
Step 3: Label the axes using xlabel() and ylabel().
Step 3: Plot the graph using show().
import matplotlib.pyplot as plt

data_x = ['Mumbai', 'Delhi', 'Ahmedabad', 'Banglore']
data_y = [40, 35, 29, 32]

plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("BAR PLOT")
plt.barh(data_x, data_y, color='red')
plt.show()
How to Make USB Rubber Ducky at Home? - GeeksforGeeks

08 Jul, 2020
USB Rubber ducky is an HID device that looks similar to a USB Pen drive. It may be used to inject keystroke into a system, used to hack a system, steal victims essential and credential data can inject payload to the victim’s computers. The main important thing about USB Rubber ducky is that it cannot be detected by any Anti-Virus or Firewall as it acts as an HID device. 
Android mobiles can also be used to make a USB rubber ducky, if an Android device is rooted we may use it as a Rubber ducky device. And can perform all the operations that an original ducky can perform. 
To Make USB rubber ducky from android : 
Android mobile must be rooted
Kali net hunter installed on the device
In this article, we must be using some other components to create a USB Rubber Ducky at home. 
Material Requirements
Arduino based boardUSB connectorArduino IDE
Arduino based board
USB connector
Arduino IDE
Step 1: First of all download Arduino IDE from the link, and install the software like any other software you install on windows. 
 
Step 2: Connect the Arduino board to the computer using the USB connector and open the IDE. 
Step 3: Now from the Payload list choose according to your task. 
Step 4: Convert the code that you have chosen to make executable in Arduino here. 
Script for turning off the Windows Defender 
REM turn off windows defender then clear action center
REM author:geeksforgeeks
REM You take responsibility for any laws you break with this, I simply point out the security flaw
REM start of script
REM let the HID enumerate
DELAY 2000
ESCAPE
DELAY 100
CONTROL ESCAPE
DELAY 100
STRING Windows Defender Settings
ENTER
DELAY 2000
REM why TAB and HOME?
TAB
DELAY 50
REM why TAB and HOME?HOME
DELAY 50
ALT F4
DELAY 3200
REM windows + a = ????
GUI a 
DELAY 500
ENTER
DELAY 100
GUI a

Step 5:In the Arduino IDE creates a new project, by clicking on File–> New project. 
Step 6: After converting to new code adding to the Arduino IDE, now select the board which you are using. Tools–>Board–>Your board. 
Step 7: Click on the project and choose the port, where Arduino is connected. Tools–>Port–>Your Port. 
Step 8: Now when the board is connected, enter the code or payload you want to work with. 
Step 9: Now verify and compile your code. Sketch–>verify/compile. 
Step 10: After compiling, upload the code to the Arduino device. 
Whenever you will Connect this board with any computer it works as a USB rubber ducky and executes the payload written. You can Check about USB rubber ducky in Details Here.
GBlog
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
DFA for exactly one of a and at least one of b - GeeksforGeeks

02 Dec, 2021
Deterministic Finite Automata (DFA) is defined as an abstract mathematical concept which is used to solve various specific problems in different software and hardware.In this type of problems we have some given parameters according to which we should design DFA. 
In this article,two instructions are given: 
DFA should have one of a  
DFA should have at least one b  
This DFA should accept the strings such as ab, ba, abb, bab, bba, abbb, babb, bbab, bbba, abbbb.... etc but it should not accept string such as a, b, bb, bbb, aabb, ababa... etc. 
Designing step-by-step : 
Step-1: Take a initial state A,and smallest possible string are ab and ba, if A takes ‘a’ as first input alphabet it goes to state B and if A takes ‘b’ as first input alphabet it goes to state C. 
 
Step-2: Now think about state B, if it takes input alphabet ‘a’,it breaks our condition of only one ‘a’ but if takes input alphabet ‘b’ it makes a acceptable string and now it goes to state D which is set to final state. 
 
Step-3: On state C if it can take any numbers of ‘b’ which is possible and it can also take ‘a’ as input alphabet.On alphabet ‘b’ it remains on same state but on input ‘a’ it goes to state E which will set to final state. 
 
Step-4: Input alphabet ‘a’ of state B breaks the condition so it goes to some dead state(Q). 
 
Step-5: Till now, our machine accepts string which are end from ‘a’ and ‘ab’.But what about if ‘a’ comes in middle such as bab,babb,bbab etc and what if there are many ‘b’ in the end.To do that give self loop of ‘b’ to both final state and send their ‘a’ to dead state. 
 
Note – Input alphabets of dead state is going to dead state only that is why these are not showing in diagrams. 
Transition Table and Transition Rules of above diagram.  
finite set of states = {A, B, C, D, E, Q} 
In transition table initial state is represented by → and the final state are E and D.  
set of input alphabets = {a, b} 
 
 
shivamtyagi0918
varshagumber28
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Introduction of Process Synchronization
Turing Machine in TOC
Introduction of Pushdown Automata
Difference between DFA and NFA
Introduction of Finite Automata
Construct Pushdown Automata for given languages
Perl | glob() Function - GeeksforGeeks

12 Jun, 2019
glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it.
Syntax: glob(Directory_name/File_type);
Parameter: path of the directory of which files are to be printed.
Returns: the list of files present in the given directory
Example 1: Printing names of all the files in the directory
#!/usr/bin/perl  # To store the files# from the directory in the array@files = glob('C:/Users/GeeksForGeeks/Folder/*');  # Printing the created arrayprint "@files\n";
Output:Above example will print all the files of the requested directory.
Example 2: Printing names of the specific files in the directory
#!/usr/bin/perl  # To store the files of a specific extension# from the directory in the array@Array = glob('C:/Users/GeeksForGeeks/Folder/*.txt');  # Printing the created arrayprint "@Array\n";
Output:Above example will print all the files of the requested directory that end with .txt extension.
Perl-File-Functions
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | length() Function
Perl | join() Function
Perl | Basic Syntax of a Perl Program
Perl | Boolean Values
Perl | sleep() Function
Perl | Subroutines or Functions
Python | Last occurrence of some element in a list - GeeksforGeeks

30 Dec, 2018
There are many ways to find out the first index of element in the list as Python in its language provides index() function that returns the index of first occurrence of element in list. But if one desires to get the last occurrence of element in list, usually a longer method has to be applied.
Let’s discuss certain shorthands to achieve this particular task.
Method #1 : Using join() + rfind()This is usually the hack that we can employ to achieve this task. Joining the entire list and then employing string function rfind() to get the first element from right i.e last index of element in list.
# Python3 code to demonstrate # to get last element occurrence# using join() + rfind()  # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',                            'g', 'e', 'e', 'k', 's']  # using join() + rfind()# to get last element occurrenceres = ''.join(test_list).rindex('e')  # printing resultprint ("The index of last element occurrence: " + str(res))
The index of last element occurrence: 10

 Method #2 : Using List Slice + index()Using list slicing we reverse the list and use the conventional index method to get the index of first occurrence of element. Due to the reversed list, the last occurrence is returned rather than the first index of list.
# Python3 code to demonstrate # to get last element occurrence# using List Slice + index()  # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',                            'g', 'e', 'e', 'k', 's']  # using List Slice + index()# to get last element occurrenceres = len(test_list) - 1 - test_list[::-1].index('e')  # printing resultprint ("The index of last element occurrence: " + str(res))
The index of last element occurrence: 10

 Method #3 : Using max() + enumerate()We use enumerate function to get the list of all the elements having the particular element and then max() is employed to get max i.e last index of the list.
# Python3 code to demonstrate # to get last element occurrence# using max() + enumerate()  # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',                            'g', 'e', 'e', 'k', 's']  # using max() + enumerate()# to get last element occurrenceres = max(idx for idx, val in enumerate(test_list)                                     if val == 'e')  # printing resultprint ("The index of last element occurrence: " + str(res))
The index of last element occurrence: 10

Python list-programs
Python
Python Programs
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
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Why use Guzzle Instead of cURL in PHP ? - GeeksforGeeks

17 Jan, 2022
What is cURL? cURL is a module in PHP with we can use libcurl. The libcurl is a library that is used in PHP to create connection and communicate with various kinds of different servers which may have different type of protocols. cURl provide us various pre-built functions like – curl_init(), curl_setopt(), curl_exec(), curl_close().Limitations of cURL:  
cURL does not support any recursive download logic.
cURL requires extra options to download.
Does not provide us with asynchronus and synchronous requests.
Example: These are the request made by using cURL. 
PHP
<?php> // Get cURL resource$curl = curl_init();// Set some optionscurl_setopt($ch, CURLOPT_POST,    "https://jsonplaceholder.typicode.com/users"); curl_setopt($ch, CURLOPT_POST, false) ; curl_setopt($ch, CURLOPT_RETURNTANSFER, false) ;$result = curl_exec($ch);curl_close($ch); ?>
Output:  
What is Guzzle? Guzzle is a Microframework (abstraction layer) that is a PHP HTTP client due to which the HTTP request is sent easily and it is trivial to integrate with web services. Guzzle can be used with any HTTP handler like cURL, socket, PHP’s stream wrapper. Guzzle by default uses cURL as Http handler. Why use Guzzle Instead of cURL in PHP?  
It provides easy user interface.
Guzzle can use various kinds of HTTP clients .
It allows us with the facility of asynchronus and synchronous requests.
Guzzle has built-in unit testing support which makes it easier to write unit tests for app and mock the http requests.
Example: These are the request made by using Guzzle. 
PHP
<?php use GuzzleHTTP\Client;require '>>/vendor/autoload.php'; $client = new Client([    'base_uri'=>'http://httpbin.org',    'timeout' => 2.0]); $response = $client->request('GET', 'ip'); echo $response->getStatusCOde(), "<br>";$body = $response->getBody();echo $body->getContents(), "<br>"; echo "<pre>";print_r(get_class_methods($body));echo "</pre>";echo "<pre>";print_r(get_class_methods($response));echo "</pre>";?>
Output:  
 
saurabh1990aror
PHP-Misc
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
Different ways for passing data to view in Laravel
How to pass form variables from one page to other page in 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?
Python - Write "GFG" using Turtle Graphics - GeeksforGeeks

03 Jun, 2020
IN this article we will learn how to write “GFG” using Turtle Graphics in Python. For that lets first know what is Turtle Graphics.
backward(length): moves the pen in the backward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
import the turtle modules.import turtle
import turtle
Get a screen to draw onws=turtle.Screen()
ws=turtle.Screen()
Define an instance for turtle.
for printing G we have to make a semicircle and then complete it by rotating the turtle and moving it forward.
Then for F move pen up using  penup() , then goto() to desired coordinates, then pen it down for drawing using pendown() and draw F.
for remaining G go to other coordinates and do same as done for 1st G.
Below is the python implementation for the above approach:
Python3
#python program for printing "GFG"#importing turtle modulesimport turtle  #setting up workscreenws=turtle.Screen()  #defining turtle instancet=turtle.Turtle()  #turtle pen will be of "GREEN" colort.color("Green")  #setting width of pent.width(3)    #for printing letter "G"for x in range(180):    t.backward(1)    t.left(1)t.right(90)t.forward(50)t.right(90)t.forward(30)t.right(90)t.forward(50)    #for printing letter "F"t.penup()t.goto(40,0)t.pendown()t.forward(110)t.goto(40,0)t.left(90)t.forward(50)t.penup()t.goto(40,-50)t.pendown()t.forward(40)    #for printing letter "G"t.penup()t.goto(150,0)t.pendown()for x in range(180):    t.backward(1)    t.left(1)t.right(90)t.forward(50)t.right(90)t.forward(30)t.right(90)t.forward(50)
Python-turtle
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Find last index of a character in a string in C++

Suppose we have a string str. We have another character ch. Our task is to find the last index of ch in the string. Suppose the string is “Hello”, and character ch = ‘l’, then the last index will be 3.
To solve this, we will traverse the list from right to left, if the character is not same as ‘l’, then decrease index, if it matches, then stop and return result.
#include<iostream>
using namespace std;
int getLastIndex(string& str, char ch) {
   for (int i = str.length() - 1; i >= 0; i--)
      if (str[i] == ch)
         return i;
   return -1;
}
int main() {
   string str = "hello";
   char ch = 'l';
   int index = getLastIndex(str, ch);
   if (index == -1)
      cout << "Character not found";
   else
      cout << "Last index is " << index;
}
Last index is 3
acpi_available command in Linux with examples - GeeksforGeeks

04 Apr, 2019
acpi_available is a command in Linux which test whether ACPI (Advanced Configuration and Power Interface) subsystem is available or not. It has three return statuses:
0 : It means ACPI subsystem is available.
1 : It means ACPI subsystem is not available.
2 : It means some usage error has occured.
Syntax:
$ acpi_available
Example 1: Here, echo $? is a command which is used to see the last return status.
Example 2: Here, we create a false error and then displayed return status.
Options:
info acpi_available : It displays help information.Example:
Example:
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Batch Script - DEL

This batch command deletes files and not directories.
del [filename]

The following example shows the different variants of the del command.
@echo off 
Rem Deletes the file lists.txt in C:\ 
del C:\lists.txt 
Rem Deletes all files recursively in all nested directories
del /s *.txt 
Rem Deletes all files recursively in all nested directories , but asks for the 
confirmation from the user first 
Del /p /s *.txt
All actions are performed as per the remarks in the batch file.
 Print
 Add Notes
 Bookmark this page
Teradata - User Management

This chapter discussed the various strategies of user management in Teradata.
A user is created using CREATE USER command. In Teradata, a user is also similar to a database. They both can be assigned space and contain database objects except that the user is assigned a password.
Following is the syntax for CREATE USER.
CREATE USER username 
AS  
[PERMANENT|PERM] = n BYTES 
PASSWORD = password 
TEMPORARY = n BYTES 
SPOOL = n BYTES;

While creating a user, the values for user name, Permanent space and Password is mandatory. Other fields are optional.
Following is an example to create the user TD01.
CREATE USER TD01 
AS  
PERMANENT = 1000000 BYTES 
PASSWORD = ABC$124 
TEMPORARY = 1000000 BYTES 
SPOOL = 1000000 BYTES;
While creating a new user, the user may be assigned to an account. ACCOUNT option in CREATE USER is used to assign the account. A user may be assigned to multiple accounts.
Following is the syntax for CREATE USER with account option.
CREATE USER username 
PERM = n BYTES 
PASSWORD = password 
ACCOUNT = accountid

The following example creates the user TD02 and assigns the account as IT and Admin.
CREATE USER TD02 
AS  
PERMANENT = 1000000 BYTES 
PASSWORD = abc$123 
TEMPORARY = 1000000 BYTES 
SPOOL = 1000000 BYTES 
ACCOUNT = (‘IT’,’Admin’);
The user can specify the account id while logging into Teradata system or after being logged into the system using SET SESSION command.
.LOGON username, passowrd,accountid 
OR 
SET SESSION ACCOUNT = accountid 

GRANT command is used to assign one or more privileges on the database objects to the user or database.
Following is the syntax of the GRANT command.
GRANT privileges ON objectname TO username;

Privileges can be INSERT, SELECT, UPDATE, REFERENCES.
Following is an example of GRANT statement.
GRANT SELECT,INSERT,UPDATE ON Employee TO TD01;
REVOKE command removes the privileges from the users or databases. The REVOKE command can only remove explicit privileges.
Following is the basic syntax for REVOKE command.
REVOKE [ALL|privileges] ON objectname FROM username;

Following is an example of REVOKE command.
REVOKE INSERT,SELECT ON Employee FROM TD01;
 Print
 Add Notes
 Bookmark this page
Finding the nth element of the lucas number sequence in JavaScript

Lucas numbers are numbers in a sequence defined like this −
L(0) = 2
L(1) = 1
L(n) = L(n-1) + L(n-2)
We are required to write a JavaScript function that takes in a number n and return the nth lucas number.
Following is the code −
 Live Demo
const num = 21;
const lucas = (num = 1) => {
   if (num === 0)
      return 2;
   if (num === 1)
      return 1;
   return lucas(num - 1) +
      lucas(num - 2);
};
console.log(lucas(num));
Following is the console output −
24476
What are Chrome Flags or Experiments? - GeeksforGeeks

31 Mar, 2021

Chrome Flags also called Experiments are the experimental features that are provided by the Chrome browser but are not a part of the default chrome experience. Anyone can use them by following some simple steps and transform their chrome browsing experience. Some flags eventually become a part of the default public release once they are tried and tested completely. For example, the Tab Groups feature was first introduced as a Chrome flag before it was rolled out as a default feature.
Chrome flags Warning
Flags are experimental features and are not always stable. Using them might make the browser act weird or crash as they haven’t been tested extensively.
Flags are not tested thoroughly for security as well. So you might want to use a different browser or turn them off when doing online banking or other sensitive activities.
To enable a flag, the browser needs to be relaunched. Once the browser is relaunched, all the windows and tabs will reopen while the incognito windows will be lost.
Proceed with Caution 
WARNING: EXPERIMENTAL FEATURES AHEAD! 
By enabling these features, you could lose browser data or compromise your security or privacy. 
Enabled features apply to all users of this browser.
Chrome flags can be accessed on this URL on any chrome browser be it Windows, Chromebook, MacOS, iPhones, or Android.
chrome://flags/
This will take you to the home page of Chrome Experiments where all the chrome flags are available along with their status (Default/Enabled/Disabled).
Let us consider the chrome flag Enable Tab Search. 
There are two ways to access it:
Search with the name in the search box, or 
Search for a flag
Go to the flag tag. For e.g. chrome://flags/#enable-tab-search 
URL for a flag
Then just enable it and relaunch the browser. 
Enable a flag
You can now see the Search Tabs icon on the right side of the title bar. With just a few clicks you can enable a very useful feature.
Individual flags can be reset similarly by changing their state to Default or Disabled. The Reset all button will bring everything back to the default state. In either case, chrome needs to be relaunched to apply the changes.
Here is a link to a list of some chrome flags mentioned on the Google Chrome Github page.

How To


TechTips

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Align Text in HTML?
How to Install FFmpeg on Windows?
Java Tutorial
How to Install Jupyter Notebook on MacOS?
How to Install Python Pandas on MacOS?
Running Python script on GPU.
Setting up the environment in Java
How to Run a Python Script using Docker?
How to Force Dark Mode on Web Contents in Chrome
'dd' command in Linux
Radix sort in Javascript?

The radix sort algorithm distributes integers into buckets based on a number's significant digit or value (the radix). The radix is based on the number system of the values of the arrays. Let us look at how it can be implemented −
function radixSort(arr) {
   // Find the max number and multiply it by 10 to get a number
   // with no. of digits of max + 1
   const maxNum = Math.max(...arr) * 10;
   let divisor = 10;
   while (divisor < maxNum) {
      // Create bucket arrays for each of 0-9
      let buckets = [...Array(10)].map(() => []);
      // For each number, get the current significant digit and put it in the respective bucket
      for (let num of arr) {
         buckets[Math.floor((num % divisor) / (divisor / 10))].push(num);
      }
      // Reconstruct the array by concatinating all sub arrays
      arr = [].concat.apply([], buckets);
      // Move to the next significant digit
      divisor *= 10;
   }
   return arr;
}
console.log(radixSort([5,3,88,235,65,23,4632,234]))
[ 3, 5, 23, 65, 88, 234, 235, 4632 ]
How to convert list of dictionaries into Pyspark DataFrame ? - GeeksforGeeks

30 May, 2021
In this article, we are going to discuss the creation of the Pyspark dataframe from the list of dictionaries.
We are going to create a dataframe in PySpark using a list of dictionaries with the help createDataFrame() method. The data attribute takes the list of dictionaries and columns attribute takes the list of names.
dataframe = spark.createDataFrame(data, columns)
Example 1:
Python3
# importing moduleimport pyspark  # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list of dictionaries of students  datadata = [{"Student ID": 1, "Student name": "sravan"},        {"Student ID": 2, "Student name": "Jyothika"},        {"Student ID": 3, "Student name": "deepika"},        {"Student ID": 4, "Student name": "harsha"}]  # creating a dataframedataframe = spark.createDataFrame(data)  # display dataframedataframe.show()
Output:
Example 2:
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list of dictionaries of crop  datadata = [{"Crop ID": 1, "name": "rose", "State": "AP"},        {"Crop ID": 2, "name": "lilly", "State": "TS"},        {"Crop ID": 3, "name": "lotus", "State": "Maharashtra"},        {"Crop ID": 4, "name": "jasmine", "State": "AP"}]  # creating a dataframedataframe = spark.createDataFrame(data)  # display dataframedataframe.show()
Output:
Example 3:
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list of dictionaries of crop  datadata = [{"Crop ID": 1, "name": "rose", "State": "AP"},        {"Crop ID": 2, "name": "lilly", "State": "TS"},        {"Crop ID": 3, "name": "lotus", "State": "Maharashtra"},        {"Crop ID": 4, "name": "jasmine", "State": "AP"}]  # creating a dataframedataframe = spark.createDataFrame(data)  # display dataframe countdataframe.count()
Output:
4
Picked
Python-Pyspark
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 | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
PyQt5 QDateEdit - Selecting Whole Date - GeeksforGeeks

07 Jul, 2020
In this article we will see how we can select the whole date of the QDateEdit. User can set a date to the date edit with the help of cursor and the keyboard. Selecting date means the text of the date, selecting date is used for copying or overwriting the text of date edit.
In order to do this we use selectAll method with the QDateEdit object
Syntax : date.selectAll()
Argument : It takes no argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating a QDateEdit widget        date = QDateEdit(self)          # setting geometry of the date edit        date.setGeometry(100, 100, 150, 40)          # creating push button        push = QPushButton("Select", self)          # setting geometry to the push button        push.setGeometry(100, 150, 120, 30)          # adding action to the push button        # when it get clicked        push.clicked.connect(lambda: push_method())          # method called by push button        def push_method():              # selecting text            date.selectAll()        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Python | Numpy numpy.matrix.T() - GeeksforGeeks

08 Apr, 2019
With the help of Numpy numpy.matrix.T() method, we can make a Transpose of any matrix either having dimension one or more than more.
Syntax : numpy.matrix.T()
Return : Return transpose of every matrix
Example #1 :In this example we can see that with the help of matrix.T() method, we are able to transform any type of matrix.
# import the important module in pythonimport numpy as np          # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4]')          # applying matrix.T() methodgeeks = gfg.getT()    print(geeks)
[[1]
 [2]
 [3]
 [4]]

Example #2 :
# import the important module in pythonimport numpy as np          # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')          # applying matrix.T() methodgeeks = gfg.getT()    print(geeks)
[[1 4 7]
 [2 5 8]
 [3 6 9]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
pr command in Linux - GeeksforGeeks

28 Jan, 2022
In Linux/Unix pr command is used to prepare a file for printing by adding suitable footers, headers, and the formatted text. pr command actually adds 5 lines of margin both at the top and bottom of the page.  The header part shows the date and time of the last modification of the file with the file name and the page number. 
Syntax:
pr [options][filename]
1. To print k number of columns we use -k. Let’s say, we have a file that contains 10 numbers from 1 to 10 with every number in a new line. 
Now if we want to print this content in 3 columns we will use the following command.
pr -3 abc.txt
here abc.txt is the name of file.
2. To suppress the headers and footers the -t option is used.
pr -t abc.txt
After executing the above command it will give us the following output.
3. To Double the paces input, reduces clutter -d option is used.
pr -d abc.txt
After executing the above command it will give us the following output. 
4. To provide number lines which helps in debugging the code -n option is used.
pr -n abc.txt
After executing the above command it will give us the following output. 
5. To print the version number of the command –version is used. 
pr --version
After executing the command, it will return us the version in the below mentioned format. 
6. To open the help section of the command or to get the details of all the options and attributes of the command –help is used.
pr --help
After executing the command, it will return us the help section in the following way.
yashdongre146
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing
Strings in LISP - GeeksforGeeks

30 Sep, 2021
A string is a set of characters. String  are enclosed in double-quotes. 
Example:
"hello geek","java","python" etc
Example: LISP program to display strings
Lisp
;edisplay hello geek(write-line "Hello Geek")  ;display (write-line "Welcome to java")
Output:
Hello Geek
Welcome to java
Used to compare two strings. Further they can be divided into two categories. They are
Case Sensitive Functions:
These functions can be represented by mathematical symbols.
Example: LISP program that demonstrates string case sensitive functions
Lisp
; case-sensitive comparison - equal to (write (string= "Hello Geeks" "Hello Geeks"))  ;new line(terpri)  ; case-sensitive comparison - equal to (write (string= "Hello Geeks" "HelloGeeks"))  ;new line(terpri)  ; case-sensitive comparison - not equal to (write (string/= "Hello Geeks" "Hello Geeks"))  ;new line(terpri)  ; case-sensitive comparison - not equal to (write (string/= "Hello Geeks" "HelloGeeks"))  ;new line(terpri)  ; case-sensitive comparison -  greater than(write (string> "Hello Geeks" "Python"))  ;new line(terpri)  ; case-sensitive comparison -  less than(write (string< "Hello Geeks" "java"))  ;new line(terpri)  ; case-sensitive comparison -  greater than or equal to(write (string>= "Hello Geeks" "Python"))  ;new line(terpri)  ; case-sensitive comparison -  less than or equal to(write (string<= "Hello Geeks" "java"))  ;new line(terpri)
Output:
T
NIL
NIL
5
NIL
0
NIL
0
Case INSENSITIVE FUNCTIONS
These functions can be represented by expressions.
Example: Lisp program that demonstrates case insensitive functions
Lisp
; case-sensitive comparison - equal to (write (string-equal "Hello Geeks" "Hello Geeks"))  ;new line(terpri)  ; case-sensitive comparison - equal to (write (string-equal "Hello Geeks" "HelloGeeks"))  ;new line(terpri)  ; case-sensitive comparison - not equal to (write (string-not-equal "Hello Geeks" "Hello Geeks"))  ;new line(terpri)  ; case-sensitive comparison - not equal to (write (string-not-equal "Hello Geeks" "HelloGeeks"))  ;new line(terpri)  ; case-sensitive comparison -  greater than(write (string-greaterp "Hello Geeks" "Python"))  ;new line(terpri)  ; case-sensitive comparison -  less than(write (string-lessp "Hello Geeks" "java"))  ;new line(terpri)  ; case-sensitive comparison -  greater than or equal to(write (string-not-lessp "Hello Geeks" "Python"))  ;new line(terpri)  ; case-sensitive comparison -  less than or equal to(write (string-not-greaterp "Hello Geeks" "java"))  ;new line(terpri)
Output:
T
NIL
NIL
5
NIL
0
NIL
0
LISP-DataTypes
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cond Construct in LISP
Data Types in LISP
Packages in LISP
LISP - Comparison Operators on Characters & Strings
Symbols in LISP
Mapping Functions in LISP
Do Construct in LISP
Case Construct in LISP
Property Lists in LISP
Naming Conventions in LISP
Python - Tuple Exercises

Now you have learned a lot about tuples, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Print the first item in the fruits tuple.
fruits = ("apple", "banana", "cherry")
print()

Go to the Exercise section and test all of our Python Tuple Exercises:

Python Tuple Exercises

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How can I set a table in a JPanel in Java?

Let us first set rows and columns for our table −
String[][] rec = {
   { "1", "Steve", "AUS" },
   { "2", "Virat", "IND" },
   { "3", "Kane", "NZ" },
   { "4", "David", "AUS" },
   { "5", "Ben", "ENG" },
   { "6", "Eion", "ENG" },
};
String[] header = { "Rank", "Player", "Country" };
Now, set the above in a table as rows and columns −
JTable table = new JTable(rec, header);
Add the table in the panel −
JPanel panel = new JPanel();
panel.add(new JScrollPane(table));
The following is an example to create a table in a panel −
package my;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
This will produce the following output −
C# Program to find the largest element from an array

Declare an array −
int[] arr = { 20, 50, -35, 25, 60 };
Now to get the largest element from an array, use the Max() method −
arr.Max());
Here is the complete code −
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      int[] arr = { 20, 50, -35, 25, 60 };
      Console.WriteLine(arr.Max());
   }
}
60
How to filter an array in Java

You can use List.removeAll() method to filter an array. 
import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("A");
      list.add("B");
      list.add("C");
      list.add("D");
      list.add("E");
      list.add("F");
      list.add("G");
      list.add("H");
      List<String> filters = new ArrayList<>();
      filters.add("D");
      filters.add("E");
      filters.add("F");
      System.out.println("Original List " + list);
      list.removeAll(filters);
      System.out.println("Filtered List " + list);
   }
}
Original List [A, B, C, D, E, F, G, H]
Filtered List [A, B, C, G, H]
Nearest Power | Practice | GeeksforGeeks

Given two integers N and M  you have to find out an integer which is a power of M and is nearest to N.
Note: If there are multiple answers possible to, print the greatest number possible.
 
Example 1:
Input:
N = 6, M = 3
Output:
9
Explanation:
Both 3 (31) and 9 (32) are equally
near to 6. But 9 is greater,
so the Output is 9.
Example 2:
Input:
N = 3, M = 2
Output:
4
Explanation:
Both 2 (21) and 4 (22) are equally
near to 3. But 4 is greater,
so the Output is 4.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function nearestPower() which takes 2 Integers N and M as input and returns the answer.
 
Expected Time Complexity: O(max(log(N),log(M)))
Expected Auxiliary Space: O(1)
 
Constraints:
1 <= N,M <= 109
0
amanpandey30071 month ago
long long nearestPower(long long N , long long M)    {          long long ans=1;       long long x=M;       while(M<N)       {              ans=M;           M=M*x;       }                     if(abs(N-ans)>=abs(M-N))       return M;              return ans;   }
0
possible2 years ago
possible
simple#include<bits stdc++.h="">using namespace std;int main() {int t;cin>>t;while(t--){    long long n,m,temp,low,high;    cin>>n>>m;    temp=floor(log(n)/log(m));    low=pow(m,temp);    high=low*m;    if(n-low<high-n) cout<<low<<endl;="" else="" cout<<high<<endl;="" }="" return="" 0;="" }<="" code="">
0
Dr. Pro6 years ago
Dr. Pro
@GFG Please change the input statement! It says that each test case contains two integers M and N. This implies that M and N will be input in that order but its the other way round.
0
manu agrawal6 years ago
manu agrawal
http://www.practice.geeksfo...
why my code is giving tle it is in O(logn)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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

Suppose we have an array A, we have to shuffle a set of numbers without duplicates. So if the input is like [1,2,3], then for shuffling, it will be [1,3,2], after resetting, if we shuffle again, it will be [2,3,1]
To solve this, we will follow these steps −
There will be different methods. these are init(), reset(), shuffle(). These will act like below −
There will be different methods. these are init(), reset(), shuffle(). These will act like below −
init will be like −
init will be like −
original := a copy of the given array
original := a copy of the given array
temp := nums
temp := nums
indices := a list of numbers from 0 to length of nums – 1
indices := a list of numbers from 0 to length of nums – 1
the reset() will return the original array
the reset() will return the original array
the shuffle() will be like −
the shuffle() will be like −
if length of temp is 0, then return empty array
if length of temp is 0, then return empty array
i := choice randomly one index from indices array, j := choose another index from indices array randomly
i := choice randomly one index from indices array, j := choose another index from indices array randomly
swap the elements present at index i and j
swap the elements present at index i and j
return temp
return temp
another method called getAllPermutation() will take nums, i, initially i = 0, will be like −
another method called getAllPermutation() will take nums, i, initially i = 0, will be like −
curr := i
curr := i
if i = length of nums, theninsert a copy of nums array into another array called allreturn
if i = length of nums, then
insert a copy of nums array into another array called all
insert a copy of nums array into another array called all
return
return
for j := curr to length of numsswap elements at index j and curr from numscall getAllPermutation(nums, curr + 1)swap elements at index j and curr from nums
for j := curr to length of nums
swap elements at index j and curr from nums
swap elements at index j and curr from nums
call getAllPermutation(nums, curr + 1)
call getAllPermutation(nums, curr + 1)
swap elements at index j and curr from nums
swap elements at index j and curr from nums
Let us see the following implementation to get better understanding −
 Live Demo
import random
class Solution(object):
   def __init__(self, nums):
      self.original = [x for x in nums]
      self.temp = nums
      self.indices = [x for x in range(len(nums))]
   def reset(self):
      return self.original
   def shuffle(self):
      if not len(self.temp):
         return []
      i = random.choice(self.indices)
      j = random.choice(self.indices)
      self.temp[i], self.temp[j] = self.temp[j], self.temp[i]
      return self.temp
ob = Solution([1,2,3])
print(ob.shuffle())
print(ob.reset())
print(ob.shuffle())
Initialize with [1,2,3] , then call shuffle(), reset() and shuffle()
[2, 1, 3]
[1, 2, 3]
[2, 3, 1]
How to add footnote under the X-axis using Matplotlib?

To add footnote under the X-axis using matplotlib, we can use figtext() and text() method.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot x and y data points using numpy.
To place the footnote, use figtext() method with x, y position and box properties.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-2, 2, 100)
y = np.exp(x)

plt.plot(x, y)
plt.figtext(0.5, 0.01, "footnote: $y=e^{x}$", ha="center", fontsize=18, bbox={"facecolor": "green", "alpha": 0.75, "pad": 5})
plt.show()