code-rag-bench/online-tutorials huggingface dataset:
Get the First parts of a Data Set in R Programming – head() Function

30 Jun, 2020
head() function in R Language is used to get the first parts of a vector, matrix, table, data frame or function.
Syntax: head(x, n)
Parameters:x: specified data typesn: number of row need to be printed
Example 1:
# R program to illustrate# head function  # Calling the head() function to # get the iris demo datasethead(iris)
Output:
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Example 2:
# R program to illustrate# head function  # Calling the head() function to # get the iris demo dataset in# 4 rowshead(iris, 4)
Output:
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa

R DataFrame-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create a green button (success) with Bootstrap

Use the .btn-success class in Bootstrap to create a green button that indicates success
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet"
         href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>Click below if you want to know the result of successful students:</p>
      <button type = "button" class = "btn btn-success">Submit</button>
   </body>
</html>
How to hide elements in responsive layout using CSS ?

11 Oct, 2019
CSS can be used to hide or display elements of the page. This can be used in a responsive website to show certain elements that are only possible to interact with a larger screen size for a good user experience.
Media queries are the technique introduced in CSS3 to help to design responsive websites. A media query has two parts, one is the optional media type which helps to describe the general class of devices that the media query will work. The other one is the media feature which describe specific characteristics of device where the page is to be displayed. These can be tested for their value to accordingly change the behavior of the contents of the page.
The media type used here is screen, which is used with the ‘only’ keyword so that the media query only affects the selected screens. The media feature can be changed based on the width. For example, it can be used with the width media feature. This can be modified to change when the width is set to a particular value like using the min-width and max-width. Other supported media features can be used to check for values that help in a responsive website.
Syntax:
// Check if the height is at least 600px@media only screen and (min-width: 600px) {    .large {        display: block;    }}
In this example, the elements are hide by setting the ‘display’ property to ‘none’. The media queries contain classes that will set the display property to blockExample:
<!DOCTYPE html><html>  <head>    <title>        How to hide elements in responsive        layout using CSS?    </title>          <style>        .box {            margin: 20px;            border: 1px dotted;            height: 100px;            width: 100px;            background-color: lightgreen;            display: none;        }          /* Check if the screen size is at least 600px */        @media only screen and (min-width: 600px) {            .lg {                display: block;            }        }          /* check if the screen size is at least 400px */        @media only screen and (min-width: 400px) {            .md {                display: block;            }        }          /* check if the screen size is at least 100px */        @media only screen and (min-width: 100px) {            .sm {                display: block;            }        }    </style></head>  <body>    <h1>        Hiding elements in responsive        layout using CSS?    </h1>      <div class="box lg">        This is only visible on        large devices    </div>          <div class="box md">        This is only visible on        medium and large devices    </div>          <div class="box sm">        This is only visible on smaller,        medium and large devices    </div></body>  </html>
Output:
When the screen size is at least 600px:
When the screen size is at least 400px:
When the screen size is at least 100px:
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Count the array elements with factors less than or equal to the factors of given x

12 Jun, 2022
Given an array, the task is to count the elements of array whose factors are less than the given number x. Examples:
Input: arr = [2, 12, 4, 6], x = 6 Output: 2 factors of x = 6 is [1, 2, 3] factors of arr[0] = 2 is [1] factors of arr[1] = 12 is [1, 2, 3, 4] factors of arr[2] = 4 is [1, 2] factors of arr[3] = 6 is [1, 2, 3] so only arr[0] and arr[2] are the answer.
Approach: Find out factors of all the elements and that of given xand after that compare all of them if factors of elements are less than that of factors of x, then increment the count. Below is the implementation of above problem – 
Python3
from math import ceil, sqrt  # function to count the factors of an arraydef factorscount(x):    count = 0    for i in range(1,ceil(sqrt(x))):        if x%i==i:            count+=1        else:            count+=2    return count  def Totalcount(arr, x):         # count of factors of  given x    count_fac = factorscount(x)         # store the count of each factors    arr_fac = [factorscount(i) for i in arr]      ans = 0      for i in arr_fac:        # if factors count of element of array is        #small than that of given number        if i<count_fac:            ans+=1      return ans    # Driver code  arr = [2,12,4,6]x = 6print(Totalcount(arr, x))
2
Time Complexity: O(√x+n√k) where n is the size of the array, x is the given number, and k is the maximum element in the array.Auxiliary Space: O(n)
pushpeshrajdx01
math
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Python program to change values in a Dictionary

08 Dec, 2020
Given a dictionary in Python, the task is to write a Python program to change the value in one of the key-value pairs. This article discusses mechanisms to do this effectively.
Examples:
Input: {'hari': 1, 'dita': 2}
Output: {'hari': 1, 'dita': 4}

Input: {'hari': 1, 'dita': 2}
Output: {'hari': 3, 'dita': 5}
Method 1
In this we refer to the key of the value to be changed and supply it with a new value.
Example:
Python3
# declaring dictionarydict = {'hari': 1, 'dita': 2}  # original dictionaryprint("initial dictionary-", dict)  # changing the key value from  2 to 4dict['dita'] = 4  # dictionary after updateprint("dictionary after modification-", dict)
Output:
initial dictionary- {‘hari’: 1, ‘dita’: 2} 
dictionary after modification- {‘hari’: 1, ‘dita’: 4}
Method 2: 
In this method we use zip() function, which aggregates the iterable and combines them into a tuple form.
Example:
Python3
# declaring dictionarydict1 = {'hari': 1, 'dita': 2}  # original dictionaryprint("initial dictionary-", dict1)  # list of values which will replace the values of dict1list1 = [3, 5]  # this preserves the keys and modifies the valuesdict1 = dict(zip(list(dict1.keys()), list1))  # modified dictionaryprint("dictionary after modification-", dict1)
Output:
initial dictionary- {‘hari’: 1, ‘dita’: 2} 
dictionary after modification- {‘hari’: 3, ‘dita’: 5}
Python dictionary-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
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
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
Change the legend position in Matplotlib

26 May, 2021
In this article, we will learn how to Change the legend position in Matplotlib. Let’s discuss some concepts :
Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002.
A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes.
The attribute Loc in legend() is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings best upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, and center place the legend at the corresponding corner of the axes/figure.
Approach:
Import Library (Matplotlib)Import / create data.Plot a chart.Add legend.Set position of legend using loc.
Import Library (Matplotlib)
Import / create data.
Plot a chart.
Add legend.
Set position of legend using loc.
Example 1:
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legendplt.legend(['Legend'])plt.show()
Output:
Without setting location of legend (best)
Example 2:
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to upper leftplt.legend(['Legend'], loc='upper left')plt.show()
Output:
Legend in Upper left
Example 3:
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower left i.e; 4plt.legend(['Legend'], loc=4)plt.show()
Output:
Legend in Lower left
Example 4:
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower rightplt.legend(['Legend'], loc='lower right')plt.show()
Output:
Legend in Lower right
sweetyty
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
C# | Tuple Class

29 Nov, 2019
In C#, Tuple class is used to provide static methods for creating tuples and this class defined under System namespace. This class itself does not represent a tuple, but it provides static methods that are used to create an instance of the tuple type. Or in other words, the Tuple class provides helper methods that are used to instantiate tuple objects without having to explicitly specify the type of each tuple component. In tuple, you can only store elements from one to eight, if you try to store elements greater than eight without nested tuple, then the compiler will give an error.
Generally, tuples are used:
To represent multiple data into a single data set.
To create, manipulate, and access data set.
To return multiple values from a method without using out parameters.
To pass multiple values to a method with the help of single parameters.
Note: You can also, create a tuple with the help of the constructors which are provided by tuple classes, but in constructors, you have to specify the type of the elements present in the tuple as shown in the below example:
Example:
// C# program to create tuple // using tuple constructor.using System;  class GFG {      // Main method    static public void Main()    {          // Creating tuple with seven elements        // Using Tuple<T1, T2, T3, T4, T5, T6,         // T7>(T1, T2, T3, T4, T5, T6, T7) constructor        Tuple<int, int, int, int, int, int, int> My_Tuple = new Tuple<int,                int, int, int, int, int, int>(22, 334, 54, 65, 76, 87, 98);          Console.WriteLine("Element 1: " + My_Tuple.Item1);        Console.WriteLine("Element 2: " + My_Tuple.Item2);        Console.WriteLine("Element 3: " + My_Tuple.Item3);        Console.WriteLine("Element 4: " + My_Tuple.Item4);        Console.WriteLine("Element 5: " + My_Tuple.Item5);        Console.WriteLine("Element 6: " + My_Tuple.Item6);        Console.WriteLine("Element 7: " + My_Tuple.Item7);    }}
Element 1: 22
Element 2: 334
Element 3: 54
Element 4: 65
Element 5: 76
Element 6: 87
Element 7: 98

Example:
// C# program to create 3-tuple // using create methodusing System;  class GFG {      // Main method    static public void Main()    {          // Creating tuple with three elements        // Using Create method        var My_Tuple = Tuple.Create("Geeks", 2323, 'g');          Console.WriteLine("Element 1: " + My_Tuple.Item1);        Console.WriteLine("Element 2: " + My_Tuple.Item2);        Console.WriteLine("Element 3: " + My_Tuple.Item3);    }}
Element 1: Geeks
Element 2: 2323
Element 3: g

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.tuple?view=netframework-4.8#definition
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
zlib.compress(s) in python

06 Mar, 2020
With the help of zlib.compress(s) method, we can get compress the bytes of string by using zlib.compress(s) method.
Syntax : zlib.compress(string)Return : Return compressed string.
Example #1 :In this example we can see that by using zlib.compress(s) method, we are able to compress the string in the byte format by using this method.
# import zlib and compressimport zlibs = b'This is GFG author, and final year student.'print(len(s))  # using zlib.compress(s) methodt = zlib.compress(s)print(len(t))
Output :
4349
Example #2 :
# import zlib and compressimport zlibs = b'GeeksForGeeks@12345678'print(len(s))  # using zlib.compress(s) methodt = zlib.compress(s)print(len(t))
Output :
2227
Python-Miscellaneous
python-zlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Tables using Plotly in Python?

05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A table helps in organizing the data into columns and rows. The use of tables is prevalent throughout all communication, research, and data analysis.  They privilege rapid entrance and proportionately elementary comparison of information. It can be created using the Table() method of graph_objects class.
Syntax: plotly.graph_objects.Table(arg=None, cells=None, columnorder=None, columnwidth=None, header=None, **kwargs)
Parameters:
arg:  dict of properties compatible with this constructor or an instance of plotly.graph_objects.Table
cells: plotly.graph_objects.table.Cells instance or dict with compatible properties
columnorder: Specifies the rendered order of the data columns; for example, a value 2 at position 0 means that column index 0 in the data will be rendered as the third column, as columns have an index base of zero.
columnwidth: The width of columns expressed as a ratio. Columns fill the available width in proportion of their specified column widths.
header: plotly.graph_objects.table.Header instance or dict with compatible properties
Example:
Python3
import plotly.graph_objects as go  fig = go.Figure(data=[go.Table(    header=dict(values=['A', 'B']),    cells=dict(values=[[10, 20, 30, 40],                       [40, 20, 10, 50]]))])fig.show()
Output:
Adding colors in alternative rows will make it easier to understand the data more efficiently. It distinguish the data from each other and the values can be separately seen easily in the data format.
Example:
Python3
import plotly.graph_objects as go  color1 = 'lightgreen'color2 = 'lightblue'  fig = go.Figure(data=[go.Table(    header=dict(values=['A', 'B']),    cells=dict(values=[[10, 20, 30, 40],                       [40, 20, 10, 50]],               fill_color=[[color1, color2, color1,                            color2, color1]*2],))])fig.show()
Output:
It is possible to change the row and column size by using the columnwidth parameter. The width of columns is expressed as a ratio. Columns fill the available width in the proportion of their specified column widths.
Example:
Python3
import plotly.graph_objects as go  color1 = 'lightgreen'color2 = 'lightblue'  fig = go.Figure(data=[go.Table(    # Ratio for column width    columnwidth=[1, 5],    header=dict(values=['A', 'B']),    cells=dict(values=[[10, 20, 30, 40],                       [40, 20, 10, 50]],               fill_color=[[color1, color2, color1,                            color2, color1]*2],))])fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to check if all the values in a list that are greater than a given value in Python

In this tutorial, we will check whether all the elements in a list are greater than a number or not. For example, we have a list [1, 2, 3, 4, 5] and a number 0. If every value in the list is greater than the given value then, we return True else False.
It's a simple program. We write it in less than 3 minutes. Try it yourself first. If you are not able to find the solution, then, follow the below steps to write the program.
Initialise a list and any number
Loop through the list.
If yes, return **False**
Return True.
## initializing the list
   values = [1, 2, 3, 4, 5]
## number num = 0
   num_one = 1
## function to check whether all the values of the list are greater than num or not
   def check(values, num):
   ## loop
      for value in values:
         ## if value less than num returns False
         if value <= num:
            return False
   ## if the following statement executes i.e., list contains values which are greater than given num
   return True
   print(check(values, num))
   print(check(values, num_one))
If you run the above program,
True False
Another way to find it is using the all() inbuilt method. all() method returns True if every element from the iterable is True else it returns False. Let's see the program using all() method.
## initializing the list
values = [1, 2, 3, 4, 5]
## number
num = 0
num_one = 1
## function to check whether all the values of the list are greater than num or not def check(values, num):
   ## all() method
   if all(value > num for value in values):
      return True
   else:
      return False
print(check(values, num))
print(check(values, num_one))
If you run the above program,
True 
False
If you have any doubts regarding the program, please do mention them in the comment section.
How to create a Modal Box with CSS and JavaScript?

To create a modal box with CSS and JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: Arial, Helvetica, sans-serif;
   }
   .modal {
      text-align: center;
      display: none;
      position: fixed;
      z-index: 1;
      padding-top: 100px;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
   }
   .modalContent {
      font-size: 20px;
      font-weight: bold;
      background-color: #fefefe;
      margin: auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
   }
   .close {
      color: rgb(255, 65, 65);
      float: right;
      font-size: 40px;
      font-weight: bold;
   }
   .close:hover, .close:focus {
      color: #ff1010;
      cursor: pointer;
   }
</style>
</head>
<body>
<h1>Modal Example</h1>
<button class="openModal">Open Modal</button>
<h2>Click on the above button to open modal</h2>
<div class="modal">
<div class="modalContent">
<span class="close">×</span>
<p>Sample text inside modal</p>
</div>
</div>
<script>
   var modal = document.querySelector(".modal");
   var btn = document.querySelector(".openModal");
   var span = document.querySelector(".close");
   btn.addEventListener("click", () => {
      modal.style.display = "block";
   });
   span.addEventListener("click", () => {
      modal.style.display = "none";
   });
   window.onclick = function(event) {
      if (event.target == modal) {
         modal.style.display = "none";
      }
   };
</script>
</body>
</html>
The above code will produce the following output −
On clicking the Open Modal button −
Variable Length Argument in C - GeeksforGeeks

12 Nov, 2017
Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.1) Sum of given numbers.2) Minimum of given numbers.and many more.
Variable number of arguments are represented by three dotes (...)
Below is an example, to find minimum of given set of integers.
// C program to demonstrate use of variable// number of arguments.#include <stdarg.h>#include <stdio.h>  // this function returns minimum of integer// numbers passed.  First argument is count// of numbers.int min(int arg_count, ...){    int i;    int min, a;      // va_list is a type to hold information about    // variable arguments    va_list ap;      // va_start must be called before accessing    // variable argument list    va_start(ap, arg_count);      // Now arguments can be accessed one by one    // using va_arg macro. Initialize min as first    // argument in list    min = va_arg(ap, int);      // traverse rest of the arguments to find out minimum    for (i = 2; i <= arg_count; i++)        if ((a = va_arg(ap, int)) < min)            min = a;      // va_end should be executed before the function    // returns whenever va_start has been previously    // used in that function    va_end(ap);      return min;}  // Driver codeint main(){    int count = 5;    printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100));    return 0;}
Here we use macros to implement the functionality of variable arguments.
Use va_list type variable in the function definition.int a_function(int x, ...)
{
    va_list a_list;
    va_start( a_list, x );
}
int a_function(int x, ...)
{
    va_list a_list;
    va_start( a_list, x );
}
Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.
Use va_arg macro and va_list variable to access each item in argument list.
macro va_end to clean up the memory assigned to va_list variable.
Another Example :
// C program to demonstrate working of // variable arguments to find average// of multiple numbers.#include <stdarg.h>#include <stdio.h>  int average(int num, ...){    va_list valist;      int sum = 0, i;      va_start(valist, num);    for (i = 0; i < num; i++)         sum += va_arg(valist, int);      va_end(valist);      return sum / num;}  // Driver codeint main(){    printf("Average of {2, 3, 4} = %d\n",                         average(2, 3, 4));    printf("Average of {3, 5, 10, 15} = %d\n",                      average(3, 5, 10, 15));    return 0;}
Output:
Average of {2, 3, 4} = 3
Average of {3, 5, 10, 15} = 10

C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
Understanding "extern" keyword in C
How to split a string in C/C++, Python and Java?
Swap three numbers in cycle - GeeksforGeeks

28 May, 2018
Given three numbers, swap them in cyclic form. First number should get the value of third, second should get the value of first and third should get value of second.
Examples:
Input : a = 2, b = 4, c = 7
Output : a = 7, b = 2, c = 4

Input : a = 10, b = 20, c = 30
Output : a = 30, b = 10, c = 20

Prerequisite : Pointers, Call by Reference,
The idea is extend simple two variable swapping.
    // Before overwriting b, store its 
    // value in temp.
    temp = b;

    // Now do required swapping starting
    // with b.
    b = a;
    a = c;
    c = temp;

C++
C#
// C program to perform Cyclic Swapping// using Call by Reference#include <stdio.h>  void cyclicSwap(int* a, int* b, int* c){    // Before overwriting b, store its     // value in temp.    int temp = *b;      // Now do required swapping starting    // with b.    *b = *a;    *a = *c;    *c = temp;}  int main(){    int a = 2, b = 4, c = 7;      printf("Value before swapping:\n");    printf("a = %d \nb = %d \nc = %d\n", a, b, c);      cyclicSwap(&a, &b, &c);      printf("Value after swapping:\n");    printf("a = %d \nb = %d \nc = %d", a, b, c);      return 0;}
// C# program to perform Cyclic Swapping// using Call by Referenceusing System;class GFG {          static void cyclicSwap(ref int a,                    ref int b, ref int c)    {                  // Before overwriting b, store         // its value in temp.        int temp = b;              // Now do required swapping         // starting with b.        b = a;        a = c;        c = temp;    }          // Driver code    public static void Main()    {        int a = 2, b = 4, c = 7;          Console.Write("Value before swapping:\n");        Console.Write("a = " + a + "\n"+ "b = " +                     b + "\n" + "c = " + c + "\n");                  cyclicSwap(ref a, ref b, ref c);              Console.Write("Value after swapping:\n");        Console.Write("a = " + a + "\n"+ "b = " +                   b + "\n" + "c = " + c + "\n");    } }  // This code is contributed by Sam007.
Value before swapping:
a = 2 
b = 4 
c = 7
Value after swapping:
a = 7 
b = 2 
c = 4

Sam007
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Data Types
Inline Functions in C++
Pure Virtual Functions and Abstract Classes in C++
Difference between Abstract Class and Interface in Java
Destructors in C++
Python Exception Handling
Exception Handling in C++
Input and Output
Ruby | Array Join (*) method - GeeksforGeeks

07 Jan, 2020
Array#*() is an Array class method which performs set join operation on the arrays. And returns new array by concatenation of int copies of the self.
Syntax: Array.*()
Parameter: Arrays for performing the join or concatenation operation.
Return: New arrays with concatenated int copies of self
Example #1 :
# Ruby code for *() method# showing join operation  # declaring arraya = ["abc", "xyz", "dog"]  # declaring arrayb = ["cow", "cat", "dog"]  # declaring arrayc = ["cat", "1", "dog"]  # a concatenating bputs "concatenation of a and b : #{a * "toy"}\n\n"  # a concatenating cputs "concatenation of a and c : #{c * 1}\n\n"  # b concatenating cputs "concatenation of b and c : #{b * "cat_rat"}\n\n"
Output :
concatenation of a and b : abctoyxyztoydog

concatenation of a and c : ["cat", "1", "dog"]

concatenation of b and c : cowcat_ratcatcat_ratdog

Example #2 :
# Ruby code for *() method# showing join operation  # declaring arraya = ["abc", "xyz", "dog"]  # declaring arrayb = ["cow", "cat", "dog"]  # declaring arrayc = ["cat", "1", "dog"]  # a concatenating bputs "concatenation of a and b : #{a * 2}\n\n"  # a concatenating cputs "concatenation of a and c : #{a * 1}\n\n"  # b concatenating cputs "concatenation of b and c : #{b * "34"}\n\n"  # b concatenating cputs "concatenation of b and c : #{c * "toy"}\n\n"
Output :
concatenation of a and b : ["abc", "xyz", "dog", "abc", "xyz", "dog"]

concatenation of a and c : ["abc", "xyz", "dog"]

concatenation of b and c : cow34cat34dog

concatenation of b and c : cattoy1toydog
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method
Ruby | String gsub! Method
How to change the color of ttk button in Tkinter?

Tkinter widgets have a consistent look and style across all the platforms and operating systems. Ttk works like CSS in an HTML script. It has many inbuilt functions, modules and methods that add style to a regular tkinter widget. Tkinter ttk buttons generally have a default color scheme, thus we can change the background color of these buttons by configuration method.
In this example, we will create a button which when pressed will change its style.
#Import the necessary library
import itertools
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter window
win = Tk()
#Set the geometry of tkinter window
win.geometry("750x250")
#Define the style
style_1 = {'fg': 'black', 'bg': 'RoyalBlue3', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_2 = {'fg': 'white', 'bg': 'OliveDrab2', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_3 = {'fg': 'black', 'bg': 'purple1', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_4 = {'fg': 'white', 'bg': 'coral2', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_cycle = itertools.cycle([style_1, style_2, style_3, style_4 ])
#Define a function to update the button style
def update_style():
style = next(style_cycle)
button.configure(**style)
#Create a tk button
button = Button(win,width=40,font=('Helvetica 18 bold'), text="Change
Style", command=update_style)
button.pack(padx=50, pady=50)
win.mainloop()
Running the above code will display a window with a button. When you click the button, it will switch the style of background color and text color.
Now, click the button to change the color of the Button.
How to submit a form in Selenium webdriver if submit button can't be identified?

We can submit a form in Selenium webdriver even if the submit button cannot be identified. This can be achieved by locating any element within the form tag and the applying submit method on it. A form in the html code is identified by the <form> tag.
Let us investigate the html code of element with in a form tag −
In the above example, we shall try to submit the form with the help of the Email or Password field and not by clicking on the Sign in button.
driver.findElement(By.className("input__input")).sendKeys("96968547");
driver.findElement(By.className("session_password")).sendKeys("test123");
driver.findElement(By.className("session_password")).submit();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class SubmitFrm{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      // identify element within form
      WebElement m=driver.findElement(By.id("session_key"));
      m.sendKeys("96968547");
      WebElement n=driver.findElement(By.id("session_password"));
      n.sendKeys("test12");
      //submit form
      n.submit();
      Thread.sleep(1000);
      System.out.println("Page title: " + driver.getTitle());
      driver.close();
   }
}
How to update MongoDB collection using $toLower?

There is a $toLower operator in MongoDB to be used as part of aggregate framework. But, we can also use the for loop to iterate over the specific field and update one by one.
Let us first create a collection with documents
> db.toLowerDemo.insertOne({"StudentId":101,"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b4515e86fd1496b38bf")
}
> db.toLowerDemo.insertOne({"StudentId":102,"StudentName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b4b15e86fd1496b38c0")
}
> db.toLowerDemo.insertOne({"StudentId":103,"StudentName":"CHris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b5115e86fd1496b38c1")
}
> db.toLowerDemo.insertOne({"StudentId":104,"StudentName":"ROBERT"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b5a15e86fd1496b38c2")
}
Following is the query to display all documents from a collection with the help of find() method
> db.toLowerDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9b1b4515e86fd1496b38bf"),
   "StudentId" : 101,
   "StudentName" : "John"
}
{
   "_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"),
   "StudentId" : 102,
   "StudentName" : "Larry"
}
{
   "_id" : ObjectId("5c9b1b5115e86fd1496b38c1"),
   "StudentId" : 103,
   "StudentName" : "CHris"
}
{
   "_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"),
   "StudentId" : 104,
   "StudentName" : "ROBERT"
}
Following is the query to update MongoDB like $toLower
> db.toLowerDemo.find().forEach(
...    function(lower) {
...       lower.StudentName = lower.StudentName.toLowerCase();
...       db.toLowerDemo.save(lower);
...    }
... );
Let us check the document once again from the above collection. Following is the query
> db.toLowerDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9b1b4515e86fd1496b38bf"),
   "StudentId" : 101,
   "StudentName" : "john"
}
{
   "_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"),
   "StudentId" : 102,
   "StudentName" : "larry"
}
{
   "_id" : ObjectId("5c9b1b5115e86fd1496b38c1"),
   "StudentId" : 103,
   "StudentName" : "chris"
}
{
   "_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"),
   "StudentId" : 104,
   "StudentName" : "robert"
}
Unpacking tuple of lists in Python

When it is required to unpack a tuple of list, the 'reduce' method can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A tuple of list contains multiple lists, which are enclosed in '(' and ')'.
The 'reduce' method is used to apply a specific method (that is passed as an argument to it) to all the values in the iterable. This method is present in the 'functools' module.
Below is a demonstration for the same −
Live Demo
from functools import reduce
import operator
def unpack_tuple(my_tup):  
   return (reduce(operator.add, my_tup))

my_tuple = (['h', 'jane'], ['m', 'may'])

print("The tuple of list is")
print(my_tuple)
print("After unpacking, it is")
print(unpack_tuple(my_tuple))
The tuple of list is
(['h', 'jane'], ['m', 'may'])
After unpacking, it is
['h', 'jane', 'm', 'may']
The required packages are imported into the environment.
A function named 'unpack_tuple' is defined that takes a tuple as parameter.
It uses the 'reduce' method, and calls the 'add' method on all elements inside the tuple.
Now, a tuple of list is defined, and is displayed on the console.
This function is called by passing the tuple of list as parameter.
This operation's data is stored in a variable.
This variable is the output that is displayed on the console.
LESS - Escaping

It builds selectors dynamically and uses property or variable value as arbitrary string.
The following example demonstrates the use of escaping in the LESS file −
<html>
   <head>
      <title>Less Escaping</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
   </head>
   
   <body>
      <h1>Example using Escaping</h1>
      <p>LESS enables customizable, manageable and reusable style sheet for web site.</p>
   </body>
</html>
Now create the style.less file.
p {
   color: ~"green";
}
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css

Execute the above command, it will create the style.css file automatically with the following code −
p {
   color: green;
}
Anything written inside ~"some_text" will be displayed as some_text after compiling the LESS code to CSS code.
Let us now perform the following steps to see how the above code works −
Save the above html code in the escaping.html file.
Save the above html code in the escaping.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
BigInteger intValue() Method in Java

04 Dec, 2018
The java.math.BigInteger.intValue() converts this BigInteger to an integer value. If the value returned by this function is too big to fit into integer value, then it will return only the low-order 32 bits. Further there is chance that this conversion can loose information about the overall magnitude of the BigInteger value. This method can also return the result with opposite sign.
Syntax:
public int intValue()
Returns: The method returns an int value which represents integer value for this BigInteger.
Examples:
Input: BigInteger1=32145
Output: 32145
Explanation: BigInteger1.intValue()=32145.

Input: BigInteger1=4326516236135
Output: 1484169063
Explanation: BigInteger1.intValue()=1484169063. This BigInteger is too big for 
intValue so it is returning lower 32 bit.

Example 1:Below programs illustrate intValue() method of BigInteger class
// Java program to demonstrate // intValue() method of BigInteger  import java.math.BigInteger;  public class GFG {      public static void main(String[] args)    {          // Creating 2 BigInteger objects        BigInteger b1, b2;          b1 = new BigInteger("32145");        b2 = new BigInteger("7613721");          // apply intValue() method        int intValueOfb1 = b1.intValue();        int intValueOfb2 = b2.intValue();          // print intValue        System.out.println("intValue of "                           + b1 + " : " + intValueOfb1);        System.out.println("intValue of "                           + b2 + " : " + intValueOfb2);    }}
intValue of 32145 : 32145
intValue of 7613721 : 7613721

Example 2: when return integer is too big for int value.
// Java program to demonstrate // intValue() method of BigInteger  import java.math.BigInteger;  public class GFG {      public static void main(String[] args)    {          // Creating 2 BigInteger objects        BigInteger b1, b2;          b1 = new BigInteger("4326516236135");        b2 = new BigInteger("251362466336");          // apply intValue() method        int intValueOfb1 = b1.intValue();        int intValueOfb2 = b2.intValue();          // print intValue        System.out.println("intValue of "                           + b1 + " : " + intValueOfb1);        System.out.println("intValue of "                           + b2 + " : " + intValueOfb2);    }}
intValue of 4326516236135 : 1484169063
intValue of 251362466336 : -2040604128

Reference:BigInteger intValue() Docs
java-basics
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
HTML | <frame> frameborder Attribute

30 Sep, 2019
The HTML <frame> frameborder attribute is used to specify whether or not a border should be displayed between the frames. For this, we use two values 0 and 1, where 0 defines no border and 1 defines the border.
Syntax
<frame frameborder="1|0"> 
Attribute Values:
0: It has a default value. It sets the border on one state.
1: It sets the border off state.
Example:
<!DOCTYPE html> <html>   <head>     <title>        HTML frame frameborder Attribute    </title> </head>   <frameset cols="30%, 40%, 30%">           <frame name="left" src="https://media.geeksforgeeks.org/wp-content/uploads/20190401113144/gfg_200X2001.png"            frameborder="1" />           <frame name="main" src="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png"             frameborder="1" />           <frame name="bottom" src="https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png"             frameborder="0" />   </frameset>   </html>
Output:
Supported Browsers: The browsers supported by HTML <frame> frameborder attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js socket.send() Method

06 May, 2021
The socket.send() method is  an inbuilt application programming interface of class Socket within dgram module which is used to send the message from one socket to another socket.
Syntax:
socket.send(msg[, offset, length][, port][, address][, callback])
Parameters: This method takes the following parameter:
msg: Message to be sent.
offset: Offset in the buffer where the message starts.
length: Number of bytes in the message.
port: Destination port.
address: Destination host name or IP address.
callback: Called when the message has been sent.
Return Value: This method does not return any value.
Example 1: Filename: index.js
Javascript
// Node.js program to demonstrate the// server.send() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket("udp4");var server = dgram.createSocket("udp4"); // Catching the message eventserver.on("message", function (msg) { // Displaying the client messageprocess.stdout.write("UDP String: " + msg + "\n"); // Exiting processprocess.exit();})   // Binding server with port  .bind(1234, () => {   // Getting the reference of the server  // by using ref() method  const size = server.ref();   // Display the result  console.log(size.eventNames());}); // Client sending message to server// by using send() methodclient.send("Hello", 0, 7, 1234, "localhost");
Output:
[ 'message' ]
UDP String: Hello
Example 2: Filename: index.js
Javascript
// Node.js program to demonstrate the// server.send() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket("udp4");var server = dgram.createSocket("udp4"); // Catching the message eventserver.on("message", function (msg) {   // Displaying the client message  process.stdout.write("UDP String: " + msg + "\n");   // Exiting process  process.exit();}); // Catching the listening eventserver.on('listening', () => {   // Getting address information for the server  const address = server.address();   // Display the result  console.log(`server listening ${address.address}:${address.port}`);});  // Binding server with port address// by using bind() methodserver.bind(1234, () => {   // Getting the reference of server  // by using ref() method  const size = server.ref();   // display the result  console.log(size.eventNames());}); // Client sending message to server// by using send() methodclient.send("Hello", 0, 7, 1234, "localhost", (err) =>{   if(err) throw err;  console.log("message sent");});
Output:
server listening 0.0.0.0:1234
[ 'message', 'listening' ]
message sent
UDP String: Hello
Run the index.js file using the following command:
node index.js
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_send_msg_offset_length_port_address_callback
sweetyty
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Miscellaneous | Question 4

28 Jun, 2021
What is the output of the following program :
print 0.1 + 0.2 == 0.3
(A) True(B) False(C) Machine dependent(D) ErrorAnswer: (B)Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off errors from 0.1 and 0.2 accumulate and hence there is a difference of 5.5511e-17 between (0.1 + 0.2) and 0.3.Quiz of this QuestionPlease comment below if you find anything wrong in the above post
amartyaghoshgfg
Miscellaneous
Python-Miscellaneous
Python-Quizzes
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python-Quizzes | Python List Quiz | Question 4
Python-Quizzes | Python List Quiz | Question 5
Python-Quizzes | Python Dictionary Quiz | Question 25
Output of Python Program - Dictionary (set 25)
Why do people prefer Selenium with Python?
Python-Quizzes | Python Dictionary Quiz | Question 23
Python | Animated Banner showing 'GeeksForGeeks'
Python-Quizzes | Data Type | Question 3
Python | Output Type | Question 4
Python-Quizzes | Python Dictionary Quiz | Question 1