code-rag-bench/online-tutorials huggingface dataset:
Python – Smallest Length String

31 Dec, 2019
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is the brute method in which we perform this task. In this, we run a loop to keep a memory of smallest string length and return the string which has min length in list.
# Python3 code to demonstrate working of # Smallest Length String# using loop   # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']   # printing original list print("The original list : " + str(test_list))   # Smallest Length String # using loop min_len = 99999for ele in test_list:     if len(ele) < min_len:         min_len = len(ele)         res = ele   # printing result print("Minimum length string is : " + res) 
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
Minimum length string is : is

 
Method #2 : Using min() + keyThis method can also be used to solve this problem. In this, we use inbuilt min() with “len” as key argument to extract the string with the minimum length.
# Python3 code to demonstrate working of # Smallest Length String# using min() + key   # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']   # printing original list print("The original list : " + str(test_list))   # Smallest Length String# using min() + key res = min(test_list, key = len)   # printing result print("Minimum length string is : " + res) 
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
Minimum length string is : is

Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to disable a button depending on a checkbox’s state in AngularJS ?

27 Jul, 2021
In this article, we will learn to disable the button depending upon the check-box status in Angular. We will use the Angular JS directive named ng-disabled to disable the button by unchecking the box. Please refer to AngularJS ng-disabled Directive.
The ng-disabled directive is used to enable or disable the HTML elements. If the expression inside the ng-disabled directive returns true then the HTML element would be disabled and vice versa. 
Approach: Here in the example, we have taken a checkbox and based on the checkbox, we are checking that whether the submit button is to be enabled or disabled. Here ng-model directive is used for binding the checkbox with the submit button & the ng-disabled directive is to handle the disable or enable operations.
Here if the checkbox is checked it will return TRUE and that TRUE will be passed to the ng-disabled directive. As a result, the submit button would be disabled but we need to enable it whenever the checkbox is checked. So for that, we need to have a NOT operation at the ng-disabled directive so that whenever the checkbox returns TRUE, the value that will go to the ng-disabled directive will be FALSE so that the submit button is enabled.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>      <!-- Including the  Angular JS CDN -->    <script src="http://code.angularjs.org/1.2.0/angular.min.js">    </script></head>  <body>      <!-- Defining the Angular Application -->    <div ng-app="">          <!-- Here we define the ng-model to             the checkbox so that we can refer             to it whether it checked or not -->        <input type="checkbox" name="isAgreed"             ng-model="isAgreed" />        <p>I agree with the Terms and Conditions</p>        <br />          <!-- If the checkbox is checked then             button would be enabled and if not             checked then button would be disabled -->        <button ng-disabled="!isAgreed">Submit</button>    </div></body>  </html>
Output:
AngularJS-Questions
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.listdir() method

20 May, 2019
os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.
Syntax: os.listdir(path)
Parameters:path (optional) : path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.
Code #1: use of os.listdir() method
# Python program to explain os.listdir() method     # importing os module import os  # Get the list of all files and directories# in the root directorypath = "/"dir_list = os.listdir(path)  print("Files and directories in '", path, "' :")   # print the listprint(dir_list)
Files and directories in ' / ' :
['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr', 
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']

 Code #2: use of os.listdir() method
# Python program to explain os.listdir() method     # importing os module import os  # Get the path of current working directorypath = os.getcwd()  # Get the list of all files and directories# in current working directorydir_list = os.listdir(path)    print("Files and directories in '", path, "' :") # print the listprint(dir_list)
Files and directories in ' /home/ihritik ' :
['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public',
'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music', 
'.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local', 
'.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates',
'.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images', 
'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks']

 Code #3: omitting path parameter
# Python program to explain os.listdir() method    # importing os module import os    # If we do not specify any path# os.listdir() method will return# the list of all files and directories# in current working directory  dir_list = os.listdir()  print("Files and directories in  current working directory :")   # print the listprint(dir_list)
Files and directories in current working directory :
['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public',
'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music', 
'.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local', 
'.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates',
'.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images', 
'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks']

As we can see the output of Code #2 and Code #3 are same. So if we omit the path parameter os.listdir() method will return the list of all files and directories in the current working directory.
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.argsort() in Python

16 Jun, 2022
numpy.argsort() function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that  would sort the array.
Syntax : numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None) Parameters : arr : [array_like] Input array. axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : [‘quicksort’, ‘mergesort’, ‘heapsort’]Selection algorithm. Default is ‘quicksort’. order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc. Return : [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr.
Code #1 : 
Python3
# Python program explaining# argpartition() function  import numpy as geek # input arrayin_arr = geek.array([ 2, 0,  1, 5, 4, 1, 9])print ("Input unsorted array : ", in_arr) out_arr = geek.argsort(in_arr)print ("Output sorted array indices : ", out_arr)print("Output sorted array : ", in_arr[out_arr])
Input unsorted array :  [2 0 1 5 4 1 9]
Output sorted array indices :  [1 2 5 0 4 3 6]
Output sorted array :  [0 1 1 2 4 5 9]
  Code #2 : 
Python3
# Python program explaining# argpartition() function import numpy as geek # input 2d arrayin_arr = geek.array([[ 2, 0, 1], [ 5, 4, 3]])print ("Input array : ", in_arr) # output sorted array indicesout_arr1 = geek.argsort(in_arr, kind ='mergesort', axis = 0)print ("Output sorteded array indices along axis 0: ", out_arr1)out_arr2 = geek.argsort(in_arr, kind ='heapsort', axis = 1)print ("Output sorteded array indices along axis 1: ", out_arr2)
Input array :  [[2 0 1]
 [5 4 3]]
Output sorteded array indices along axis 0:  [[0 0 0]
 [1 1 1]]
Output sorteded array indices along axis 1:  [[1 2 0]
 [2 1 0]]
sweetyty
Python numpy-Sorting Searching
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Optional padding in list elements

05 Feb, 2019
In real world problems, we sometimes require to pad the element of list according to a condition that maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved.
Method #1 : Using list comprehensionThis problem can be solved easily using the basic list comprehension in which we just need to use string formatting to perform the optional padding with 0 if size of each element is less than the specified size.
# Python3 code to demonstrate # to perform list element padding# using list comprehension  # initializing list  test_list = [3, 54, 4, 1, 10]  # printing original listprint ("The original list is : " + str(test_list))  # using list comprehension# to perform list element paddingres = ["%02d" %i for i in test_list]  # printing result print ("The list after element padding " +  str(res))
The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

 Method #2 : Using str.rjust()There is a function dedicated in python to do this job. rjust() function does the task of specifying the size of the string and also takes the character in which the character has to be padded.
# Python3 code to demonstrate # to perform list element padding# using str.rjust()  # initializing list  test_list = [3, 54, 4, 1, 10]  # printing original listprint ("The original list is : " + str(test_list))  # using str.rjust()# to perform list element paddingres = [str(i).rjust(2, '0') for i in test_list]  # printing result print ("The list after element padding " +  str(res))
The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.zip() Method - GeeksforGeeks

01 Sep, 2020
The _.zip() method is used to create an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second element of the given arrays, and so on.
Syntax:
_.zip([arrays])
Parameters: This method accepts a single parameter as mentioned above and described below:
[arrays]: This parameter holds the arrays to process.
Return Value: This method returns the new array of regrouped elements.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library  const _ = require("lodash");   // Use of _.zip() method let gfg = _.zip(['a', 'b', 'c'],                 [1, 2, 3],                 [true, false, true]);        // Printing the output  console.log(gfg)
Output:
a,1,true,b,2,false,c,3,true
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");   // Use of _.zip()  // method let gfg = _.zip(['Amit', 'Akash', 'Avijit'],                 [1, 2, 3],                 ['pass', 'pass', 'fail']);        // Printing the output  console.log(gfg)
Output:
Amit,1,pass,Akash,2,pass,Avijit,3,fail
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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 | Remove repeated sublists from given list - GeeksforGeeks

06 May, 2019
Given a list of lists, write a Python program to remove all the repeated sublists (also with different order) from given list.
Examples:
Input : [[1], [1, 2], [3, 4, 5], [2, 1]]
Output : [[1], [1, 2], [3, 4, 5]]

Input : [['a'], ['x', 'y', 'z'],  ['m', 'n'], ['a'], ['m', 'n']]
Output : [['a'], ['x', 'y', 'z'], ['m', 'n']]

 Approach #1 : Set comprehension + Unpacking
Our first approach is to use set comprehension with sorted tuple. In every iteration in the list, we convert the current sublist to a sorted tuple, and return a set of all these tuples, which in turn eliminates all repeated occurrences of the sublists and thus, remove all repeated rearranged sublists.
# Python3 program to Remove repeated # unordered sublists from list  def Remove(lst):     return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}])         # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst))
[[1, 2], [3, 4, 5], [1]]

 Approach #2 : Using map() with set and sorted tuples.
# Python3 program to Remove repeated # unordered sublists from list  def Remove(lst):     return list(map(list, (set(map(lambda x: tuple(sorted(x)), lst)))))       # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst))
[[1, 2], [3, 4, 5], [1]]

With maintaining order –
Approach #3 : Using sorted tuple as hash
First, we initialize an empty list as ‘res’ and a set as ‘check’. Now, For each sublist in the list, convert the sublist to sorted tuple and save it in ‘hsh’. Then check if hsh is present in check or not. If not, append the current sublist to ‘.res’ and ‘hsh’ to ‘check’. This way it would be easier to maintain the order to sublists.
# Python3 program to Remove repeated # unordered sublists from list  def Remove(lst):     res = []     check = set()       for x in lst:         hsh = tuple(sorted(x))         if hsh not in check:             res.append(x)             check.add(hsh)                    return res       # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst))
[[1], [1, 2], [3, 4, 5]]

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
Python - Custom Split Comma Separated Words - GeeksforGeeks

20 Aug, 2020
While working with Python, we can have problem in which we need to perform the task of splitting the words of string on spaces. But sometimes, we can have comma separated words, which have comma’s joined to words and require to split them separately. Lets discuss certain ways in which this task can be performed.Method #1 : Using replace() Using replace() is one way to solve this problem. In this, we just separate the joined comma from string to spaced so that they can be splitted along with other words correctly. 
Python3
# Python3 code to demonstrate working of# Custom Split Comma Separated Words# Using replace() # initializing stringtest_str = 'geeksforgeeks, is, best, for, geeks' # printing original stringprint("The original string is : " + str(test_str)) # Distance between occurrences# Using replace()res = test_str.replace(", ", " , ").split() # printing resultprint("The strings after performing splits : " + str(res))
The original string is : geeksforgeeks, is, best, for, geeks The strings after performing splits : [‘geeksforgeeks’, ‘, ‘, ‘is’, ‘, ‘, ‘best’, ‘, ‘, ‘for’, ‘, ‘, ‘geeks’] 
 
 Method #2 : Using re.findall() This problem can also be used using regex. In this, we find the occurrences of non space word and perform a split on that basis. 
Python3
# Python3 code to demonstrate working of# Custom Split Comma Separated Words# Using re.findall()import re # initializing stringtest_str = 'geeksforgeeks, is, best, for, geeks' # printing original stringprint("The original string is : " + str(test_str)) # Distance between occurrences# Using re.findall()res = re.findall(r'\w+|\S', test_str) # printing resultprint("The strings after performing splits : " + str(res))
The original string is : geeksforgeeks, is, best, for, geeks The strings after performing splits : [‘geeksforgeeks’, ‘, ‘, ‘is’, ‘, ‘, ‘best’, ‘, ‘, ‘for’, ‘, ‘, ‘geeks’] 
 
nidhi_biet
tarangagarwal
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Get the first occurrence of a substring within a string in Arduino

The indexOf() function within Arduino scans a string from the beginning, and returns the first index of the specified substring within the string. The syntax is −
Syntax
myString.indexOf(substr)
where substr is the substring to search for. It can be of type character or string.
Optionally, you can provide a different starting point to begin the search from, in which case, the syntax is −
Syntax
myString.indexOf(substr, from)
where from is the index from where the search should start. This function returns the index of the first occurrence of the substring within the string, or -1, if no match is found.
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   String s1 = "Mississippi";
   String substr1 = "is";
   String substr2 = "os";
   Serial.println(s1.indexOf(substr1));
   Serial.println(s1.indexOf(substr2));
   Serial.println(s1.indexOf(substr1, 3));
}
void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, in the first case, the index 1 was printed (counting starts from 0). In the second case, since no match was found, -1 was printed. In the third case, we told Arduino to start searching from index 3. Therefore, the next match was found at index 4, and that was printed.
Convert decimal to binary number in Python program

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a decimal number, we need to convert it into its binary equivalent.
There are two approaches to solve the given problem. Let’s see them one by one−
 Live Demo
def DecimalToBinary(num):
   if num > 1:
      DecimalToBinary(num // 2)
   print(num % 2, end = '')
# main
if __name__ == '__main__':
   # decimal input
   dec_val = 56
   # binary equivalent
   DecimalToBinary(dec_val)
111000
All the variables and functions are declared in the global scope shown in the figure above.
 Live Demo
def decimalToBinary(n):
   return bin(n).replace("0b", "")
# Driver code
if __name__ == '__main__':
   print(decimalToBinary(56))
111000
All the variables and functions are declared in the global scope shown in the figure above.
In this article, we have learned about the python program to convert a list into a string.
fmt.Sscanf() Function in Golang With Examples - GeeksforGeeks

05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sscanf() function in Go language scans the specified string and stores the successive space-separated values into successive arguments as determined by the format. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Sscanf(str string, format string, a ...interface{}) (n int, err error)

Parameters: This function accepts three parameters which are illustrated below:
str string: This parameter contains the specified text which is going to be scanned.
format string: This parameter is the different types of format for each elements of the specified string.
a ...interface{}: This parameter receives each elements of the string.
Returns: It returns the number of items successfully parsed.
Example 1:
// Golang program to illustrate the usage of// fmt.Sscanf() function  // Including the main packagepackage main  // Importing fmtimport (    "fmt")  // Calling mainfunc main() {      // Declaring two variables    var name string    var alphabet_count int      // Calling the Sscanf() function which    // returns the number of elements    // successfully parsed and error if    // it persists    n, err := fmt.Sscanf("GFG is having 3 alphabets.",      "%s is having %d alphabets.", &name, &alphabet_count)      // Below statements get     // executed if there is any error    if err != nil {        panic(err)    }      // Printing the number of     // elements and each elements also    fmt.Printf("%d: %s, %d\n", n, name, alphabet_count)  }
Output:
2: GFG, 3

Example 2:
// Golang program to illustrate the usage of// fmt.Sscanf() function  // Including the main packagepackage main  // Importing fmtimport (    "fmt")  // Calling mainfunc main() {      // Declaring some variables    var name string    var alphabet_count int    var float_value float32    var boolean_value bool      // Calling the Sscanf() function which    // returns the number of elements    // successfully parsed and error if    // it persists    n, err := fmt.Sscanf("GeeksforGeeks 13 6.7 true",               "%s %d %g %t", &name, &alphabet_count,                         &float_value, &boolean_value)      // Below statements get executed    // if there is any error    if err != nil {        panic(err)    }      // Printing the number of elements    // and each elements also    fmt.Printf("%d: %s, %d, %g, %t", n, name,      alphabet_count, float_value, boolean_value)  }
Output:
4: GeeksforGeeks, 13, 6.7, true

Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Interfaces in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
How to Trim a String in Golang?
What is the return type of a “count” query against MySQL using Java JDBC?

The return type of count is long. The Java statement is as follows
rs.next();
long result= rs.getLong("anyAliasName");
First, create a table with some records in our sample database test3. The query to create a table is as follows
mysql> create table CountDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into CountDemo(Name) values('John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountDemo(Name) values('Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountDemo(Name) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into CountDemo(Name) values('David');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from CountDemo;
The following is the output
+----+-------+
| Id | Name  |
+----+-------+
| 1 | John   |
| 2 | Carol  |
| 3 | Bob    |
| 4 | David  |
+----+-------+
4 rows in set (0.00 sec)
Here is the Java code return type of a “count” query against MySQL using Java JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ReturnTypeOfCount {
   public static void main(String[] args) {
      Connection con=null;
      Statement st=null;
      ResultSet rs=null;
      try {
         con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test3?useSSL=false",
         "root","123456");
         String yourQuery = "SELECT COUNT(*) AS totalCount FROM CountDemo";
         st = con.createStatement();
         rs = st.executeQuery(yourQuery);
         rs.next();
         long result= rs.getLong("totalCount");
         System.out.println("Total Count="+result);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The following is the output
Total Count=4
Here is the snapshot of the output:
How to convert python tuple into a two-dimensional table?

If you have a numeric library like numpy available, you should use the reshape method to reshape the tuple to a multidimensional array. 
import numpy
data = numpy.array(range(1,10))
data.reshape([3,3])
print(data)
This will give the output −
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
If you prefer to do it in pure python, you can use a list comprehension −
data = tuple(range(1, 10))
table = tuple(data[n:n+3] for n in xrange(0,len(data),3))
print(table)
This will give the output −
((1, 2, 3), (4, 5, 6), (7, 8, 9))
How to handle frame in Selenium WebDriver using java?

We can handle frames in Selenium webdriver. A frame is identified with <frame> tag in the html document. A frame is used to insert an HTML document inside another HTML document.
To work with frames, we should first understand switching between frames and identify the frame to which we want to move. There are multiple ways to switch to frames −
switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0.
switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0.
Syntax −
driver.switchTo().frame(1), we shall switch to the frame with index 1.
switchTo().frame(name) - The frame id or name is passed as an argument to switch to.
switchTo().frame(name) - The frame id or name is passed as an argument to switch to.
Syntax −
driver.switchTo().frame("fname"), we shall switch to the frame with name fname.
switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to.
switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to.
Syntax −
driver.switchTo().frame(n), we shall switch to the frame with webelement n.
switchTo().defaultContent() – To switch back to the main page from the frame.
switchTo().defaultContent() – To switch back to the main page from the frame.
Syntax −
driver.switchTo().defaultContent()
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Framehandling{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://the-internet.herokuapp.com/frames";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      driver.findElement(By.linkText("Nested Frames")).click();
      // switch to frame with frame name and identify inside element
      driver.switchTo().frame("frame-bottom");
      WebElement l = driver.findElement(By.cssSelector("body"));
      System.out.println("Bottom frame text: " +l.getText());
      // switch to main page
      driver.switchTo().defaultContent();
      driver.quit();
   }
}
Git - Stash Operation

Suppose you are implementing a new feature for your product. Your code is in progress and suddenly a customer escalation comes. Because of this, you have to keep aside your new feature work for a few hours. You cannot commit your partial code and also cannot throw away your changes. So you need some temporary space, where you can store your partial changes and later on commit it.
In Git, the stash operation takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time.
[jerry@CentOS project]$ git status -s
M string.c
?? string

Now, you want to switch branches for customer escalation, but you don’t want to commit what you’ve been working on yet; so you’ll stash the changes. To push a new stash onto your stack, run the git stash command.
[jerry@CentOS project]$ git stash
Saved working directory and index state WIP on master: e86f062 Added my_strcpy function
HEAD is now at e86f062 Added my_strcpy function

Now, your working directory is clean and all the changes are saved on a stack. Let us verify it with the git status command.
[jerry@CentOS project]$ git status -s
?? string

Now you can safely switch the branch and work elsewhere. We can view a list of stashed changes by using the git stash list command.
[jerry@CentOS project]$ git stash list
stash@{0}: WIP on master: e86f062 Added my_strcpy function

Suppose you have resolved the customer escalation and you are back on your new feature looking for your half-done code, just execute the git stash pop command, to remove the changes from the stack and place them in the current working directory.
[jerry@CentOS project]$ git status -s
?? string

[jerry@CentOS project]$ git stash pop

The above command will produce the following result:
# On branch master
# Changed but not updated:
# (use "git add ..." to update what will be committed)
# (use "git checkout -- ..." to discard changes in working directory)
#
#
modified: string.c
#
# Untracked files:
# (use "git add ..." to include in what will be committed)
#
#
string
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4)

[jerry@CentOS project]$ git status -s
M string.c
?? string


    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    23 Lectures 
     2 hours 

 Asif Hussain

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    125 Lectures 
     9 hours 

 John Shea

    13 Lectures 
     2.5 hours 

 Raghu Pandey

    13 Lectures 
     3 hours 

 Sebastian Sulinski
 Print
 Add Notes
 Bookmark this page
C program to store the car information using dynamic linked list.

Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes.
Node has two parts which are as follows −
Data
Link
The types of linked lists in C programming language are as follows −
Single / Singly linked lists
Double / Doubly linked lists
Circular single linked list
Circular double linked list
Refer an algorithm given below for storing the car information by using the dynamic linked list.
Step 1 − Declare structure variables.
Step 2 − Declare Function definition to display.
Step 3 − Allocate dynamic memory allocation to variable.
Step 4 − Use do while loop to enter the car information.
Step 5 − Call display function goto step 2.
Following is the C program for storing the car information by using the dynamic linked list −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
   char model[10],color[10];
   int year;
   struct node *next;
};
struct node *temp,*head;
void display(struct node *head){
   temp=head;
   while(temp!=NULL){
      if(temp->year>2010 && (strcmp("yellow",temp->color)==0))
      printf(" %s \t\t %s \t\t %d",temp->model,temp->color,temp->year);
      temp=temp->next;
      printf("\n");
   }
}
int main(){
   int n;
   char option,enter;
   head=(struct node *)malloc(sizeof(struct node));
   temp=head;
   do{
      printf("\nenter car model: ");
      scanf("%s",temp->model);
      printf("enter car color: ");
      scanf("%s",temp->color);
      printf("enter car year: ");
      scanf("%d",&temp->year);
      printf("\nDo you want continue Y(es) | N(o) : ");
      scanf("%c",&enter);
      scanf("%c",&option);
      if (option!='N'){
         temp->next=(struct node *)malloc(sizeof(struct node));
         temp=temp->next;
      } else {
         temp->next=NULL;
      }
   }while(option!='N');
   display(head);
   return 0;
}
When the above program is executed, it produces the following output −
enter car model: I20
enter car color: white
enter car year: 2016
Do you want continue Y(es) | N(o) : Y
enter car model: verna
enter car color: red
enter car year: 2018
Do you want continue Y(es) | N(o) : Y
enter car model: creta
enter car color: Maroon
enter car year: 2010
Do you want continue Y(es) | N(o) : N
numpy.pad() function in Python

01 Oct, 2020
numpy.pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy.pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.
Syntax: numpy.pad(array, pad_width, mode=’constant’, **kwargs) 
Parameters :
array: the array to pad
pad_width: This parameter defines the number of values that are padded to the edges of each axis.mode : str or function(optional)
**kwargs: allows you to pass keyword variable length of argument to a function. It is used when we want to handle the named argument in a function.
Return:A padded array of rank equal to an array with shape increased according to pad_width.
Example 1:
Python3
# Python program to explain# working of numpy.pad() functionimport numpy as np    arr = [1, 3, 2, 5, 4]  # padding array using CONSTANT modepad_arr = np.pad(arr, (3, 2), 'constant',                  constant_values=(6, 4))  print(pad_arr)
Output:
[6 6 6 1 3 2 5 4 4 4]

Example 2:
Python3
# Python program to explain# working of numpy.pad() functionimport numpy as np    arr = [1, 3, 2, 5, 4]   # padding array using 'linear_ramp' modepad_arr = np.pad(arr, (3, 2), 'linear_ramp',                 end_values=(-4, 5))     print(pad_arr)
Output:
[-4 -2 -1  1  3  2  5  4  4  5]

Example 3:
Python3
# Python program to explain# working of numpy.pad() functionimport numpy as np    arr = [1, 3, 9, 5, 4]  # padding array using 'maximum' modepad_arr = np.pad(arr, (3,), 'maximum')  print(pad_arr)
Output:
[9 9 9 1 3 9 5 4 9 9 9]

Example 4:
Python3
# Python program to explain# working of numpy.pad() functionimport numpy as np    arr = [[1, 3],[5, 8]]   # padding array using 'minimum' modepad_arr = np.pad(arr, (3,), 'minimum')         print(pad_arr)
Output:
[[1 1 1 1 3 1 1 1]
[1 1 1 1 3 1 1 1]
[1 1 1 1 3 1 1 1]
[1 1 1 1 3 1 1 1]
[5 5 5 5 8 5 5 5]
[1 1 1 1 3 1 1 1]
[1 1 1 1 3 1 1 1]
[1 1 1 1 3 1 1 1]]

Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Split String on all punctuations

02 Sep, 2020
Given a String, Split the String on all the punctuations.
Input : test_str = ‘geeksforgeeks! is-best’Output : [‘geeksforgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]Explanation : Splits on ‘!’ and ‘-‘.
Input : test_str = ‘geek-sfo, rgeeks! is-best’Output : [‘geek’, ‘-‘, ‘sfo’, ‘, ‘, ‘rgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]Explanation : Splits on ‘!’, ‘, ‘ and ‘-‘.
Method : Using regex + findall()
This is one way in which this problem can be solved. In this, we construct appropriate regex and task of segregating and split is done by findall().
Python3
# Python3 code to demonstrate working of # Split String on all punctuations# using regex + findall()import re  # initializing stringtest_str = 'geeksforgeeks ! is-best, for @geeks'  # printing original Stringprint("The original string is : " + str(test_str))  # using findall() to get all regex matches. res = re.findall( r'\w+|[^\s\w]+', test_str)  # printing result print("The converted string : " + str(res)) 
The original string is : geeksforgeeks! is-best, for @geeks
The converted string : ['geeksforgeeks', '!', 'is', '-', 'best', ', ', 'for', '@', 'geeks']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python | Combine two dictionary adding values for common keys

31 Mar, 2022
Given two dictionary, the task is to combine the dictionaries such that we get the added values for common keys in resultant dictionary. Example:  
Input: dict1 = {'a': 12, 'for': 25, 'c': 9}
       dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}

Output: {'for': 325, 'Geeks': 100, 'geek': 200}
Let’s see some of the methods to do the task. Method #1: Naive method 
Python3
# Python program to combine two dictionary# adding values for common keys# initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}  # adding the values with common keyfor key in dict2:    if key in dict1:        dict2[key] = dict2[key] + dict1[key]    else:        pass         print(dict2)
{'for': 325, 'Geeks': 100, 'geek': 200}
 
 Method #2: Using collections.Counter() 
Python3
# Python program to combine two dictionary# adding values for common keysfrom collections import Counter # initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}  # adding the values with common key         Cdict = Counter(dict1) + Counter(dict2)print(Cdict)
Counter({'for': 325, 'geek': 200, 'Geeks': 100, 'a': 12, 'c': 9})
 
 Method #3: Using itertools.chain() 
Python3
# Python program to combine two dictionary# adding values for common keysimport itertoolsimport collections # initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # using defaultdictCdict = collections.defaultdict(int) # iterating key, val with chain()for key, val in itertools.chain(dict1.items(), dict2.items()):    Cdict[key] += val     print(dict(Cdict))
{'for': 325, 'a': 12, 'geek': 200, 'Geeks': 100, 'c': 9}
 
  Method #4: Using functools.reduce and dict comprehension
Python3
#Here is another way to combine dictionaies and#sum values of common keys (runs fast):  from functools import reduce # creating three dictionaries in a listdict_seq = [  {'a': 1, 'b': 2, 'c': 3},  {'a':10, 'b': 20},  {'b': 100},] print(reduce(lambda d1,d2: {k: d1.get(k,0)+d2.get(k,0)for k in set(d1)|set(d2)}, dict_seq))
Output:
{'a': 11, 'b': 122, 'c': 3}
mberest
sagartomar9927
Marketing
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python – Group Similar keys in dictionary

22 Apr, 2020
Sometimes while working with dictionary data, we can have problems in which we need to perform grouping based on substring of keys and reform the data grouped on similar keys. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute way in which we perform this task. In this, we check for element using conditional statement and insert the keys according to substring presence.
# Python3 code to demonstrate working of # Group Similar keys in dictionary# Using loop  # initializing Dictionarytest_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3,             'gfg2' : 9, 'is2' : 8, 'best2' : 7,            'gfg3' : 10, 'is3' : 5, 'best3' : 6}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Group Similar keys in dictionary# Using loopres = []res1, res2, res3 = {}, {}, {}for key, value in test_dict.items():  if 'gfg' in key:    res1[key] = value  elif 'is' in key:    res2[key] = value  elif 'best' in key:    res3[key] = value  res.append(res1)res.append(res2)res.append(res3)  # printing result print("The grouped similar keys are : " + str(res)) 
The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}]
 
Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. In this, we group the substring to keys using dictionary comprehension.
# Python3 code to demonstrate working of # Group Similar keys in dictionary# Using dictionary comprehension  # initializing Dictionarytest_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3,             'gfg2' : 9, 'is2' : 8, 'best2' : 7,            'gfg3' : 10, 'is3' : 5, 'best3' : 6}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Group Similar keys in dictionary# Using dictionaryres = []res1 = {key : val for key, val in test_dict.items() if 'gfg' in key}res2 = {key : val for key, val in test_dict.items() if 'is' in key}res3 = {key : val for key, val in test_dict.items() if 'best' in key}res.append(res1)res.append(res2)res.append(res3)  # printing result print("The grouped similar keys are : " + str(res)) 
The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
HTML | onload Event Attribute

08 Aug, 2021
This attribute works when an object has been loaded. This attribute mostly used within the <body> element to execute a script. It can be used with other elements as well. This attribute is used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.Supported Tags: 
<body>
<frame>
<frameset>
<iframe>
<img>
<input type=”image”>
<link>
<script>
<style>
Syntax:  
<element onload = "script">
Attribute Value: This attribute contains single value script and it runs when onload event triggered. This attribute is associated with many HTML elements.Example 1:  
html
<!DOCTYPE html><html>    <head>        <title>onload event attribute</title>        <script>        function Function() {            alert("Page is loaded");        }        </script>        <style>            body {                text-align:center;            }            h1 {                color:green;            }        </style>    </head>    <body onload="Function()">        <h1>GeeksforGeeks</h1>        <h2>onload event attribute</h2>    </body></html>
Output:  
Example 2:  
html
<!DOCTYPE html><html>    <head>        <title>onload event attribute</title>    </head>    <body>        <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png"        onload="loadImage()" width="500" height="132">        <script>            function loadImage() {                alert("Image loaded successfully");            }        </script>    </body></html>                   
Output:  
Supported Browsers: The browser supported by onload attribute are listed below:  
Chrome
Internet Explorer
Firefox
Safari
Opera
 
hritikbhatnagar2182
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python @staticmethod

21 Nov, 2019
There can be some functionality that relates to the class, but does not require any instance(s) to do some work, static methods can be used in such cases. A static method is a method which is bound to the class and not the object of the class. It can’t access or modify class state. It is present in a class because it makes sense for the method to be present in class. A static method does not receive an implicit first argument.
Syntax:

class C(object):
    @staticmethod
    def fun(arg1, arg2, ...):
        ...

Returns: a static method for function fun.

When function decorated with @staticmethod is called, we don’t pass an instance of the class to it as it is normally done with methods. It means that the function is put inside the class but it cannot access the instance of that class.
Example #1:
# Python program to # demonstrate static methods  class Maths():          @staticmethod    def addNum(num1, num2):        return num1 + num2          # Driver's codeif __name__ == "__main__":          # Calling method of class    # without creating instance    res = Maths.addNum(1, 2)    print("The result is", res)
Output:
The result is 3

Example #2:
# Python program to# demonstrate static methods  class Person:     def __init__(self, name, age):         self.name = name         self.age = age             # a static method to check if a Person is adult or not.     @staticmethod    def isAdult(age):         return age > 18          # Driver's codeif __name__ == "__main__":    res = Person.isAdult(12)    print('Is person adult:', res)          res = Person.isAdult(22)    print('\nIs person adult:', res)
Output:
Is person adult: False

Is person adult: True

Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python