code-rag-bench/online-tutorials huggingface dataset:
Python | Print diagonals of 2D list - GeeksforGeeks

30 Aug, 2021
Given a 2D list (with equal length of sublists), write a Python program to print both the diagonals of the given 2D list.
Examples: 
Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output : Diagonal 1 - [1, 5, 9]
         Diagonal 2 - [3, 5, 7]

Input : [['a', 'b'], ['c', 'd']]
Output : Diagonal 1 - ['a', 'd']
         Diagonal 2 - ['b', 'c']
Approach #1 : Using Python xrange()We can use one-liner list comprehension along with xrange() function. xrange() is used to iterate a certain number of times in for loops. Thus, we print the element at [i][i] position in every iteration of loop. [Works in Python2] 
Python
# Python2 program to print diagonals in 2D list def printDiagonal(lst):    # To print Primary Diagonal    print('Diagonal 1 -'),    print([lst[i][i] for i in xrange(len(lst))])     # To print Secondary Diagonal    print('Diagonal 2 -'),    print([lst[i][len(lst)-1-i] for i in xrange(len(lst))])      # Driver codelst = [[1, 2, 3],       [4, 5, 6],       [7, 8, 9]] printDiagonal(lst)
Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
  Approach #2 : Using range()This method is similar to Approach #1. The advantage of range() is that it works for both the versions of Python i.e. Python2 and Python3. 
Python3
# Python3 program to print diagonals in 2D list def printDiagonal(lst):     # To print Primary Diagonal    print('Diagonal 1 - ', end ="")    print([lst[i][i] for i in range(len(lst))])         # To print Secondary Diagonal    print('Diagonal 2 - ', end ="")    print([lst[i][len(lst)-i-1] for i in range(len(lst))])     # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst)
Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
  Approach #3 : Using enumerate()Python enumerate() is also an alternative to above mentioned methods. It uses two variable ‘i’ and ‘r’ two traverse through enumerate(lst) and simply return the ith element of ‘r’. 
Python3
# Python3 program to print diagonals in 2D list def printDiagonal(lst):    # To print Primary Diagonal    print('Diagonal 1 - ', end ="")    print([r[i] for i, r in enumerate(lst)])         # To print Secondary Diagonal    print('Diagonal 2 - ', end ="")    print([r[~i] for i, r in enumerate(lst)])      # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst)
Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
gabaa406
ruhelaa48
Python list-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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python - API.update_status() in Tweepy - GeeksforGeeks

05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The API.update_status() method of the API class in Tweepy module is used to update the authenticated user’s current status or in simple words, tweeting.
Syntax : API.update_status(parameters)
Parameters :
status : The text of the tweet / status update.
in_reply_to_status_id : The ID of the tweet that the new tweet is being replied to.
attachment_url : This provides a URL as a tweet attachment.
media_ids : A list of media_ids to be associated with the tweet.
possibly_sensitive : Set it to True if the tweet might contain sensitive data.
lat : The latitude of the tweet.
long : The longitude of the tweet.
place_id : The name of the place of the tweet.
display_coordinates : Set this value to True if the exact coordinates of the tweet have to be displayed.
Returns : an object of the class Status
Example 1 :Using the update_status() method with only the text and no other parameter.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the text to be tweetedstatus = "This is a tweet."  # posting the tweetapi.update_status(status)
Output :
Example 2 :Using the update_status() method with in_reply_to_status_id parameter to reply to the previous tweet.
# the text to be tweetedstatus = "This is a tweet is a reply."  # the ID of the tweet to be replied toin_reply_to_status_id = ""  # posting the tweetapi.update_status(status, in_reply_to_status_id)
Output :
Python-Tweepy
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
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python | Increment 1's in list based on pattern - GeeksforGeeks

30 Jul, 2019
Given a list of binary numbers 0 and 1, Write a Python program to transform the list in such a way that whenever 1 appears after the occurrence of a sequence of 0’s, increment it by n+1, where ‘n’ is the last increment.
Examples:
Input : [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]
Output : [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]

Input : [1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1]
Output : [1, 0, 2, 0, 0, 0, 3, 3, 0, 0, 4, 4, 4, 0, 5, 0, 6]

 Approach #1 : Naive Approach
This is a naive approach to the given problem. It uses two variable ‘previous’ and ‘grp’ to store previously incremented number and to store the number of 1’s in a group. Now, using a for loop, increment 1’s accordingly.
# Python3 program to increment 1's in # list based on pattern   def transform(lst):          previous = 0    grp = 0    for elem in lst:        if elem and not previous:             grp += 1        previous = elem        yield (grp if elem else 0)      # Driver codelst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]x = (transform(lst))res = []for i in range(0, len(lst)):    res.append(next(x))print(res)
[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]

 
Approach #2 : Using count, chain and groupby from itertools module.This is an efficient and more pythonic approach towards the given problem where we use count, chain and groupby from itertools module.
# Python3 program to increment 1's in # list based on pattern from itertools import *   def transform(lst):          c = count(1)    return list(chain(*[list(g) if k != 1 else [next(c)]*len(list(g))     for k, g in groupby(lst)]))      # Driver codelst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]print(transform(lst))
[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]

ManasChhabra2
Python list-programs
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
Tailwind CSS List Style Type - GeeksforGeeks

23 Mar, 2022
This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS List Style Type property. This class specifies the appearance of the list item marker (such as a disc, character, or custom counter style) if the ‘list-style-image’ has the value ‘none’.
List Style Type classes:
list-none: No marker is shown in this mode.
list-disc: This is the default value. The marker is a filled circle.
list-decimal: A marker is a decimal number, beginning with 1.
Syntax:
<element class="List Style Type">...</element>
Example:
HTML
<!DOCTYPE html> <head>     <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"           rel="stylesheet"> </head>   <body class="text-center mx-4 space-y-2">     <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>     <b>Tailwind CSS List Style Type Class</b>     <div class="mx-24 bg-green-200 text-justify px-6">        <ul class="list-disc">            <li>Self learning</li>            <li>Contribute at Open Source</li>            <li>Gain Stack overflow respect</li>        </ul>        <br>        <ol class="list-decimal">            <li>Self learning</li>            <li>Contribute at Open Source</li>            <li>Gain Stack overflow respect</li>                </ol>        <br>        <ul class="list-none">            <li>Self learning</li>            <li>Contribute at Open Source</li>            <li>Gain Stack overflow respect</li>                </ul>    </div></body>   </html> 
Output:
       
List style type
Tailwind CSS
Tailwind-Typography
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
MathF.Pow() Method in C# with Examples - GeeksforGeeks

04 Apr, 2019
In C#, MathF.Pow(Single, Single) is a MathF class method. This method is used to calculate a number raise to the power of some other number.
Syntax: public static float Pow (float x, float y);
Parameters:x: It is a single-precision floating-point number which is to be raised to a power and type of this parameter is System.Single.y: It is a single-precision floating-point number which specifies a power or exponent and type of this parameter is System.Single.
Return Type: The function returns the number base raised to the power. The return type of this method is System.Single
Example:
// C# program to illustrate the// MathF.Pow(Single, Single) Methodusing System;  class GFG {      // Main Method    static public void Main()    {          // Find power using MathF.Pow        // 8 is base and 4 is power or        // index or exponent of a number        float pow_ab = MathF.Pow(8f, 4f);          // Print the result        Console.WriteLine(pow_ab);          // 7.5 is base and 2 is power or        // index or exponent of a number        float pow_tt = MathF.Pow(7.5f, 2f);          // Print the result        Console.WriteLine(pow_tt);          // 1234 is base and 7 is power or        // index or exponent of a number        float pow_t = MathF.Pow(1234f, 7f);          // Print the result        Console.WriteLine(pow_t);    }}
4096
56.25
4.357186E+21

CSharp-MathF-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Count numbers with same first and last digits in C++

We are given an interval [first, last]. The goal is to find the count of numbers that have the same first and last digit within this interval. For example, 232 has the same first and last digit as 2.
We will do this by traversing from i=first to i=last. For each number I compare its first digit with the last digit, if they are the same increment the count.
Let’s understand with examples.
Input − first=8 last=40
Output − Count of numbers with same first and last digits − 5
Explanation − Numbers between 8 and 40 with same first and last digit −
8, 9, 11, 22, 33
Input − first=100 last=200
Output − Count of numbers with same first and last digits: 5
Explanation − Numbers between 100 and 200 with same first and last digit −
101, 111, 121, 131, 141, 151, 161, 171, 181, 191.
We take two integers first and last to define range [first,last].
We take two integers first and last to define range [first,last].
Function getFirstDigit(int num) takes a number and returns its first digit.
Function getFirstDigit(int num) takes a number and returns its first digit.
While num>=10, divide num by 10. In the end num will have the first digit. Return this value.
While num>=10, divide num by 10. In the end num will have the first digit. Return this value.
Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits.
Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits.
Take the initial count as 0.
Take the initial count as 0.
Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i)).
Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i)).
Calculate last digit as ldigit=i%10.
Calculate last digit as ldigit=i%10.
If ldigit==fdigit, means they are the same. Increment count.
If ldigit==fdigit, means they are the same. Increment count.
Return count as result.
Return count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//to find starting digit
int getFirstDigit(int num){
   while (num >= 10)
      { num = num/ 10; }
   return num;
}
int getCount(int fst,int lst){
   int count=0;
   for(int i=fst;i<=lst;i++){
      int fdigit=getFirstDigit(i);
      int ldigit=i%10; //to get last digit
      if(fdigit==ldigit) //if both are equal increment count
         { ++count; }
   }
   return count;
}
int main(){
   int first = 10, last = 23;
   cout<<"Numbers with same first and last digits:"<<getCount(first, last);
   return 0;
}
If we run the above code it will generate the following output −
Numbers with same first and last digits:2
C Language | Set 7 - GeeksforGeeks

27 Mar, 2017
Following questions have been asked in GATE CS 2010 exam.
1. What does the following program print?
#include<stdio.h>void f(int *p, int *q){  p = q; *p = 2;}int i = 0, j = 1;int main(){  f(&i, &j);  printf("%d %d \n", i, j);  getchar();  return 0;}
(A) 2 2(B) 2 1(C) 0 1(D) 0 2
Answer (D)See below f() with comments for explanation.
/* p points to i and q points to j */void f(int *p, int *q){  p = q;    /* p also points to j now */ *p = 2;   /* Value of j is changed to 2 now */}
2. What is the value printed by the following C program?
#include<stdio.h>int f(int *a, int n){  if(n <= 0) return 0;  else if(*a % 2 == 0) return *a + f(a+1, n-1);  else return *a - f(a+1, n-1);}  int main(){  int a[] = {12, 7, 13, 4, 11, 6};  printf("%d", f(a, 6));  getchar();  return 0;}
(A) -9(B) 5(C) 15(D) 19
Answer (C)f() is a recursive function which adds f(a+1, n-1) to *a if *a is even. If *a is odd then f() subtracts f(a+1, n-1) from *a. See below recursion tree for execution of f(a, 6)..
 f(add(12), 6) /*Since 12 is first element. a contains address of 12 */
    |
    |
 12 + f(add(7), 5) /* Since 7 is the next element, a+1 contains address of 7 */
        |
        |
     7 - f(add(13), 4)
              |
              |
           13 - f(add(4), 3)
                     |
                     |
                  4 + f(add(11), 2)
                             |
                             |
                           11 - f(add(6), 1)
                                    |
                                    |
                                 6 + 0

So, the final returned value is 12 + (7 – (13 – (4 + (11 – (6 + 0))))) = 15
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2010
GATE-CS-C-Language
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Semaphores in Process Synchronization
Inter Process Communication (IPC)
Introduction of Operating System - Set 1
Data encryption standard (DES) | Set 1
Data Structures and Algorithms | Set 25
Operating Systems | Set 1
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 1
Computer Networks | Set 2
strrev() function in PHP

The strrev() function is used to reverse a string. It returns the reversed string.
strrev(str)
str − The string to be reversed
str − The string to be reversed
The strrev() function returns the reversed string.
The following is an example −
 Live Demo
<?php
   echo strrev("Jack");
?>
The following is the output −
kcaJ
Let us see another example −
 Live Demo
<?php
   $val = 7837;
   echo strrev($val);
?>
The following is the output −
7387
Merge two arrays using C# AddRange() method

Firstly, set two arrays −
int[] arr1 = { 15, 20, 27, 56 };
int[] arr2 = { 62, 69, 76, 92 };
Now create a new list and use AddRange() method to merge −
var myList = new List<int>();
myList.AddRange(arr1);
myList.AddRange(arr2);
After that, convert the merged collection to an array −
int[] arr3 = myList.ToArray()
Let us see the complete code
 Live Demo
using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int[] arr1 = { 15, 20, 27, 56 };
      int[] arr2 = { 62, 69, 76, 92 };
      // displaying array1
      Console.WriteLine("Array 1...");
      foreach(int ele in arr1) {
         Console.WriteLine(ele);
      }
      // displaying array2
      Console.WriteLine("Array 2...");
      foreach(int ele in arr2) {
         Console.WriteLine(ele);
      }
      var myList = new List<int>();
      myList.AddRange(arr1);
      myList.AddRange(arr2);
      int[] arr3 = myList.ToArray();
      Console.WriteLine("Merged array..");
      foreach (int res in arr3) {
         Console.WriteLine(res);
      }
   }
}
Array 1...
15
20
27
56
Array 2...
62
69
76
92
Merged array..
15
20
27
56
62
69
76
92
How to convert Decimal to Hexadecimal in Java

To convert decimal to hexadecimal, use any of the two methods i.e.
Integer.toHexString() − It returns a string representation of the integer argument as an unsigned integer in base 16.
Integer.toHexString() − It returns a string representation of the integer argument as an unsigned integer in base 16.
Integer.parseInt() − It allows you to set the radix as well, for example, for hexadecimal set it as 16.
Integer.parseInt() − It allows you to set the radix as well, for example, for hexadecimal set it as 16.
Let us see an example now to convert decimal to hexadecimal using Integer.toHexString() method.
 Live Demo
public class Demo {
   public static void main( String args[] ) {
      int dec = 158;
      System.out.println(Integer.toHexString(dec));
   }
}
9e
Let us see an example now to convert decimal to hexadecimal using Integer.parseInt() method.
 Live Demo
public class Demo {
   public static void main( String args[] ) {
      String str = "3d8";
      System.out.println(Integer.parseInt(str, 16));
   }
}
984
Batch Script - Reading from the Registry

Reading from the registry is done via the REG QUERY command. This command can be used to retrieve values of any key from within the registry.
REG QUERY [ROOT\]RegKey /v ValueName [/s] 
REG QUERY [ROOT\]RegKey /ve --This returns the (default) value

Where RegKey is the key which needs to be searched for in the registry.
@echo off 
REG QUERY HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\
The above command will query all the keys and their respective values under the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\
The output will display all the keys and values under the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\

This location in the registry has some key information about the windows system such as the System Directory location.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows
   Directory REG_EXPAND_SZ %SystemRoot%
   SystemDirectory REG_EXPAND_SZ %SystemRoot%\system32
   NoInteractiveServices REG_DWORD 0x1
   CSDBuildNumber REG_DWORD 0x4000
   ShellErrorMode REG_DWORD 0x1
   ComponentizedBuild REG_DWORD 0x1
   CSDVersion REG_DWORD 0x0
   ErrorMode REG_DWORD 0x0
   CSDReleaseType REG_DWORD 0x0
   ShutdownTime REG_BINARY 3AFEF5D05D46D101	

 Print
 Add Notes
 Bookmark this page
Aptitude - Arithmetic Online Quiz

Following quiz provides Multiple Choice Questions (MCQs) related to Basic Arithmetic. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - If an A.P. have 4th term as 14 and 12th term as 70. What will be its first term?
A - -10
B - -7
C - 7
D - 10
  
Let's have first term as a, common difference is d then  
a + 3d = 14 ... (i)  
a + 11d = 70 ... (ii)  
Subtracting (i) from (ii)  
=> 8d = 56  => d = 7  
Using (i)  
=> a = 14 - 3d  = -7  

Q 2 - Which of the following is equal to 205x15?
A - 205x10+15x5
B - 200x15+5x15
C - 200(1+5)
D - 200+5x1x5
  
205x15= (200+5) x15
=200x15+5x15  
Q 3 - If |x - 5| = 10 and |2y - 12| = 8, what is the minimum possible value of y/x?
A - -2
B - -1
C - -3/5
D - 2/-5
  
 y =10, 2.  
 x =15,-5.  
 So minimum value would be 10 / -5 = -2  
Q 4 - If (28)3 is subtracted from the square of a number, the answer so obtained is 1457. What is the number?
A - 127
B - 136
C - 142
D - 153
 
 Let the number = x 
 According to question, x2 - 283 = 1457 
 or, 
 x = 153 
Q 5 - How many numbers between 200 and 600 are exactly divisible by 4, 5 and 6?
A - 5
B - 6
C - 7
D - 8
 
 L.C.M. of 4, 5 and 6 (2 x 2) x (5) x (3 x 2) = 4 x 5 x 3 = 60 
 ∴ required numbers are 240, 300, 360, 420, 480, 540 which are 6. 
Q 6 - What is the sum of all even numbers between 100 and 200 including both?
A - 3750
B - 6200
C - 6500
D - 7550
  
 Required sum = 100 + 102 + ... + 200 which is an A.P. where a = 100, d = 2, l = 200.  
 Using formula Tn = a + (n - 1)d  
 Tn = 100 + (n-1)2 = 200  
 => 2n = 200 - 98 = 102  
 => n = 51  
 Now Using formula Sn = (n/2)(a + l)  
 ∴ Required sum = (51/2)(100+200)  = 51 x 150  = 7550 
Q 7 - If first term of a G.P. is 5, common ratio is 2 what is the 8th term?
A - 160
B - 256
C - 640
D - 1280
  
 Here a = 5,  r = 2, n = 8. 
 Using formula Tn = arn- 1 
 Tn = 5 x 2(8-1)  
 =5 x 27  
 =5 x 128  =640 
Q 8 - 142 + 152 ... + 302 = ?
A - 3836
B - 8336
C - 8366
D - 8636
  
 Using formula  (12 + 32 ... +  n2) = [n(n+1)(2n+1)]/6  
 142 + 152 ... + 302 = (12 + 22 ... + 302) - (12 + 22 ... + 132)  
 = (30 x 31 x 61)/ 6 - (13 x 14 x 27) / 6  
 = 9455 - 819  = 8636 
Q 9 - If an A.P. have 4th term as 16 and 12th term as 80. What will be its first term?
A - -10
B - -7
C - 7
D - 10
  
 Let's have first term as a, common difference is d then  
 a + 3d = 16 ... (i)  
 a + 11d = 80 ... (ii)  
 Subtracting (i) from (ii)  
 => 8d = 64  => d = 8  
 Using (i)  
 => a = 14 - 3d  = -10  
Q 10 - 142 + 152 ... + 502 = ?
A - 6738396
B - 6738416
C - 6738400
D - 6738406
  
 Using formula  (12 + 32 ... +  n2) = [n(n+1)(2n+1)]/6  
 142 + 152 ... + 502 = (12 + 22 ... + 502) - (12 + 22 ... + 132)  
 = (50 x 51 x 101)/ 6 - (13 x 14 x 27) / 6  
 = 6739225 - 819  
 = 6738406 

    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
How does Selenium Webdriver handle the SSL certificate in Edge?

We can handle SSL certificates in Edge browser with Selenium webdriver. This is done with the help of the EdgeOptions class. We shall create an object of this class and set the parameter setAcceptInsecureCerts to the true value.
Finally, this information has to be passed to the webdriver object to get the desired browser settings. An SSL is a protocol designed to establish a secured connection between the server and the browser.
EdgeOptions e = new EdgeOptions();
e.setAcceptInsecureCerts(true);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeBrwserSSL{
   public static void main(String[] args) {
      System.setProperty("webdriver.edge.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\msedgedriver.exe");
      //instance of EdgeOptions
      EdgeOptions e = new EdgeOptions();
      //configure setAcceptInsecureCerts to true boolean value
      e.setAcceptInsecureCerts(true);
      //object of EdgeDriver
      WebDriver driver = new EdgeDriver(e);
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("application url");
   }
}
Python MySQL – GROUP BY and HAVING Clause

09 May, 2021
In this article, we will see how to perform groupby() and HAVING() operations on SQL using Python. Here we will consider a college database to perform group by operation on the department with respect to student strength.
The GROUP BY statement groups rows that have the same values into single based on the aggregate function used. Aggregate functions are (COUNT(), MAX(), MIN(), SUM(), AVG()).
Syntax: SELECT aggregare_function(column1),column2,...,columnn
FROM table_name
GROUP BY column_name;
Database in use:
Example:
Python3
# Establish connection to MySQL databaseimport mysql.connector   database = mysql.connector.connect(     host="localhost",     user="root",     password="",     database="sravan")   # Creating cursor objectcur_object = database.cursor()   # Execute the query find = "SELECT  department,sum(strength) from \college_data GROUP BY(department)";cur_object.execute(find)   # fetching all resultsdata = cur_object.fetchall() print("Total departments with count : ")print(" ")for res in data:     print(res[0],res[1],sep="--")   # Close database connection database.close() 
Output:
Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The having clause is always used after the Group By clause.
Syntax: SELECT aggregate_function (column_names),column1,column2,...,columnn FROM table_name
GROUP BY column_name
HAVING aggregate_function(column_name) condition;
Database in use:
Example:
Python3
# Establish connection to MySQL databaseimport mysql.connector   # give connection with xamppdatabase = mysql.connector.connect(     host="localhost",     user="root",     password="",     database="sravan")   # Creating cursor objectcur_object = database.cursor()   find = "SELECT  department,sum(strength) from college_data\GROUP BY(department) HAVING sum(strength)<=400 ";  # Execute the query cur_object.execute(find)   # fetching all resultsdata = cur_object.fetchall() print("Total departments with count less than 400 : ")print(" ")for res in data:     print(res[0],res[1],sep="--")   # Close database connection database.close() 
Output:
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Rename Database

08 Oct, 2021
ALTER SQL command is a DDL (Data Definition Language) statement. ALTER is used to update the structure of the table in the database (like add, delete, modify the attributes of the tables in the database).In this article, we will look at how to rename a database in the SQL server by using the ALTER-Modify keyword. To rename the database we need to create the database first. So, let us create it.
Step 1: Creating Database
We are creating the database using CREATE query.
Step 2: CREATE query
The CREATE query is used to create a new database.
Query:
CREATE DATABASE Test
Output:
Step 3: Rename Database
For this, we need to use the ALTER command. ALTER keyword is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.
Renaming means we are modifying the data.
Hence, we will use ALTER – MODIFY.
Query:
ALTER DATABASE Test MODIFY NAME = Example
Output:
The database name is changed from Test to Example.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Replace vowels by next vowel

14 Oct, 2020
Given a String replace each vowel with next vowel in series.
Input : test_str = ‘geekforgeeks’Output : giikfurgiiksExplanation : After e, next vowel is i, all e replaced by i.
Input : test_str = ‘geekforgeeks is best’Output : giikfurgiiks os bistExplanation : After e, next vowel is i, all e replaced by i.
Method #1 : Using zip() + list comprehension
This is one of the ways in which this task can be performed. In this we perform the task of forming replace dictionary using zip() and then list comprehension is used to perform the task of replacement with next vowel.
Python3
# Python3 code to demonstrate working of # Replace vowels by next vowel# Using list comprehension + zip()  # initializing stringtest_str = 'geekforgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # constructing dictionary using zip()vow = 'a e i o u'.split()temp = dict(zip(vow, vow[1:] + [vow[0]]))  # list comprehension to perform replacementres = "".join([temp.get(ele, ele) for ele in test_str])  # printing result print("The replaced string : " + str(res)) 
The original string is : geekforgeeks
The replaced string : giikfurgiiks

Method #2 : Using dictionary comprehension + list comprehension
This is yet another way in which this task can be performed. In this we perform the task of mapping using dictionary comprehension and list comprehension is used to perform task of replacement.
Python3
# Python3 code to demonstrate working of # Replace vowels by next vowel# Using list comprehension + dictionary comprehension  # initializing stringtest_str = 'geekforgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # constructing dictionary using dictionary comprehensionvow = "aeiou"temp = {vow[idx] : vow[(idx + 1) % len(vow)] for idx in range(len(vow))}  # using get() to map elements to dictionary and join to convertres = "".join([temp.get(ele, ele) for ele in test_str])  # printing result print("The replaced string : " + str(res)) 
The original string is : geekforgeeks
The replaced string : giikfurgiiks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NumPy – 3D matrix multiplication

12 Nov, 2020
A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors.
Let us consider an example matrix A of shape (3,3,2) multiplied with another 3D matrix B of shape (3,2,4).
Python
import numpy as np  np.random.seed(42)  A = np.random.randint(0, 10, size=(3, 3, 2))B = np.random.randint(0, 10, size=(3, 2, 4))  print("A:\n{}, shape={}\nB:\n{}, shape={}".format(  A, A.shape, B, B.shape))
OUTPUT:
The first matrix is a stack of three 2D matrices each of shape (3,2), and the second matrix is a stack of 3 2D matrices, each of shape (2,4).
The matrix multiplication between these two will involve three multiplications between corresponding 2D matrices of A and B having shapes (3,2) and (2,4) respectively. Specifically, the first multiplication will be between A[0] and B[0], the second multiplication will be between A[1] and B[1], and finally, the third multiplication will be between A[2] and B[2]. The result of each individual multiplication of 2D matrices will be of shape (3,4). Hence, the final product of the two 3D matrices will be a matrix of shape (3,3,4).
Let’s realize this using code.
Python
C = np.matmul(A, B)  print("Product C:\n{}, shape={}".format(C, C.shape))
Output:
Python numpy-Linear Algebra
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
numpy matrix operations | repmat() function

21 Feb, 2019
numpy.matlib.repmat() is another function for doing matrix operations in numpy. It returns Repeat a 0-D, 1-D or 2-D array or matrix M x N times.
Syntax : numpy.matlib.repmat(a, m, n)
Parameters :a : [array_like] The input array or matrix which to be repeated.m, n : [int] The number of times a is repeated along the first and second axes.
Return : [ndarray] repeating array.
Code #1 :
# Python program explaining# numpy.matlib.repmat() function  # importing numpy and matrix libraryimport numpy as geekimport numpy.matlib  # creating input array using  # array function in_arr = geek.array([[1, 0, 2], [3, 4, 5]])print("Input array", in_arr)   # making a new array # using repmat() function out_mat = geek.matlib.repmat(in_arr, 2, 3) print ("Output repeated matrix : ", out_mat) 
Input array [[1 0 2]
 [3 4 5]]
Output repeated matrix :  [[1 0 2 1 0 2 1 0 2]
 [3 4 5 3 4 5 3 4 5]
 [1 0 2 1 0 2 1 0 2]
 [3 4 5 3 4 5 3 4 5]]

 
Code #2 :
# Python program explaining# numpy.matlib.repmat() function  # importing numpy and matrix libraryimport numpy as geekimport numpy.matlib  # creating input array using  # arange function in_arr = geek.arange(3)print("Input array", in_arr)   # making a new array # using repmat() function out_mat = geek.matlib.repmat(in_arr, 2, 2) print ("Output repeated matrix : ", out_mat) 
Input array [0 1 2]
Output repeated matrix :  [[0 1 2 0 1 2]
 [0 1 2 0 1 2]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – seaborn.swarmplot() method

18 Aug, 2020
Prerequisite : Fundamentals of Seaborn
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. There is just something extraordinary about a well-designed visualization. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well.
Draw a categorical scatterplot with non-overlapping points. A swarm plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution. Arranging the points properly requires an accurate transformation between data and point coordinates. This means that non-default axis limits must be set *before* drawing the plot.
Syntax : seaborn.swarmplot(parameters)
Parameters :
x, y, hue : Inputs for plotting long-form data.
data : Dataset for plotting.
order, hue_order : Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.
dodge : To separate the strips for different hue levels along the categorical axis
orient : Orientation of the plot (vertical or horizontal).
color : Color for all of the elements, or seed for a gradient palette.
palette : Colors to use for the different levels of the hue variable.
size : Radius of the markers, in points.
edgecolor : Color of the lines around each point.
linewidth : Width of the gray lines that frame the plot elements.
ax : Axes object to draw the plot onto, otherwise uses the current Axes.
kwargs : Other keyword arguments
Returns : Returns the Axes object with the plot drawn onto it.
Below is the implementation of above method with some examples :
Example 1 :
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("tips")  # plot the swarmplot# size set to 5sns.swarmplot(x ="day", y = "total_bill",               data = data, size = 5)plt.show()
Output :
Example 2 :
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("tips")  # plot the swarmplot# hue by size# oriented to horizontalsns.swarmplot(y = "day", x = "total_bill", hue = "size",               orient = "h", data = data)plt.show()
Output :
Example 3 :
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("tips")  # plot the swarmplot# hue by smoker# dodge = Truesns.swarmplot(x = "sex", y = "total_bill", hue = "smoker",               data = data, dodge = True)plt.show()
Output :
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB insertMany() Method – db.Collection.insertMany()

28 Jan, 2021
The insertMany() method inserts one or more documents in the collection. It takes array of documents to insert in the collection. 
By default, documents are inserted in the given order if you want to insert documents in unordered, then set the value of ordered to false.
Using this method you can also create a collection by inserting documents.
You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error.
This method can also throw a BulkWriteError exception.
This method can also be used inside multi-document transactions.
Syntax:
db.Collection_name.insertMany(
[<document 1>, <document 2>, ...],
{
    writeConcern: <document>,
    ordered: <boolean>
})
Parameters:
The first parameter is the array of documents to insert into the collection.
The second parameter is optional.
Optional Parameters:
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
ordered: The type of this parameter is boolean that specifies whether the MongoDB instance should perform an ordered or unordered insertion. If it is true insertion will be in ordered manner otherwise in unordered manner. Default it is true.
Return:
This method returns :
Boolean acknowledged as true if write concern was enabled or false if write concern was disabled.
The insertedId field with the _id value of the inserted document.
Examples:
In the following examples, we are working with:
Database: gfg
Collection: student
Document: Empty
Example 1: Inserts the one document that contains the name and age of the student
db.student.insertMany([{name:"Akshay",age:18}])
Example 2: Insert the array of documents that contains the name and age of the students
db.student.insertMany([{name:"Ajay",age:20},
                       {name:"Bina",age:24},
                       {name:"Ram",age:23}])
Example 3: Insert multiple documents with _id field
db.student.insertMany([{_id:"stu200", name:"Ammu", age:18},
                       {_id:"stu201", name:"Priya", age:29}])
Example 4: Insert unordered documents by setting the value of ordered option to false
db.student.insertMany([{_id:"stu203",name:"Soniya",age:28}, 
                       {_id:"stu202", name:"Priya", age:25}], 
                       {ordered: false})
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Spring Boot - CRUD Operations using MongoDB
Teradata - Statistics

Teradata optimizer comes up with an execution strategy for every SQL query. This execution strategy is based on the statistics collected on the tables used within the SQL query. Statistics on the table is collected using COLLECT STATISTICS command. Optimizer requires environment information and data demographics to come up with optimal execution strategy.
Number of Nodes, AMPs and CPUs
Amount of memory
Number of rows
Row size
Range of values in the table
Number of rows per value
Number of Nulls
There are three approaches to collect statistics on the table.
Random AMP Sampling
Full statistics collection
Using SAMPLE option
COLLECT STATISTICS command is used to collect statistics on a table.
Following is the basic syntax to collect statistics on a table.
COLLECT [SUMMARY] STATISTICS   
INDEX (indexname) COLUMN (columnname) 
ON <tablename>;

The following example collects statistics on EmployeeNo column of Employee table.
COLLECT STATISTICS COLUMN(EmployeeNo) ON Employee;
When the above query is executed, it produces the following output.
*** Update completed. 2 rows changed. 
*** Total elapsed time was 1 second.

You can view the collected statistics using HELP STATISTICS command.
Following is the syntax to view the statistics collected.
HELP STATISTICS <tablename>; 

Following is an example to view the statistics collected on Employee table.
HELP STATISTICS employee;
When the above query is executed, it produces the following result.
  Date       Time      Unique Values           Column Names 
--------   -------- -------------------- ----------------------- 
16/01/01   08:07:04         5                       * 
16/01/01   07:24:16         3                   DepartmentNo 
16/01/01   08:07:04         5                   EmployeeNo
Select First Row of Each Group in DataFrame in R

23 Sep, 2021
In this article, we will discuss how to select the first row of each group in Dataframe using R programming language.
The duplicated() method is used to determine which of the elements of a dataframe are duplicates of other elements. The method returns a logical vector which tells which of the rows of the dataframe are duplicates. 
Syntax:
duplicated(data-frame$col-name)
The non-duplicated rows are taken using the complemented duplicated() method, and referred to using the dataframe indexing methods, where all the columns are taken and the rows are the ones filtered out using the duplicated() method. The row numbers of the original dataframe are retained in the final output. 
Example: Selecting first row from each group
R
# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2),                               rep('Grp2',2),                               rep('Grp3',2)),                         col2=rep(c(1:3),2),                        col3=rep(1:2,3)                         )  print("Original DataFrame")print(data_frame1)  print("Modified DataFrame")  # computing sum over rest of columnsdata_frame1[!duplicated(data_frame1$col1), ]
Output:
[1] "Original DataFrame" 
  col1 col2 col3 
1 Grp1    1    1 
2 Grp1    2    2 
3 Grp2    3    1 
4 Grp2    1    2 
5 Grp3    2    1 
6 Grp3    3    2 
[1] "Modified DataFrame" 
  col1 col2 col3 
1 Grp1    1   1 
3 Grp2    3   1 
5 Grp3    2   1
The following code snippet illustrates the usage of duplicated function, applied over multiple columns. The columns can be clubbed together using the c() method. 
Example: Selecting first row of each group 
R
# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2),                               rep('Grp2',2),                               rep('Grp3',2)),                         col2=rep(1,2),                        col3=rep(1,3)                         )  print("Original DataFrame")print(data_frame1)  # grouping by col3print("Modified DataFrame")  # computing groups over col3 and col2data_frame1[!duplicated(c(data_frame1$col3,data_frame1$col2)), ]
Output:
[1] "Original DataFrame" 
col1 col2 col3 
1 Grp1    1    1 
2 Grp1    1    1 
3 Grp2    1    1 
4 Grp2    1    1 
5 Grp3    1    1 
6 Grp3    1    1 
[1] "Modified DataFrame" 
col1 col2 col3 
1 Grp1    1    1
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
What is the difference between List and IList in C#?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index. The IList interface implemented from two interfaces and they are ICollection and IEnumerable.
List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList. The major difference between List and IList is that List is a concrete class and IList is an interface. Overall, List is a concrete type that implements the IList interface.
using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         IList<string> ilist = new IList<string>();
         //This will throw error as we cannot create instance for an IList as it is an interface.
         ilist.Add("Mark");
         ilist.Add("John");
         foreach (string list in ilist){
            Console.WriteLine(list);
         }
      }
   }
}
 Live Demo
using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         IList<string> ilist = new List<string>();
         ilist.Add("Mark");
         ilist.Add("John");
         List<string> list = new List<string>();
         ilist.Add("Mark");
         ilist.Add("John");
         foreach (string lst in ilist){
            Console.WriteLine(lst);
         }
         foreach (string lst in list){
            Console.WriteLine(lst);
         }
         Console.ReadLine();
      }
   }
}
The output of the above code is
Mark
John
Mark
John
How can I trigger a JavaScript click event?

To trigger a JavaScript click event, let us see the example of mouse hover.
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p>Hover over the button.</p>
      <form>
         <input type="button" id="test" value="Hover" onmouseover="display()" onclick="alert('click event')">
      </form>
      <script>
         function display() {
            document.getElementById("test").click();
         }
      </script>
   </body>
</html>