code-rag-bench/online-tutorials huggingface dataset:
Introduction to Express - GeeksforGeeks

28 Mar, 2019
Prerequisite – Node.js
Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features.It makes it easier to organize your application’s functionality with middle ware and routing; it adds helpful utilities to Node.js’s HTTP objects;it facilitates the rendering of dynamic HTTP objects.
Express is a part of MEAN stack, a full stack JavaScript solution used in building fast, robust, and maintainable production web applications.
MongoDB(Database)
ExpressJS(Web Framework)
AngularJS(Front-end Framework)
NodeJS(Application Server)
Assuming that you have installed node.js on your system, the following steps should be followed to install express on your Windows:
STEP-1: Creating a directory for our project and make that our working directory.
$ mkdir gfg
$ cd gfg 

STEP-2: Using npm init command to create a package.json file for our project.
$ npm init

This command describes all the dependencies of our project. The file will be updated when adding further dependencies during the development process, for example when you set up your build system.
Keep pressing enter and enter “yes/no” accordingly at the terminus line.STEP-3: Installing Express
Now in your gfg(name of your folder) folder type the following command line:
$ npm install express --save

NOTE- Here “WARN” indicates the fields that must be entered in STEP-2.
STEP-4: Verify that Express.js was installed on your Windows:
To check that express.js was installed on your system or not, you can run the following command line on cmd:
C:\Users\Admin\gfg\node_modules>npm --version express

The version of express.js will be displayed on successful installation.
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
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?
Bootstrap 4 .rounded-circle class

To create a rounded circle with Bootstrap, use the rounded-circle class.
Add the rounded-circle class in the <div>
<div class="test rounded-circle">
</div>
Above, we also have a test class, which is a CSS class to style the circle −
.test {
  width: 270px;
  height: 320px;
  background-color: yellow;
}
You can try to run the following code to implement the rounded-circle class in Bootstrap 4 −
Live Demo
<!DOCTYPE html>
<html>
  <head>
   <title>Bootstrap Example</title>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/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.0/js/bootstrap.min.js"></script>
   <style>
    .test {
      width: 350px;
      height: 320px;
      background-color: yellow;
    }
   </style>
  </head>
<body>
  <div class="container">
    <h2>Circle</h2>
    <p>We have a circle below:</p>
    <div class="test rounded-circle"></div>
  </div>
</body>
</html>
Draw a triangle with centroid using OpenCV - GeeksforGeeks

18 Dec, 2018
Prerequisite: Geometric shapes using OpenCV
Given three vertices of a triangle, write a Python program to find the centroid of the triangle and then draw the triangle with its centroid on a black window using OpenCV.
Examples:
Input: (100, 200) (50, 50) (300, 100)
Output: (150, 116)

Libraries Needed:
OpenCV
Numpy

Approach:Create a black window with three color channels with resolution 400 x 300. Draw three lines which are passing through the given points using the inbuilt line function of the OpenCV. It will create a triangle on the black window. Find the centroid of the triangle using the following simple formula.
    
Draw this centroid on the black window using circle function of OpenCV with zero thickness.
Below is the implementation of the above approach:
# Python3 code to draw a triangle and find centroid  # importing librariesimport numpy as npimport cv2  # Width and height of the black window width = 400height = 300  # Create a black window of 400 x 300img = np.zeros((height, width, 3), np.uint8)  # Three vertices(tuples) of the triangle p1 = (100, 200)p2 = (50, 50)p3 = (300, 100)  # Drawing the triangle with the help of lines#  on the black window With given points # cv2.line is the inbuilt function in opencv librarycv2.line(img, p1, p2, (255, 0, 0), 3)cv2.line(img, p2, p3, (255, 0, 0), 3)cv2.line(img, p1, p3, (255, 0, 0), 3)  # finding centroid using the following formula# (X, Y) = (x1 + x2 + x3//3, y1 + y2 + y3//3) centroid = ((p1[0]+p2[0]+p3[0])//3, (p1[1]+p2[1]+p3[1])//3)  # Drawing the centroid on the window  cv2.circle(img, centroid, 4, (0, 255, 0))  # image is the title of the windowcv2.imshow("image", img)cv2.waitKey(0)
Output:
(150, 116)

OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
How to multiply large numbers using Python?

You can multiply large numbers in python directly without worrying about speed. Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.
As long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.
For example,
a = 15421681351
b = 6184685413848
print(a * b)
This will give the output −
95378247708541418748648
Python | pandas.date_range() method

17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
pandas.date_range() is one of the general functions in Pandas which is used to return a fixed frequency DatetimeIndex.
Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs)
Parameters:start : Left bound for generating dates.end : Right bound for generating dates.periods : Number of periods to generate.freq : Frequency strings can have multiples, e.g. ‘5H’. See here for a list of frequency aliases.tz : Time zone name for returning localized DatetimeIndex. By default, the resulting DatetimeIndex is timezone-naive.normalize : Normalize start/end dates to midnight before generating date range.name : Name of the resulting DatetimeIndex.closed : Make the interval closed with respect to the given frequency to the ‘left’, ‘right’, or both sides (None, the default).
Returns: DatetimeIndex
Code #1:
# importing pandas as pdimport pandas as pd  per1 = pd.date_range(start ='1-1-2018',          end ='1-05-2018', freq ='5H')  for val in per1:    print(val)
Output:
 
Code #2:
# importing pandas as pdimport pandas as pd  dRan1 = pd.date_range(start ='1-1-2018',           end ='8-01-2018', freq ='M')  dRan2 = pd.date_range(start ='1-1-2018',          end ='11-01-2018', freq ='3M')  print(dRan1, '\n\n', dRan2)
Output:
 Code #3:
# importing pandas as pdimport pandas as pd  # Specify start and periods, the number of periods (days).dRan1 = pd.date_range(start ='1-1-2018', periods = 13)  # Specify end and periods, the number of periods (days).dRan2 = pd.date_range(end ='1-1-2018', periods = 13)  # Specify start, end, and periods; the frequency # is generated automatically (linearly spaced).dRan3 = pd.date_range(start ='01-03-2017',             end ='1-1-2018', periods = 13)  print(dRan1, "\n\n", dRan2, '\n\n', dRan3)
Output:
 
Code #4:
# importing pandas as pdimport pandas as pd  # Specify start and periods, the number of periods (days).dRan1 = pd.date_range(start ='1-1-2018',        periods = 13, tz ='Asia / Tokyo')  dRan1
Output:
Python pandas-general-functions
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Types of VPN Tunneling

27 Jun, 2022
Tunneling is the technique of putting an integrated data packet into another packet (which contains routing information) and sending it over the internet. The packets travel through a path which is known as tunnel. To secure a tunneled transmission against interception, all traffic over a VPN is encrypted for safety. Virtual Private Network (VPN) supports 2 types of tunneling which are as follows:
1. Voluntary tunelling
2. Compulsory tunelling
Both types of tunneling are typically used. These are explained as following below: 
1. Voluntary Tunneling: VPN client in the voluntary tunneling handles all the connection setup. For the setup of connection through tunnel both the tunnel client and the tunnel server have to accept the same tunneling protocol. In voluntary tunneling, client-first form a connection to the ISP or carrier network provider. Then the tunnel on a VPN server builds by the VPN client application using this live connection. Two step procedure is required to set up the VPN connection in voluntary tunneling. 
2. Compulsory Tunneling: The carrier network provider in the voluntary tunneling handles all the connection setup required for VPN. It is a one step process as compared to the two step in voluntary tunneling. In compulsory tunneling, the client first establish a normal connection to the carrier then the carrier works as an intermediary to make a connection between a VPN server and that client. Compulsory tunneling provides complete management control of the tunnels to the ISP and hides the details of the connectivity of VPN server from the clients. 
Broker devices are used in compulsory tunneling for the verification of clients. The logic build in the broker device are used to associates the client with the different VPN servers. This network device is also called as the following:
VPN Front End Processor (FEP)
Network Access Server (NAS)
Point of Presence Server (POS)
sahithya3chow
Information-Security
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
TCP Server-Client implementation in C
Socket Programming in Python
Differences between IPv4 and IPv6
Wireless Application Protocol
GSM in Wireless Communication
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
TCP 3-Way Handshake Process
Numbers - GeeksforGeeks

28 Jun, 2021
TYPES OF NUMBERS
Integers : All numbers whose fractional part is 0 (zero) like -3, -2, 1, 0, 10, 100 are integers.
Natural Numbers : Counting numbers like 1, 2, 3, 4, 5, 6 ... Basically, all integers greater than 0 are natural numbers ... More on Numbers
3, 9, 27, 81..............531441 form a G.P. 
with a = 3 and r = 9/3 = 3
Let the number of terms be n
Then 3 x 3n-1 = 531441
∴ 3n = 312
∴ n = 12
If the average of four consecutive odd numbers is 16, find the smallest of these numbers?
5
7
8
11
Let the numbers be x, x+2, x+4 and x+6
Then (x + x + 2 + x + 4 + x + 6)/4  = 16
∴ 4x + 16 = 48
∴ x = 8
The difference between a two-digit number and the number obtained by interchanging the positions of its digits is 36. What is the difference between the two digits of that number?
4
5
6
None of these
Let the ten’s digit be x and unit’s digit be y
Then (10x + y) – (10y + x) = 45
         9(x – y) = 36
           x – y = 4
Given:
ab = 12 ................(i) and,
(10a + b) - (10b + a) = 9
10a + b - 10b - a = 9
9a - 9b = 9
9(a-b) = 9
(a-b) = 1 .................(ii)
Let the number be x.
Then x + 16 = 80 * (1/x)
x2 + 16x – 80 = 0
x2 + 20x – 4x – 80 =0
(x + 20) (x -4)
Therefore x = 4
Let the no. be x and (x +2).
Then (x + 2)2 – x2 = 56
4x + 4 = 56
x + 1 = 14
x = 13
Sum of numbers = x + (x +2) = 28
Let the numbers be x and y.
Then xy = 108 and x2 + y2 = 225
(x –y)2 = x2 + y2 – 2xy
(x –y)2 = 225 – 216
(x –y)2 = 9
Therefore (x –y) = 3
 11'th result = sum of 21 results – sum of 20 results
             = 21 x 20 – (24 x 10 + 14 x 10)
             = 420 – (240 + 140)
             = 420- 380 = 40
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
map key_comp() in C++ STL

24 Oct, 2018
The std::map::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container.By default, this is a less object, which returns the same as operator ‘<'.It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise.Two keys are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
Syntax:
key_compare map_name.key_comp();
Parameters: This function does not accept any parameter.
Return value: The function returns a copy of the comparison object used by the container.
Below examples illustrate map::key_comp() method:
Program 1:
// C++ program to illustrate the// map::key_comp() function  #include <bits/stdc++.h>using namespace std;  int main(){      // Creating a map named m;    map<char, int> m;      map<char, int>::key_compare        comp        = m.key_comp();      // Inserting elements into map    m['a'] = 10;    m['b'] = 20;    m['c'] = 30;    m['d'] = 40;      cout << "Map has the elements\n";      // Store key value of last element    char l = m.rbegin()->first;      // initializing the iterator    map<char, int>::iterator it = m.begin();      // printing elements of all map    do {          cout << it->first             << " => "             << it->second             << '\n';    } while (comp((*it++).first, l));      return 0;}
Map has the elements
a => 10
b => 20
c => 30
d => 40

Program 2:
// C++ program to illustrate the// map::key_comp() function  #include <bits/stdc++.h>using namespace std;  int main(){      // Creating a map named m;    map<char, int> m;      map<char, int>::key_compare        comp        = m.key_comp();      // Inserting elements into map    m['a'] = 1;    m['b'] = 2;    m['c'] = 3;    m['d'] = 4;      cout << "Map has the elements\n";      // Store key value of last element    char l = m.rbegin()->first;      // initializing the iterator    map<char, int>::iterator it = m.begin();      // printing elements of all map    do {          cout << it->first             << " => "             << it->second             << '\n';    } while (comp((*it++).first, l));      return 0;}
Map has the elements
a => 1
b => 2
c => 3
d => 4

CPP-Functions
cpp-map
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Draw a Tic Tac Toe Board using Python-Turtle - GeeksforGeeks

16 Oct, 2020
The Task Here is to Make a Tic Tac Toe board layout using Turtle Graphics in Python. For that lets first know what is Turtle Graphics.
In computer graphics, turtle graphics are vector graphics using a relative cursor upon a Cartesian plane. Turtle is drawing board like feature which let us to command a turtle and draw using it.
Features of turtle graphics:
backward(length): moves the pen in the backward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
import the turtle modules.
import turtle


Get a screen to draw on.
ws = turtle.Screen()


The screen will look like this.
Screen
Define an instance for turtle.
Here, i had manually set the speed of the turtle to 2.
For a drawing a Tic Tac Toe board first we have to make an outer Square.
Then we will Make inner lines of the square which will ultimately make up the board.
For inner lines i had used penup(),goto() and pendown() method to take the pen up and then take it down at certain coordinates.
The inner lines will make up the Tic Tac Toe board perfectly. 
Below is the implementation of the above approach:
Python3
import turtle  # getting a Screen to work onws=turtle.Screen() # Defining Turtle instancet=turtle.Turtle() # setting up turtle color to greent.color("Green") # Setting Up width to 2t.width("2") # Setting up speed to 2t.speed(2) # Loop for making outside square of# length 300for i in range(4):    t.forward(300)    t.left(90)  # code for inner lines of the squaret.penup()t.goto(0,100)t.pendown() t.forward(300) t.penup()t.goto(0,200)t.pendown() t.forward(300) t.penup()t.goto(100,0)t.pendown() t.left(90)t.forward(300) t.penup()t.goto(200,0)t.pendown()  t.forward(300)
 
 
Output:
 
Turtle making Tic Tac Toe Board
 
anshitaagarwal
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
isupper(), islower(), lower(), upper() in Python and their applications
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Graph Plotting in Python | Set 1
How to find all checkbox inputs using jQuery ? - GeeksforGeeks

13 Jan, 2022
The task is to find all the checkbox input using jQuery. Checkboxes are the square boxes that are ticked when activated, and it is used to select one or more number of choices.
Method and Selectors used:
:checkbox: This selector is used to select the input element with type = checkbox.
 .wrap(): This method is used to specify the HTML element around each selected element.
Approach:
Create the HTML page with the input type checkbox.
Using the checkbox selector you can select all the input with the type checkbox.
With the help of the .wrap() method, you can style those selected items.
Example:
HTML
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script>    <style>      body {        text-align: center;        font-size: 30px;      }      button {        background-color: #4caf50; /* Green */        border: none;        color: white;        padding: 15px 32px;        text-align: center;        text-decoration: none;        display: inline-block;        font-size: 16px;      }    </style>     <script>      $(document).ready(function () {        $(":checkbox").wrap("<span style='border-style:dotted'>");      });    </script>  </head>  <body>    <h2 style="color: green">GeeksforGeeks</h2>     <form action="">      First Name: <input type="text" name="user" />      <br />      <br />I like chocolates      <input type="checkbox" name="chocolate"             value="chocolate" /><br />      I like fruits:      <input type="checkbox"             name="fruits" value="fruits" />      <br />      I like blue color:      <input type="checkbox"             name="color" value="color" />      <br />      <button>Submit</button>    </form>  </body></html>
Output:
checkbox
adnanirshad158
jQuery-HTML/CSS
jQuery-Selectors
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
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?
How to count text lines inside of DOM element ? - GeeksforGeeks

12 Jun, 2020
To count number of text lines inside DOM element, we will use the following approach.
Obtain the total height of content inside the DOM element.Obtain the height of one line.By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.
Obtain the total height of content inside the DOM element.
Obtain the height of one line.
By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.
Example:
html
<!DOCTYPE html><html>  <head>    <title>Count lines </title></head>  <body>    <h1 style="color: green;">        GeeksForGeeks    </h1>      <div id="content" style="width: 100%;                 line-height: 20px">        hello how are you?<br>        hello how are you?<br>        hello how are you? <br>        hello how are you?<br>    </div>      <button onclick="countLines()">        Count lines    </button>      <script>          // Function to count total        // number of lines        function countLines() {              // Get element with 'content' as id                                        var el =                 document.getElementById('content');              // Get total height of the content                var divHeight = el.offsetHeight              // object.style.lineHeight, returns             // the lineHeight property            // height of one line             var lineHeight =                 parseInt(el.style.lineHeight);              var lines = divHeight / lineHeight;            alert("Lines: " + lines);        }    </script></body>  </html>
Before Clicking on the button: 
After Clicking on the button: 
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to position a div at the bottom of its container using CSS?
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
Operating Systems | Set 1 - GeeksforGeeks

27 Nov, 2019
Following questions have been asked in GATE CS exam.
1. Which of the following is NOT a valid deadlock prevention scheme? (GATE CS 2000)(a) Release all resources before requesting a new resource(b) Number the resources uniquely and never request a lower numbered resource than the last one requested.(c) Never request a resource after releasing any resource(d) Request and all required resources be allocated before execution.
Answer: (c)References:http://www.cs.jhu.edu/~yairamir/cs418/os4/sld013.htmhttp://en.wikipedia.org/wiki/Deadlock
2. Let m[0]...m[4] be mutexes (binary semaphores) and P[0] .... P[4] be processes.Suppose each process P[i] executes the following:
  wait (m[i]); wait(m[(i+1) mode 4]);

  ------

  release (m[i]); release (m[(i+1)mod 4]);

This could cause (GATE CS 2000)(a) Thrashing(b) Deadlock(c) Starvation, but not deadlock(d) None of the above
Answer: (b)Explanation:You can easily see a deadlock in a situation where..P[0] has acquired m[0] and waiting for m[1]P[1] has acquired m[1] and waiting for m[2]P[2] has acquired m[2] and waiting for m[3]P[3] has acquired m[3] and waiting for m[0]
3. A graphics card has on board memory of 1 MB. Which of the following modes can thecard not support? (GATE CS 2000)(a) 1600 x 400 resolution with 256 colours on a 17 inch monitor(b) 1600 x 400 resolution with 16 million colours on a 14 inch monitor(c) 800 x 400 resolution with 16 million colours on a 17 inch monitor(d) 800 x 800 resolution with 256 colours on a 14 inch monitorAnswer: (b)Explanation:Monitor size doesn’t matter here. So, we can easily deduce that answer should be (b) as this has the highest memory requirements. Let us verify it.Number of bits required to store a 16M colors pixel = ceil(log2(16*1000000)) = 24Number of bytes required for 1600 x 400 resolution with 16M colors = (1600 * 400 * 24)/8 which is 192000000 (greater than 1MB).
4 Consider a virtual memory system with FIFO page replacement policy. For an arbitrary page access pattern, increasing the number of page frames in main memory will (GATE CS 2001)a) Always decrease the number of page faultsb) Always increase the number of page faultsc) Some times increase the number of page faultsd) Never affect the number of page faults
Answer: (c)Explanation:Incrementing the number of page frames doesn’t always decrease the page faults (Belady’s Anomaly). For details see http://en.wikipedia.org/wiki/Belady%27s_anomaly
5. Which of the following requires a device driver? (GATE CS 2001)a) Registerb) Cachec) Main memoryd) Disk
Answer: (d)
ShaliniSingh13
GATE CS
MCQ
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Normal Forms in DBMS
Differences between TCP and UDP
Data Structures and Algorithms | Set 25
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 1
Computer Networks | Set 2
Database Management Systems | Set 1
array get() function in C++ STL - GeeksforGeeks

29 Aug, 2018
The array::get() is a built-in function in C++ STL which returns a reference to the i-th element of the array container.
Syntax:
get(array_name)
Parameters: The function accepts two mandatory parameters which are described below.
i – position of an element in the array, with 0 as the position of the first element.
arr_name – an array container.
Return Value: The function returns a reference to the element at the specified position in the array
Time complexity: O(1)
Below programs illustrate the above function:
Program 1:
// CPP program to demonstrate the// array::get() function#include <bits/stdc++.h>using namespace std;int main(){    // array initialisation    array<int, 3> arr = { 10, 20, 30 };      // function call    cout << "arr[0] = " << get<0>(arr) << "\n";    cout << "arr[1] = " << get<1>(arr) << "\n";    cout << "arr[2] = " << get<2>(arr) << "\n";      return 0;}
arr[0] = 10
arr[1] = 20
arr[2] = 30

Program 2:
// CPP program to demonstrate the// array::get() function#include <bits/stdc++.h>using namespace std;int main(){    // array initialisation    array<char, 3> arr = { 'a', 'b', 'c' };      // function call    cout << "arr[0] = " << get<0>(arr) << "\n";    cout << "arr[1] = " << get<1>(arr) << "\n";    cout << "arr[2] = " << get<2>(arr) << "\n";      return 0;}
arr[0] = a
arr[1] = b
arr[2] = c

cpp-array
CPP-Functions
STL
C++
Misc
Misc
Misc
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Tryit Editor v3.7

Tryit: smiley face
C Program for Recursive Insertion Sort

Insertion sort is a sorting algorithm which is an in-place comparison-based algorithm.
The algorithm works by place element in their position in the sorted sub-array i.e. the sub-array preceding the element which is a sorted sub-array.
Step1 − loop from 1 to n-1 and do −
Step2.1 − select element at position i, array[i].
Step2.2 − insert the element in its position in the sorted sub-array array[0] to arr[i].
Let’s take an example to understand the algorithm
Array = [34, 7, 12, 90, 51]
For i = 1, arr[1] = 7, placing in its positon in subarray arr[0] - arr[1].
[7, 34, 12, 90, 51]
For i = 2, arr[2] = 12, placing in its positon in subarray arr[0] - arr[2].
[7, 12, 34, 90, 51]
For i = 3, arr[3] = 90, placing in its positon in subarray arr[0] - arr[3].
[7, 12, 34, 90, 51]
For i = 4, arr[4] = 51, placing in its positon in subarray arr[0] - arr[4].
[7, 12, 34, 54, 90]
Here, we will see how recursive insertion sort works. It works on a reverse basis i.e. we will recursively call the recursiveInsertionSort() function for sorting n-1 element array as compared to the current iteration. And then in this sorted array which will be returned by the function, we will insert the nth element at its position as in the sorted array.
Program for recursive insertion sort −
 Live Demo
#include <stdio.h>
void recursiveInsertionSort(int arr[], int n){
   if (n <= 1)
      return;
   recursiveInsertionSort( arr, n-1 );
   int nth = arr[n-1];
   int j = n-2;
   while (j >= 0 && arr[j] > nth){
      arr[j+1] = arr[j];
      j--;
   }
   arr[j+1] = nth;
}
int main(){
   int array[] = {34, 7, 12, 90, 51};
   int n = sizeof(array)/sizeof(array[0]);
   printf("Unsorted Array:\t");
      for (int i=0; i < n; i++)
   printf("%d ",array[i]);
      recursiveInsertionSort(array, n);
   printf("\nSorted Array:\t");
   for (int i=0; i < n; i++)
      printf("%d ",array[i]);
   return 0;
}
Unsorted Array: 34 7 12 90 51
Sorted Array: 7 12 34 51 90
How to add a method to struct type in Golang? - GeeksforGeeks

22 Jun, 2020
Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type.
A normal function returning an integer and taking no parameter would look like.
func function_name() int {
    //code
}

Associating the above-mentioned function with the type type_name() would look like.
type type_name struct { }
func (m type_name) function_name() int {
    //code
}

In the below code, an Area() function is added to a struct Rect. Here, Area() is working explicitly with Rect type with func (re Rect) Area() int
Example:
package main  import "fmt"  // taking a structtype Rect struct {    len, wid int}  func (re Rect) Area() int {    return re.len * re.wid}  func main() {    r := Rect{10, 12}    fmt.Println("Length and Width are:", r)    fmt.Println("Area of Rectangle: ", r.Area())}
Output:
Length and Width are: {10, 12}
Area of Rectangle: 120

Go language does not use keywords like this or self, rather, in Go language, when you define a method associated with a type, it is given as a named variable (r Rect) (for eg. in the above case) and then within that method re variable is used.
In the above code, the instance of Rect is passed as a value, to call the method Area(). You can also pass it by reference. There will be no difference in calling the method whether the instance you are using to call it with is a pointer or a value, Go will automatically do the conversion for you.
package main  import "fmt"  // taking a structtype Rect struct {    len, wid int}  func (re Rect) Area_by_value() int {    return re.len * re.wid}  func (re *Rect) Area_by_reference() int {    return re.len * re.wid}  // main functionfunc main() {    r := Rect{10, 12}    fmt.Println("Length and Width is:", r)    fmt.Println("Area of Rectangle is:", r.Area_by_value())    fmt.Println("Area of Rectangle is:", r.Area_by_reference())    fmt.Println("Area of Rectangle is:", (&r).Area_by_value())    fmt.Println("Area of Rectangle is:", (&r).Area_by_reference())}
Output:
Length and Width is: {10, 12}
Area of Rectangle is: 120
Area of Rectangle is: 120
Area of Rectangle is: 120
Area of Rectangle is: 120

In the above code, we defined two similar methods, one takes the instance(Rect) as a pointer and another take it by value. Both the methods are called via a value r and as an address &r. But since Go perform appropriate conversions, it displays the same results.
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Tryit Editor v3.7

Tryit: HTML color names
How OLD and NEW keywords enable us to access columns in row affected by
a trigger?

As we know that in trigger definition, we can refer to columns of the row being inserted, updated or deleted. Following are the ways OLD and NEW keywords enable us to access columns −
We must have to prefix the column name with a qualifier of OLD to refer to a value from the original row.
We must have to prefix the column name with a qualifier of OLD to refer to a value from the original row.
We must have to prefix the column name with a qualifier of NEW to refer to a value in the new row.
We must have to prefix the column name with a qualifier of NEW to refer to a value in the new row.
Now, the use of OLD and NEW must be done appropriately because the triggering event
Determines which of them are allowable −
In an INSERT trigger, NEW.column_name indicates a column value to be inserted into a new row. Here OLD is not allowable.
In an INSERT trigger, NEW.column_name indicates a column value to be inserted into a new row. Here OLD is not allowable.
In a DELETE trigger, OLD.column_name indicates the value of a column in a row to be deleted. Here NEW is not allowable.
In a DELETE trigger, OLD.column_name indicates the value of a column in a row to be deleted. Here NEW is not allowable.
In an UPDATE trigger, OLD.column_name and NEW.column_name refer to the value of the column in a row before and after the row is updated respectively.
In an UPDATE trigger, OLD.column_name and NEW.column_name refer to the value of the column in a row before and after the row is updated respectively.
In other words, we can say that OLD must be used in read-only fashion and NEW can be used to read or change column values.
Following the example of DELETE trigger is showing the use of OLD −
mysql> CREATE TRIGGER studentinfo_after_delete
   -> AFTER DELETE
   -> ON student_info
   -> FOR EACH ROW FOLLOWS
   -> BEGIN
   -> DECLARE vuser varchar(30);
   -> SELECT USER() into vuser;
   -> INSERT INTO student_info_deleted(id,deleted_date,deleted_by) VALUES(OLD.id,SYSDATE(),vuser);
   -> END; //
Query OK, 0 rows affected (0.25 sec)
Following the example of INSERT trigger is showing the use of NEW −
mysql> Create Trigger before_inser_studentage BEFORE INSERT ON
student_age FOR EACH ROW
BEGIN
IF NEW.age < 0 THEN SET NEW.age = 0;
END IF;
END //
Query OK, 0 rows affected (0.30 sec)
How to scroll to element in horizontal div using jQuery?

To scroll to element in horizontal div, use the scrollleft.
You can try to run the following code to learn how to scroll to element in jQuery:
Live Demo
<html>
   <head>
   
      <title>jQuery Scroll</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
           document.addEventListener('DOMContentLoaded', function () {
              var frames = document.getElementById('frames');
              frames.addEventListener('click', function (e) {
                 if (e.target.classList.contains('item')) {
                   e.target.parentNode.scrollLeft = e.target.offsetLeft;
                 }
             });
          });
               
         });
      </script>
       
      <style>
     
        .myclass {
            width: 300px;
            display: flex;
            position: relative;
            overflow-x: scroll;
        }
   
        .item {
            width: 400px;
            background: #FFB563;
            margin-right: 40px;
        }
         </style>
         </head>
   <body>
   <div class="myclass" id="frames">
        <div class="item frames-item">demo1</div>
        <div class="item frames-item">demo2</div>
        <div class="item frames-item">demo3</div>
        <div class="item frames-item">demo4</div>
        <div class="item frames-item">demo5</div>
        <div class="item frames-item">demo6</div>
        <div class="item frames-item">demo7</div>
        <div class="item frames-item">demo8</div>
    </div>
   </body>
   
</html>
size_t data type in C

The datatype size_t is unsigned integral type. It represents the size of any object in bytes and returned by sizeof operator. It is used for array indexing and counting. It can never be negative. The return type of strcspn, strlen functions is size_t.
Here is the syntax of size_t in C language,
const size_t var_name;
Here,
var_name − This the name of variable.
Here is an example of size_t in C language,
 Live Demo
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
int main(void) {
   const size_t x = 150;
   int a[x];
   for (size_t i = 0;i < x; ++i)
   a[i] = i;
   printf("SIZE_MAX = %lu\n", SIZE_MAX);
   size_t size = sizeof(a);
   printf("size = %zu\n", size);
}
SIZE_MAX = 18446744073709551615
size = 600
In the above program, variable x of size_t datatype is declared. An array is also declared with the size x. size_t is a datatype of unsigned integral variable x. It is calculating the size of variable a in bytes.
printf("SIZE_MAX = %lu\n", SIZE_MAX);
size_t size = sizeof(a);
C++ Friend Functions

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows −
class Box {
   double width;
   
   public:
      double length;
      friend void printWidth( Box box );
      void setWidth( double wid );
};

To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne −
friend class ClassTwo;

Consider the following program −
#include <iostream>
 
using namespace std;
 
class Box {
   double width;
   
   public:
      friend void printWidth( Box box );
      void setWidth( double wid );
};

// Member function definition
void Box::setWidth( double wid ) {
   width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
   /* Because printWidth() is a friend of Box, it can
   directly access any member of this class */
   cout << "Width of box : " << box.width <<endl;
}
 
// Main function for the program
int main() {
   Box box;
 
   // set box width without member function
   box.setWidth(10.0);
   
   // Use friend function to print the wdith.
   printWidth( box );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Width of box : 10


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
How to group JSON data in JavaScript?

To group JSON data, you need to extract all the keys and use the push(). Following is the
code −
var details=
{
   "1":
   {
      name:"John"
   },
   "2":
   {
      name:"John"
   },
   "3":
   {
      name:"David"
   }
   var objectWithGroupByName = {};
   for (var key in details){
      var name = details[key].name;
   if (!objectWithGroupByName[name]){
      objectWithGroupByName[name] = [];
   }
   objectWithGroupByName[name].push(details[key]);
}
console.log(objectWithGroupByName);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo122.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo122.js
{
   John: [ { name: 'John' }, { name: 'John' } ],
   David: [ { name: 'David' } ]
}
How to Change Placeholder Color for Textboxes in CSS

Using the ::placeholder pseudo-element, we can change the placeholder text color for textboxes.
The syntax of CSS ::placeholder pseudo-element is as follows −
::placeholder {
   attribute: /*value*/
}
The following examples illustrate CSS :: placeholder pseudo-element.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
input:last-child::placeholder {
   color: cornflowerblue;
}
</style>
</head>
<body>
<input type="text" placeholder="Default color" />
<input type="text" placeholder="Check my new color :D" />
</body>
</html>
This will produce the following result −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
input::placeholder {
   color: fuchsia;
}
input {
   margin: 2%;
   width: 100%;
}
div {
   display: flex;
   flex-direction: column;
   margin: 3%;
   padding: 3%;
   text-align: center;
   align-items: center;
   box-shadow: inset 0 0 30px brown;
}
button {
   width: 40%;
}
</style>
</head>
<body>
<div>
<input type="text" placeholder="Normal placeholder" />
<input type="email" placeholder="somenone@somewhere.com" />
<button>dummy btn</button>
</div>
</body>
</html>
This will produce the following result −
Solidity - Conditional Operators

Try the following code to understand how the Conditional Operator works in Solidity.
pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }
   function getResult() public view returns(string memory){
      uint a = 1; // local variable
      uint b = 2;
      uint result = (a > b? a: b);  //conditional operation
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;
      while (j != 0) {
         len++;
         j /= 10;
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);
   }
}
Run the above program using steps provided in Solidity First Application chapter.
0: string: 2


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Transform the element along with x-axis and y-axis with CSS

Use the translate(x,y) method to transform the element along with x-axis and y-axis.
Let us see the syntax
translate(x,y)
Here, x is a length representing the x-coordinate of the translating vector.
y is a length representing the ordinate of the translating vector
Let us see an example
div {
   width: 50px;
   height: 50px;
   background-color: orange;
}
.trans {
   transform: translate(20px);
   background-color: black;
}
Python | Convert String list to ascii values

23 Jun, 2022
Sometimes, while working with Python, we can have a problem in which we need to convert String List to ascii values. This kind of problem can occur many times. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + ord() This problem can be solved using above functionalities. In this, we iterate the list and convert each character to it’s ascii number using ord(). 
Python3
# Python3 code to demonstrate working of# Convert String list to ascii values# using loop + ord() # initialize listtest_list = ['gfg', 'is', 'best'] # printing original listprint("The original list : " + str(test_list)) # Convert String list to ascii values# using loop + ord()res = []for ele in test_list:    res.extend(ord(num) for num in ele) # printing resultprint("The ascii list is : " + str(res))
The original list : ['gfg', 'is', 'best']
The ascii list is : [103, 102, 103, 105, 115, 98, 101, 115, 116]
 Method #2 : Using list comprehension + ord() This is yet another way to perform this task. This is just shorthand to above problem in which we compact the code using list comprehension using similar logic. 
Python3
# Python3 code to demonstrate working of# Convert String list to ascii values# using list comprehension + ord() # initialize listtest_list = ['gfg', 'is', 'best'] # printing original listprint("The original list : " + str(test_list)) # Convert String list to ascii values# using list comprehension + ord()res = [ord(ele) for sub in test_list for ele in sub] # printing resultprint("The ascii list is : " + str(res))
The original list : ['gfg', 'is', 'best']
The ascii list is : [103, 102, 103, 105, 115, 98, 101, 115, 116]
Method#3: Using reduce() and map function + ord function: reduce is used to iterate over the list of string and Map function is used to convert the string to list of its ascii value by using ord as it’s function.  
Python3
# Python 3 code to convert# string list to ascii value# using redunce and map function#importing reduce functionfrom functools import reduce # list of stringtest_str = ["gfg", "is", "best"]; # printing original listprint("Original list is : " + str(test_str)) # using redunce and map to convert# list of string to ascii valuek = reduce(lambda x,y  + list(map(ord, y)),test_str, [])print("The ascii list is : ", str(k))
Output:
Original list is : ['gfg', 'is', 'best']
The ascii list is :  [103, 102, 103, 105, 115, 98, 101, 115, 116]
satyam00so
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers