code-rag-bench/online-tutorials huggingface dataset:
What is the difference between the dot (.) operator and -> in C++?

The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as class, struct, or union are considered "of class type". So the following refers to all three of them.
a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class.
a→b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that a points to.
Note that . is not overloadable. → is overloadable operator, so we can define our own function(operator→()) that should be called when this operator is used. so if a is an object of a class that overloads operator→ (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented.
[1] References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the #3 as well. However, I thought this would be more confusing than helpful, since references to pointers (T*&) are rarely ever used.
#include<iostream>
class A {
   public: int b;
   A() { b = 5; }
};

int main() {
   A a = A();
   A* x = &a;
   std::cout << "a.b = " << a.b << "\n";
   std::cout << "x->b = " << x->b << "\n";
   return 0;
}
This will give the output −
5
5
Python | Dividing two lists

11 Feb, 2019
Sometimes we come across the situations in which we require to apply a particular function to each elements of two lists at similar index. Most popular of them are 4 of the elementary mathematics operations. These are quite similar and come up as application for certain utilities. Let’s discuss certain ways in which the division of two lists can be performed.
Method #1 : Using zip() + list comprehensionThe zip operation can be used to link one list with the other and the computation part can be handled by the list comprehension and hence providing a shorthand to this particular problem.
# Python3 code to demonstrate # division of lists# using zip() + list comprehension  # initializing lists test_list1 = [3, 5, 2, 6, 4]test_list2 = [7, 3, 4, 1, 5]  # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # division of lists# using zip() + list comprehensionres = [i / j for i, j in zip(test_list1, test_list2)]  # printing resultprint ("The division list is : " + str(res))
The original list 1 is : [3, 5, 2, 6, 4]
The original list 2 is : [7, 3, 4, 1, 5]
The division list is : [0.42857142857142855, 1.6666666666666667, 0.5, 6.0, 0.8]

 Method #2 : Using map()Using map function is most elegant way in which we can possibly perform the twining of a function with both the lists. Different operations other than division can also be applied over it.
# Python3 code to demonstrate # division of lists# using map()from operator import truediv  # initializing lists test_list1 = [3, 5, 2, 6, 4]test_list2 = [7, 3, 4, 1, 5]  # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # division of lists# using map()res = list(map(truediv, test_list1, test_list2))  # printing resultprint ("The division list is : " + str(res))
The original list 1 is : [3, 5, 2, 6, 4]
The original list 2 is : [7, 3, 4, 1, 5]
The division list is : [0.42857142857142855, 1.6666666666666667, 0.5, 6.0, 0.8]

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python – Assign Alphabet to each element

11 Sep, 2021
Given a list of elements, assign similar alphabet to same element.
Input : test_list = [4, 5, 2, 4, 2, 6] Output : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’, ‘d’] Explanation : Alphabets assigned to elements as occurring.
Input : test_list = [4, 5, 2, 4, 2, 6] Output : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’] Explanation : Alphabets assigned to elements as occurring.  
Method #1 : Using ascii_lowercase() + loop + list comprehension 
In this, we extract all lowercase alphabets using lowercase(), and create dictionary mapping same element to similar character, post that we flatten that to appropriate index using list comprehension.
Python3
# Python3 code to demonstrate working of# Assign Alphabet to each element# Using ascii_lowercase() + loop + list comprehensionimport string # initializing listtest_list = [4, 5, 2, 4, 2, 6, 5, 2, 5] # printing listprint("The original list : " + str(test_list)) temp = {}cntr = 0for ele in test_list:    if ele in temp:        continue         # assigning same Alphabet to same element    temp[ele] = string.ascii_lowercase[cntr]    cntr += 1     # flatteningres = [temp.get(ele) for ele in test_list] # printing resultsprint("The mapped List : " + str(res))
The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']
Method #2 : Using defaultdict() + ascii_lowercase() + iter()
In this we use defaultdict() to assign values to similar elements, ascii_lowercase() is used to get all lowercase all lowercased alphabets.
Python3
# Python3 code to demonstrate working of# Assign Alphabet to each element# Using defaultdict() + ascii_lowercase() + iter()from collections import defaultdictimport string # initializing listtest_list = [4, 5, 2, 4, 2, 6, 5, 2, 5] # printing listprint("The original list : " + str(test_list)) # assigning lowercases as iteratortemp = iter(string.ascii_lowercase) # lambda functions fits to similar elementsres = defaultdict(lambda: next(temp)) # flatten in listres = [res[key] for key in test_list] # printing resultsprint("The mapped List : " + str(list(res)))
The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']
sagartomar9927
akshaysingh98088
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
Python Script to create random jokes using pyjokes

02 Dec, 2020
Python supports creation of random jokes using one of its libraries. Let us explore it a little more, Pyjokes is a python library that is used to create one-line jokes for programmers. Informally, it can also be referred as a fun python library which is pretty simple to use. Let us see how you can actually use it to perform the required task,
You can simply install it using pip with the following command:
pip install pyjokes
Now to use it, we need to import the installed library in our python Script using the following command:
import pyjokes
Before, moving further towards our python script, it is necessary to get familiar with the two functions of Pyjokes library, namely get_joke() and get_jokes(). 
get_joke() 
Syntax:
get_joke(language,category)
As the name suggests, this function is used to actually return a single joke from a certain category and in a particular language, (Categories and languages will be introduced later in this article). 
get_jokes()
Syntax:
get_jokes(language,category)
It is similar to the get_joke() function, the only difference lies in the fact that instead of returning a single joke, it returns a list of random jokes from a certain category and in a particular language.
Language and category are the two parameters of get_joke() and get_jokes() functions. 
Language specifies in which language you want the joke(s) to be displayed. By default, it is set to “en” that returns jokes in English. All other possible values for language parameter are described below:
Similarly, the category parameter specifies the category in which you want joke(s) to be displayed. By default, it is set to “neutral”. All other possible values for the category parameter are described below:
Below are some examples to understand better:
Example 1: Using get_joke() to generate a single joke
Python3
# importing installed libraryimport pyjokes  # using get_joke() to generate a single joke#language is english#category is neutralMy_joke = pyjokes.get_joke(language="en", category="neutral")  print(My_joke)
Output:
Example 2: Using get_jokes() to generate a list of jokes
Python3
import pyjokes  # using get_jokes() to generate a whole list of jokes# language is german# category is twisterlist_of_jokes = pyjokes.get_jokes(language="de", category="twister")  # traversing through the generated list of jokes# Range of i may change, depending on the number of jokes# you want to displayfor i in range(0, 4):    print(list_of_jokes[i], sep='\n')
Output:
python-modules
python-utility
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Looping through buttons in Tkinter

26 Mar, 2021
In this article, let’s see how we can loop through the buttons in Tkinter.
Stepwise implementation:
Step 1: Import the Tkinter package and all of its modules and create a root window (root = Tk()).
Python3
# Import package and it's modulesfrom tkinter import *  # create root windowroot = Tk()  # root window title and dimensionroot.title("GeekForGeeks")  # Set geometry (widthxheight)root.geometry('400x400')  # Execute Tkinterroot.mainloop()
Output
Step 2: Now let’s add a Entry() class and will display the button name as soon as one of the buttons is clicked.
Python3
# Import package and it's modulesfrom tkinter import *  # create root windowroot = Tk()  # root window title and dimensionroot.title("GeekForGeeks")  # Set geometry (widthxheight)root.geometry('400x400')  # Entry Boxtext = Entry(root, width = 30, bg = 'White')text.pack(pady = 10)  # Execute Tkinterroot.mainloop()
Output  
Step 3: Now let’s create an empty dictionary (button_dict) to save all the button objects and a list consisting of names of all the buttons. Now loop over each item of the list to create an button object of it and store it in the dictionary. For the button command, create a function named ‘action’ and for each button call the text_update() function to update the changes in the entry in Entry() object created earlier.
Python3
# Import package and it's modulesfrom tkinter import *    # text_update functiondef text_updation(language):    text.delete(0, END)    text.insert(0, language)  # create root windowroot = Tk()  # root window title and dimensionroot.title("GeekForGeeks")  # Set geometry (widthxheight)root.geometry('400x400')  # Entry Boxtext = Entry(root, width=30, bg='White')text.pack(pady=10)  # create buttonsbutton_dict = {}words = ["Python", "Java", "R", "JavaScript"]for lang in words:        # pass each button's text to a function    def action(x = lang):         return text_updation(x)            # create the buttons     button_dict[lang] = Button(root, text = lang,                               command = action)    button_dict[lang].pack(pady=10)  # Execute Tkinterroot.mainloop()
Output
Picked
Python Tkinter-exercises
Python-tkinter
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
Python OpenCV | cv2.copyMakeBorder() method

08 Aug, 2021
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.copyMakeBorder() method is used to create a border around the image like a photo frame.  
Syntax: cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value)
Parameters: src: It is the source image. top: It is the border width in number of pixels in top direction. bottom: It is the border width in number of pixels in bottom direction. left: It is the border width in number of pixels in left direction. right: It is the border width in number of pixels in right direction. borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc dest: It is the destination imagevalue: It is an optional parameter which depicts color of border if border type is cv2.BORDER_CONSTANT.
Return Value: It returns an image.  
The borderType flags are described below:  
cv2.BORDER_CONSTANT: It adds a constant colored border. The value should be given as a keyword argumentcv2.BORDER_REFLECT: The border will be mirror reflection of the border elements. Suppose, if image contains letters “abcdefg” then output will be “gfedcba|abcdefg|gfedcba“. cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT: It does the same works as cv2.BORDER_REFLECT but with slight change. Suppose, if image contains letters “abcdefgh” then output will be “gfedcb|abcdefgh|gfedcba“. cv2.BORDER_REPLICATE: It replicates the last element. Suppose, if image contains letters “abcdefgh” then output will be “aaaaa|abcdefgh|hhhhh“.  
Image used for all the below examples:  
Example #1:  
Python3
# Python program to explain cv2.copyMakeBorder() method  # importing cv2import cv2  # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'  # Reading an image in default modeimage = cv2.imread(path)  # Window name in which image is displayedwindow_name = 'Image' # Using cv2.copyMakeBorder() methodimage = cv2.copyMakeBorder(image, 10, 10, 10, 10, cv2.BORDER_CONSTANT, None, value = 0) # Displaying the imagecv2.imshow(window_name, image)
Output:  
Example #2:  
Python3
# Python program to explain cv2.copyMakeBorder() method  # importing cv2import cv2  # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'  # Reading an image in default modeimage = cv2.imread(path)  # Window name in which image is displayedwindow_name = 'Image' # Using cv2.copyMakeBorder() methodimage = cv2.copyMakeBorder(image, 100, 100, 50, 50, cv2.BORDER_REFLECT) # Displaying the imagecv2.imshow(window_name, image)
Output:  
 
smyafe7o9x6r1d65ted6ubs9hacynx7ltfue26rl
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
Introduction To PYTHON
Find max or min value in an array of primitives using Java - GeeksforGeeks

04 Nov, 2020
Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using “aslist()“. aslist() type casts a list from the array passed in its argument. This function is defined in “Java.utils.Arrays“. To get the minimum or maximum value from the array we can use the Collections.min() and Collections.max() methods. But as this method requires a list type of data we need to convert the array to list first using above explained “aslist()” function.
Note:  “The array you are are passing to the Arrays.asList() must have a return type of Integer or whatever class you want to use”, since the Collections.sort() accepts ArrayList object as a parameter. 
Note: If you use type int while declaring the array you will end up seeing this error: “no suitable method found for min(List<int[]>)”
Java
// Java code to demonstrate how to// extract minimum and maximum number// in 1 line.import java.util.Arrays;import java.util.Collections; public class MinNMax {    public static void main(String[] args)    {         // Initializing array of integers        Integer[] num = { 2, 4, 7, 5, 9 };         // using Collections.min() to        // find minimum element        // using only 1 line.        int min = Collections.min(Arrays.asList(num));         // using Collections.max()        // to find maximum element        // using only 1 line.        int max = Collections.max(Arrays.asList(num));         // printing minimum and maximum numbers        System.out.println("Minimum number of array is : "                           + min);        System.out.println("Maximum number of array is : "                           + max);    }}
Minimum number of array is : 2
Maximum number of array is : 9

This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Johnpk
mchac7
parascoding
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Access Modifiers in C#

Access Modifiers specifies the scope of variable and functions in C#. The following are the access modifiers used provided by C#:
The public modifier sets no restriction on the access of members.
Access limited to the derived class or class definition.
The Internal access modifier access within the program that has its declaration.
It has both the access specifiers provided by protected and internal access modifiers.
Limited only inside the class in which it is declared. The members specified as private cannot be accessed outside the class.
Let us see an example of protected access modifier, accessing the protected members −
Live Demo
using System;
namespace MySpecifiers {
   class Demo {
      protected string name = "Website";
      protected void Display(string str) {
         Console.WriteLine("Tabs: " + str);
      }
   }

   class Test : Demo {
      static void Main(string[] args) {
         Test t = new Test();
         Console.WriteLine("Details: " + t.name);
         t.Display("Product");
         t.Display("Services");
         t.Display("Tools");
         t.Display("Plugins");
      }
   }
}
Details: Website
Tabs: Product
Tabs: Services
Tabs: Tools
Tabs: Plugins
Show Matplotlib graphs to image as fullscreen

To show matplotlib graphs as full screen, we can use full_screen_toggle() method.
Create a figure or activate an existing figure using figure() method.
Create a figure or activate an existing figure using figure() method.
Plot a line using two lists.
Plot a line using two lists.
Return the figure manager of the current figure.
Return the figure manager of the current figure.
To toggle full screen image, use full_screen_toggle() method.
To toggle full screen image, use full_screen_toggle() method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.figure()
plt.plot([1, 2], [1, 2])
manager = plt.get_current_fig_manager()
manager.full_screen_toggle()
plt.show()
Conversions in LINQ

The operators change the type of input objects and are used in a diverse range of applications.
using System;
using System.Linq;

namespace Operators {
   class Cast {
      static void Main(string[] args) {
      
         Plant[] plants = new Plant[] {new CarnivorousPlant { Name = "Venus Fly Trap", TrapType = "Snap Trap" },
                          new CarnivorousPlant { Name = "Pitcher Plant", TrapType = "Pitfall Trap" },
                          new CarnivorousPlant { Name = "Sundew", TrapType = "Flypaper Trap" },
                          new CarnivorousPlant { Name = "Waterwheel Plant", TrapType = "Snap Trap" }};

         var query = from CarnivorousPlant cPlant in plants
                     where cPlant.TrapType == "Snap Trap"
                     select cPlant;

         foreach (var e in query) {
            Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }

   class Plant {
      public string Name { get; set; }
   }

   class CarnivorousPlant : Plant {
      public string TrapType { get; set; }
   }
}
Module Module1
   Sub Main()

      Dim plants() As Plant = {New CarnivorousPlant With {.Name = "Venus Fly Trap", .TrapType = "Snap Trap"},
                              New CarnivorousPlant With {.Name = "Pitcher Plant", .TrapType = "Pitfall Trap"},
                              New CarnivorousPlant With {.Name = "Sundew", .TrapType = "Flypaper Trap"},
                              New CarnivorousPlant With {.Name = "Waterwheel Plant", .TrapType = "Snap Trap"}}

      Dim list = From cPlant As CarnivorousPlant In plants
                 Where cPlant.TrapType = "Snap Trap"
                 Select cPlant

      For Each e In list
         Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
   End Sub

   Class Plant
      Public Property Name As String
   End Class

   Class CarnivorousPlant
      Inherits Plant
      Public Property TrapType As String
   End Class

End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
Name = Venus Fly Trap, TrapType = Snap Trap
Name = Waterwheel Plant, TrapType = Snap Trap

Press any key to continue.


    23 Lectures 
     1.5 hours 

 Anadi Sharma

    37 Lectures 
     13 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Quick Sort

The quicksort technique is done by separating the list into two parts. Initially, a pivot element is chosen by partitioning algorithm. The left part of the pivot holds the smaller values than the pivot, and right part holds the larger value. After partitioning, each separate lists are partitioned using the same procedure.
Time Complexity: O(n log n) for best case and average case, O(n^2) for the worst case.
Space Complexity: O(log n)
Input:
The unsorted list: 90 45 22 11 22 50
Output:
Array before Sorting: 90 45 22 11 22 50
Array after Sorting: 11 22 22 45 50 90
partition(array, lower, upper)
Output: Pivot in the correct position
Begin
   pivot := array[lower]
   start := lower and end := upper
   while start < end do
      while array[start] <= pivot AND start < end do
         start := start +1
      done

      while array[end] > pivot do
         end := end – 1
      done
      if start < end then
         swap array[start] with array[end]
   done

   array[lower] := array[end]
   array[end] := pivot
   return end
End
quickSort(array, left, right
Input − An array of data, and lower and upper bound of the array
Output − The sorted Array
Begin
   if lower < right then
      q = partition(arraym left, right)
      quickSort(array, left, q-1)
      quickSort(array, q+1, right)
End
#include<iostream>
using namespace std;

void swapping(int &a, int &b) { //swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

int partition(int *array, int lower, int upper) {
   //Hoare partitioning technique to find correct location for pivot
   int pivot, start, end;
   pivot = array[lower];      //first element as pivot
   start = lower; end = upper;

   while(start < end) {
      while(array[start] <= pivot && start<end) {
         start++;      //start pointer moves to right
      }

      while(array[end] > pivot) {
         end--;      //end pointer moves to left
      }

      if(start < end) {
         swap(array[start], array[end]); //swap smaller and bigger element
      }
   }

   array[lower] = array[end];
   array[end] = pivot;
   return end;
}

void quickSort(int *array, int left, int right) {
   int q;

   if(left < right) {
      q = partition(array, left, right);
      quickSort(array, left, q-1);    //sort left sub-array
      quickSort(array, q+1, right);   //sort right sub-array
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   quickSort(arr, 0, n-1); //(n-1) for last index
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 6
Enter elements:
90 45 22 11 22 50
Array before Sorting: 90 45 22 11 22 50
Array after Sorting: 11 22 22 45 50 90
Perl keys Function

This function returns all the keys of the HASH as a list. The keys are returned in random order but, in fact, share the same order as that used by values and each.
Following is the simple syntax for this function −
keys HASH

This function returns number of keys in the hash in scalar context and list of keys in list context.
Following is the example code showing its basic usage −
#!/usr/bin/perl

%hash = ('One' => 1,
         'Two' => 2,
         'Three' => 3,
         'Four' => 4);

@values = values( %hash );
print("Values are  ", join("-", @values), "\n");

@keys = keys( %hash );
print("Keys are ", join("-", @keys), "\n");
When above code is executed, it produces the following result −
Values are  4-3-2-1
Keys are Four-Three-Two-One


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
jQuery Effect - Clip Effect

The Clip effect can be used with show/hide/toggle. This clips the element on or off, vertically or horizontally.
Here is the simple syntax to use this effect −
selector.hide|show|toggle( "clip", {arguments}, speed );

Here is the description of all the arguments −
direction − The direction of the effect. Can be "vertical" or "horizontal". Default is vertical.
direction − The direction of the effect. Can be "vertical" or "horizontal". Default is vertical.
mode − The mode of the effect. Can be "show" or "hide". Default is hide.
mode − The mode of the effect. Can be "show" or "hide". Default is hide.
Following is a simple example a simple showing the usage of this effect −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
   
         $(document).ready(function() {

            $("#hide").click(function(){
               $(".target").hide( "clip", {direction: "horizontal"}, 1000 );
            });

            $("#show").click(function(){
               $(".target").show( "clip", {direction: "vertical"}, 1000 );
            });
				
         });
			
      </script>
		
      <style>
         p {background-color:#bca; width:200px; border:1px solid green;}
      </style>
   </head>
	
   <body>
      <p>Click on any of the buttons</p>
		
      <button id = "hide"> Hide </button>
      <button id = "show"> Show</button> 
		
      <div class = "target">
         <img src = "../images/jquery.jpg" alt = "jQuery" />
      </div>
   </body>
</html>
This will produce following result −
Click on any of the buttons

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
PyTorch - Datasets

In this chapter, we will focus more on torchvision.datasets and its various types. PyTorch includes following dataset loaders −
MNIST
COCO (Captioning and Detection)
Dataset includes majority of two types of functions given below −
Transform − a function that takes in an image and returns a modified version of standard stuff. These can be composed together with transforms.
Transform − a function that takes in an image and returns a modified version of standard stuff. These can be composed together with transforms.
Target_transform − a function that takes the target and transforms it. For example, takes in the caption string and returns a tensor of world indices.
Target_transform − a function that takes the target and transforms it. For example, takes in the caption string and returns a tensor of world indices.
The following is the sample code for MNIST dataset −
dset.MNIST(root, train = TRUE, transform = NONE, 
target_transform = None, download = FALSE)
The parameters are as follows −
root − root directory of the dataset where processed data exist.
root − root directory of the dataset where processed data exist.
train − True = Training set, False = Test set
train − True = Training set, False = Test set
download − True = downloads the dataset from the internet and puts it in the root.
download − True = downloads the dataset from the internet and puts it in the root.
This requires the COCO API to be installed. The following example is used to demonstrate the COCO implementation of dataset using PyTorch −
import torchvision.dataset as dset
import torchvision.transforms as transforms
cap = dset.CocoCaptions(root = ‘ dir where images are’, 
annFile = ’json annotation file’,
transform = transforms.ToTensor())
print(‘Number of samples: ‘, len(cap))
print(target)
The output achieved is as follows −
Number of samples: 82783
Image Size: (3L, 427L, 640L)

 Print
 Add Notes
 Bookmark this page
How to open External Programs using Tkinter?

Sometimes, while creating an application, we need to interact with external programs and applications. In order to interact with the system's applications and programs, we have to use os Module in python.
In this article, we will see how we can interact with external programs and open
files using the OS module in Python.
First, we will define a function that will open the chosen file using the filedialog library in Python. Then, we will print the path and open the file using the os module.
# Import the required Libraries
from tkinter import *
from tkinter import filedialog
import os

#Create an instance of tkinter frame
win= Tk()

#Set the geometry for the window or frame
win.geometry("600x400")

#Define a function to open the application

def app():
   file= filedialog.askopenfilename()
   text.config(text= file)
   #Open the program
   os.system('"%s"' %file)

#Create a button
Button(win, text='Click to Open a Program',font=('Poppins bold', 10),
command=app).pack(pady=20)

#Create a Label after button event
text= Label(win, text= "", font= ('Poppins bold', 10))
text.pack(pady=20)

#Keep running the window or frame
win.mainloop()
Running the above code will produce the following window as the output −
Now, click the button and it will open the “My Documents” folder from where you
can open a program.
Bootstrap Glyphicons

Bootstrap provides 260 glyphicons from the Glyphicons
Halflings set.
Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc.
Here are some examples of glyphicons:
Envelope glyphicon: 
Print glyphicon: 
Search glyphicon: 
Download glyphicon: 
A glyphicon is inserted with the following syntax:
The name part in the syntax above must be replaced with the proper name of the glyphicon.
The following example shows different ways to use glyphicons:
Use a Glyphicon class value to make the span display as a "search" icon.
<span class=""></span>

Start the Exercise
For a complete reference of all glyphicons, go to our complete
Bootstrap Glyphicon Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Abstract vs Sealed Classes vs Class Members in C#

The abstract class includes abstract and non-abstract methods. You cannot instantiate an abstract class.
The sealed class prevents inheritance and you cannot use it as a base class.
To declare an abstract class, you need to place the keyword abstract before the class definition. An example of class members in an abstract class can be the following that defines an abstract method −
public abstract class Vehicle {
   public abstract void display();
}
The abstract method definition is followed by a semi-colon since it has no implementation.
To declare a sealed class, you need to place the keyword sealed before the class definition. The sealed class prevents inheritance and you cannot use it as a base class.
public sealed class Test {
   // Class members comes here
}
Set a MySQL field with the current date (UNIX_TIMESTAMP(now))

For this, use unix_timestamp(). Let us first create a table −
mysql> create table DemoTable1894
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   DueTime int
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1894 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1894 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1894 values();
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1894;
This will produce the following output −
+----+---------+
| Id | DueTime |
+----+---------+
|  1 |    NULL |
|  2 |    NULL |
|  3 |    NULL |
+----+---------+
3 rows in set (0.00 sec)
Here is the query to set a field with UNIX Timestamp −
mysql> update DemoTable1894 set DueTime=unix_timestamp(now());
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1894;
This will produce the following output −
+----+------------+
| Id | DueTime    |
+----+------------+
|  1 | 1576042722 |
|  2 | 1576042722 |
|  3 | 1576042722 |
+----+------------+
3 rows in set (0.00 sec)
Check if a line touches or intersects a circle in C++

Suppose we have a circle and another straight line. Our task is to find if the line touches the circle or intersects it, otherwise, it passes through outside. So there are three different cases like below −
Here we will solve it by following steps. These are like below −
Find perpendicular P between the center and given a line
Compare P with radius r −if P > r, then outsideif P = r, then touchesotherwise inside
if P > r, then outside
if P = r, then touches
otherwise inside
To get the perpendicular distance, we have to use this formula (a center point is (h, k))
ah+bk+ca2+b2
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
void isTouchOrIntersect(int a, int b, int c, int h, int k, int radius) {
   int dist = (abs(a * h + b * k + c)) / sqrt(a * a + b * b);
   if (radius == dist)
      cout << "Touching the circle" << endl;
   else if (radius > dist)
      cout << "Intersecting the circle" << endl;
   else
      cout << "Outside the circle" << endl;
}
int main() {
   int radius = 5;
   int h = 0, k = 0;
   int a = 3, b = 4, c = 25;
   isTouchOrIntersect(a, b, c, h, k, radius);
}
Touching the circle
Program to count number of elements are placed at correct position in Python

Suppose we have a list of numbers called nums, we have to find the number of elements that are present in the correct indices, when the list was to be sorted.
So, if the input is like [2, 8, 4, 5, 11], then the output will be 2, as the elements 2 and 11 are in their correct positions. The sorted sequence will be [2, 4, 5, 8, 11]
To solve this, we will follow these steps −
s := sort the list nums
count := 0
for i in range 0 to size of nums, doif s[i] is same as nums[i], thencount := count + 1
if s[i] is same as nums[i], thencount := count + 1
count := count + 1
return count
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      s = sorted(nums)
      count = 0
      for i in range(len(nums)):
         if s[i] == nums[i]:
            count += 1
      return count
ob = Solution()
print(ob.solve([2, 8, 4, 5, 11]))
[2, 8, 4, 5, 11]
2
ExpressJS - Sessions

HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID.
We will need the Express-session, so install it using the following code.
npm install --save express-session

We will put the session and cookie-parser middleware in place. In this example, we will  use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object.
Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted). We can add more properties to the session object. In the following example, we will create a view counter for a client.
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

app.use(cookieParser());
app.use(session({secret: "Shh, its a secret!"}));

app.get('/', function(req, res){
   if(req.session.page_views){
      req.session.page_views++;
      res.send("You visited this page " + req.session.page_views + " times");
   } else {
      req.session.page_views = 1;
      res.send("Welcome to this page for the first time!");
   }
});
app.listen(3000);
What the above code does is, when a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cookie is checked and the page_view session variable is updated accordingly.
Now if you run the app and go to localhost:3000, the following output will be displayed.
If you revisit the page, the page counter will increase. The page in the following screenshot was refreshed 42 times.

    16 Lectures 
     1 hours 

 Anadi Sharma
 Print
 Add Notes
 Bookmark this page
PHP | pi( ) Function - GeeksforGeeks

08 Mar, 2018
While solving mathematical problems we often come across questions which requires the value of π. Manually inserting the value of PI (π) can be time-consuming and erroneous. It is also not considered as a good programming practice. To solve this issue a built-in function of PHP pi() comes to aid.
The pi() function in PHP is used to return the value of π . Also, M_PI is a named constant PHP which gives identical value to that of returned by pi() function. It is slightly faster than the pi() function.
Some other predefined named constants related to π are :
M_PI_2 : It describes π/2. Its value is 1.570796.
M_PI_4 : It describes π/4. Its value is 0.785398.
M_1_PI : It describes 1/π. Its value is 0.318309.
M_PI : It describes π. Its value is 3.141592.
M_2_PI : It describes 2/π. Its value is 0.636619.
M_SQRTPI : It describes sqrt(π). Its value is 1.772453.
M_2_SQRTPI : It describes 2/sqrt(π). Its value is 1.128379.
Syntax:
float pi()
Parameters: This function does not accept any parameter.
Return Value: It returns a floating point value which is an approximate value of PI.
Examples:
Input : echo(pi())
Output : 3.1415926535898

Input : echo M_PI
Output : 3.1415926535898

Below programs illustrate the pi() function in PHP:
When pi() function is used:<?php  echo(pi());  ?>Output:3.1415926535898When M_PI is used for finding the value of PI:<?php  echo M_PI;  ?>Output:3.1415926535898
When pi() function is used:<?php  echo(pi());  ?>Output:3.1415926535898
<?php  echo(pi());  ?>
Output:
3.1415926535898
When M_PI is used for finding the value of PI:<?php  echo M_PI;  ?>Output:3.1415926535898
<?php  echo M_PI;  ?>
Output:
3.1415926535898
Important Points To Note:
The pi() function can be used to return the value of π.
M_PI is a named constant which is slightly faster than the pi() function.
pi() function returns the value of pi as float.
Reference:http://php.net/manual/en/function.pi.php
PHP-function
PHP-math
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
HTML DOM Input Number type Property

The HTML DOM Input number type property is associated with the input element having its type=”number”. It will always return number for the input number element.
Following is the syntax for number type property −
numberObject.type
Let us look at an example for the HTML DOM Input Number type property −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Input Number type property</h1>
PHONE NO: <input type="number" id="NUMBER1">
<p>Get the above element type by clicking the below button</p>
<button onclick="getType()">Get Type</button>
<p id="Sample"></p>
<script>
   function getType() {
      var t = document.getElementById("NUMBER1").type;
      document.getElementById("Sample").innerHTML = "The type for the input field is : "+t;
   }
</script>
</body>
</html>
This will produce the following output −
On clicking the “Get Type” button −
In the above example −
We have created an input field with type number and its id set to “NUMBER1”.
PHONE NO: <input type="number" id="NUMBER1">
We have then created the “Get Type” button that will execute the getType() method when clicked by the user −
<button onclick="getType()">Get Type</button>
The getType() method gets the input element using the getElementById() method and assigns its type attribute value to variable t. This variable is then displayed in the paragraph with id “Sample” using its innerHTML property −
function getType() {
   var t = document.getElementById("NUMBER1").type;
   document.getElementById("Sample").innerHTML = "The type for the input field is : "+t;
}
HTML - <script> Tag

The HTML <script> tag is used for declaring a script (such as JavaScript) within your HTML document.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML script Tag</title>
   </head>

   <body>
      <script type = "text/JavaScript">
         document.write("You're visiting tutorialspoint!")
      </script>
   </body>
	
</html>
This will produce the following result −
For more detail on <script> tag please check HTML Scripts chapter.
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <script> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
PHP | popen( ) Function

04 Jun, 2018
The popen() function used to open a pipe to the program specified by the user using the command parameter. It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature i.e it can be only used for reading or writing. The popen() pointer can be used with fgets(), fgetss(), and fwrite(). The file pointer initiated by the popen() function must be closed with pclose().The command and the mode are sent as parameters to the popen() function and it returns a unidirectional file pointer on success or FALSE on failure.
Syntax:
popen(command, mode)
Parameters Used:The popen() function in PHP accepts two parameters.
command : It is a mandatory parameter which specifies the command to be executed.mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w).
command : It is a mandatory parameter which specifies the command to be executed.
mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w).
Return Value:It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature.
Errors And Exceptions:
The file pointer initiated by the popen() function must be closed with pclose().If the command to be executed could not be found, then the popen() function returns a valid resource.
The file pointer initiated by the popen() function must be closed with pclose().
If the command to be executed could not be found, then the popen() function returns a valid resource.
Examples:
Input : $my_file= popen("/bin/ls", "r");
Output : 1

Input : $my_file= popen('/executable/gfg.exe', 'r');
        echo "'my_file'; " . get_class($my_handle) . "\n";
        $file_read = fread($my_file, 4192);
        echo $file_read;
        pclose($my_file);
Output : 1

Below programs illustrate the popen() function.
Program 1
<?php  // opening a pipe $my_file= popen("/bin/ls", "r");?>
Output:
1
Program 2
<?php // opening a pipe$my_file= popen('/executable/gfg.exe', 'r');  // returning name of class of an object using get_class()  echo "'$my_file'; " . get_class($my_file) . "\n";  // reading file using fread()$filereader = fread($my_file, 4192);   echo $filereader;  // closing the pipepclose($my_file);?>
Output:
1
Related Article: PHP | pclose( ) Function
Reference:http://php.net/manual/en/function.popen.php
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.