code-rag-bench/online-tutorials huggingface dataset:
Difference Between Network Address Translation (NAT) and Port Address Translation (PAT) - GeeksforGeeks

15 Jun, 2020
Network Address Translation (NAT):NAT, in which the Private IP address or local address are translated into the public IP address. NAT is used to slow down the rate of depletion of available IP address by translates the local IP or Private IP address into global or public ip address. NAT can be a one-to-one relation or many-to-one relation.
Port Address Translation (PAT):In PAT, Private IP addresses are translated into the public IP address via Port numbers. PAT also uses IPv4 address but with port number. It have two types:
1. Static
2. Overloaded PAT 
Difference Between Network Address Translation (NAT) and Port Address Translation (PAT):
Akanksha_Rai
manmeetjuneja5
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
TCP 3-Way Handshake Process
Implementation of Diffie-Hellman Algorithm
UDP Server-Client implementation in C
User Datagram Protocol (UDP)
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Designing GUI applications Using PyQt in Python - GeeksforGeeks

07 Sep, 2021
Building GUI applications using the PYQT designer tool is comparatively less time-consuming than code the widgets. It is one of the fastest and easiest ways to create GUIs. 
The normal approach is to write the code even for the widgets and for the functionalities as well. But using Qt-designer, one can simply drag and drop the widgets, which comes very useful while developing big-scale applications. 
Installation of PyQt5 : 
For Linux :
 sudo apt-get install python3-pyqt5
For Windows : 
 pip install pyqt5
 pip install pyqt5-tools 
Let’s create a signup form using the QT designer tool. No code is required for creating forms, buttons, text boxes, etc! It is a rather drag and drops environment. So, using PyQt is a lot simpler than Tkinter. 
QT Designer will be located at MyPythonInstallationDir\Lib\site-packages\pyqt5-tools and is named designer.exe (on Windows OS). Open Qt Designer, then select Main Window and click Create. Set your preferred size of the window by dragging the edges of the window. 
To create the layout of the Signup form, the following widgets are needed : 
Three text edit boxes.One button.Four Text Labels (SignId Banner, UserName label, Password and Confirm Password label).
Three text edit boxes.
One button.
Four Text Labels (SignId Banner, UserName label, Password and Confirm Password label).
One has to find those widgets in Widget Tool Box. Just drag and drop the required widgets onto the Main Window or the window working on.  
To change the appearance of the window or the widget, just right click on the widget and click Change StyleSheet.  
To get a preview of the window, press Ctrl + R. 
Save the file : The file will be saved with the .ui extension. To convert this file (.ui extension) to a Python file (.py extension), follow these steps :  
Open the terminal and navigate to the folder where the layout.UI file is present.To convert into a Python file, type pyuic5 -x layout.ui -o layout.py on a terminal.Run layout.py using python!
Open the terminal and navigate to the folder where the layout.UI file is present.
To convert into a Python file, type pyuic5 -x layout.ui -o layout.py on a terminal.
Run layout.py using python!
 
fridayda13
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
Python-PyQt
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
Wilson's Theorem - GeeksforGeeks

19 Nov, 2016
Wilson’s theorem states that a natural number p > 1 is a prime number if and only if

    (p - 1) ! ≡  -1   mod p 
OR  (p - 1) ! ≡  (p-1) mod p
 
Examples:
p  = 5
(p-1)! = 24
24 % 5  = 4

p  = 7
(p-1)! = 6! = 720
720 % 7  = 6

How does it work?1) We can quickly check result for p = 2 or p = 3.
2) For p > 3: If p is composite, then its positive divisors are among the integers 1, 2, 3, 4, ... , p-1 and it is clear that gcd((p-1)!,p) > 1, so we can not have (p-1)! = -1 (mod p).
3) Now let us see how it is exactly -1 when p is a prime. If p is a prime, then all numbers in [1, p-1] are relatively prime to p. And for every number x in range [2, p-2], there must exist a pair y such that (x*y)%p = 1. So
    [1 * 2 * 3 * ... (p-1)]%p 
 =  [1 * 1 * 1 ... (p-1)] // Group all x and y in [2..p-2] 
                          // such that (x*y)%p = 1
 = (p-1)
How can it be useful?Consider the problem of computing factorial under modulo of a prime number which is close to input number, i.e., we want to find value of “n! % p” such that n < p, p is a prime and n is close to p. For example (25! % 29). From Wilson's theorem, we know that 28! is -1. So we basically need to find [ (-1) * inverse(28, 29) * inverse(27, 29) * inverse(26) ] % 29. The inverse function inverse(x, p) returns inverse of x under modulo p (See this for details).
See this for more applications of Wilson’s Theorem.
References:https://en.wikipedia.org/wiki/Wilson’s_theoremhttps://primes.utm.edu/notes/proofs/Wilsons.html
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Modular Arithmetic
Prime Number
Mathematical
Mathematical
Prime Number
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Minimum number of jumps to reach end
C | Data Types | Question 4 - GeeksforGeeks

24 Sep, 2020
Predict the output of following C program
#include <stdio.h>int main(){    char a = 012;      printf("%d", a);      return 0;}
(A) Compiler Error(B) 12(C) 10(D) EmptyAnswer: (C)Explanation: The value ‘\012’ means the character with value 12 in octal, which is decimal 10.Note: It is equivalent to char a = 012 and int a = ‘\012’ and int a = 012.Quiz of this Question
shaztri
pin_ftv
C-Data Types
Data Types
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C | Arrays | Question 7
C | Advanced Pointer | Question 1
C | Operators | Question 2
C | Structure & Union | Question 10
C | Structure & Union | Question 4
C | Loops & Control Structure | Question 8
C | Advanced Pointer | Question 2
C | Pointer Basics | Question 4
C | Pointer Basics | Question 14
C | Operators | Question 1
Construct ∈-NFA of Regular Language L = 0(0+1)*1

The ∈ transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ
∈-NFA is defined in five tuple representation
{Q, q0, Σ, δ, F}
Where,
δ − Q × (Σ∪∈)->2Q
δ − Q × (Σ∪∈)->2Q
Q − Finite set of states
Q − Finite set of states
Σ − Finite set of the input symbol
Σ − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ: Transition function
δ: Transition function
NFA also has five states same as DFA, but with different transition function, as shown follows −
δ:Q×∑⟶2Q
Where,
Q − Finite set of states
Q − Finite set of states
Σ − Finite set of the input symbol
Σ − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ − Transition function
δ − Transition function
Consider NFA with ε as follows −
Here q0 is a start state with input 0, one can be either in state q0 or in state q1.
If we get at the start symbol 1 then with epsilon transition, we can change state from q0 to q1 and then input 1 can be in state q1.
On the other hand, from state q0 with input 1, we can reach state q2.
Thus, it is not sure that on input 1 whether we will be in state q1 or q2.
Hence it is called non deterministic finite automata and since there are some epsilon moves by which we can simply change the state from 1 to other.
Hence it is called NFA with epsilon.
Let’s consider the given language L = 0(0+1)*1.
Steps for construction for ε-NFA are as follows −
Step 1 − NFA with epsilon for 0+ is as follows −
Step 2 − NFA with epsilon for 0* is as follows −
Step 3 − NFA with epsilon for (0+1) is as follows −
The above transition diagram accepts either 0 or 1 as input. Those two paths lead to the final state.
Step 4 − NFA with epsilon for 01 is as follows −
For concatenation 0 must be followed by 1.
Step 5 − ε-NFA for L = 0(0+1)*1 is as follows −
L = 0(0+1)*1 is divided into three parts- 0, (0+1)* and 1. The second part, (0+1)*, is constructed above just concatenate with 0 and 1, followed by second rule 0*.
The final NFA with epsilon move is as follows −
Python Program for simple interest

In this article, we will learn about the calculation of simple interest in Python 3.x. Or earlier.
Simple interest is calculated by multiplying the daily interest rate by the principal amount by the number of days that elapse between the payments.
Mathematically,
Simple Interest = (P x T x R)/100
Where,
P is the principal amount
T is the time and
R is the rate
For example,
If P = 1000,R = 1,T = 2
Then SI=20.0
Now let’s see how we can implement a simple interest calculator in
Python.
 Live Demo
P = 1000
R = 1
T = 2
# simple interest
SI = (P * R * T) / 100
print("simple interest is", SI)
simple interest is 20.0
Here the simple interest is obtained three arithmetic products and one arithmetic division.
Now let’s see the scope of the variables declared. As shown in the figure below all variables are declared in the global scope.
In this article, we learned about simple interest and it’s implementation using Python script.
How to find maximum value in an array using spread operator in JavaScript?

We have logical methods and also many inbuilt methods to find a maximum value in an array, but the use of spread operator has made our task much easier to find the maximum value. Inbuilt method Math.max() is the most common method used to find a maximum value in an array. But in this method, we need to pass all the elements individually, making our task harder. So to alleviate this problem spread operator comes into the picture.
In the following example, the spread operator doesn't accompany Math.max() function. Every value of an array is sent into the math function. It is fine if there is a small set of values, but in case of a large set of values, it is difficult to pass every element into math function. 
Live Demo
<html>
<body>
   <script>
      var array = [1,2,3];
      var Max1 = Math.max(array);
      var Max2 = Math.max(array[1],array[1],array[2]) ;
      document.write(Max1);
      document.write("<br>");
      document.write(Max2);
   </script>
</body>
</html>
NaN
3
In the following example, spread operator (...) is used instead of sending each value into math function. This is a modern method used to find the maximum value in an array.
Live Demo
<html>
<body>
   <script>
      var array = [1,2,3];
      var Max1 = Math.max(array);
      var Max2 = Math.max(...array) ;
      document.write(Max1);
      document.write("<br>");
      document.write(Max2);
   </script>
</body>
</html>
NaN
3
How to remove duplicates from an ArrayList in Java?

In Java, Set object does not allow duplicate elements so you can remove duplicates from a list by creating a set object by passing required List object to its constructor.
Example:
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;

public class ArrayListSample {
   public static void main(String[] args){
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      Set<String> set = new LinkedHashSet<String>(list);
      System.out.println(set);
   }
}
Output:
[JavaFx, Java, WebGL, OpenCV]
C++ Logical Operators

Try the following example to understand all the logical operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this program.
#include <iostream>
using namespace std;

main() {
   int a = 5;
   int b = 20;
   int c ;

   if(a && b) {
      cout << "Line 1 - Condition is true"<< endl ;
   }
   
   if(a || b) {
      cout << "Line 2 - Condition is true"<< endl ;
   }
   
   /* Let's change the values of  a and b */
   a = 0;
   b = 10;
   
   if(a && b) {
      cout << "Line 3 - Condition is true"<< endl ;
   } else {
      cout << "Line 4 - Condition is not true"<< endl ;
   }
   
   if(!(a && b)) {
      cout << "Line 5 - Condition is true"<< endl ;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true


    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
array_search() function in PHP

The array_search() function searches an array for a given value and returns the key. The function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.
array_search(val, arr, strict)
val − The value to be searched
val − The value to be searched
arr − The array to be searched
arr − The array to be searched
strict − Possible values are TRUE or FALSE. Search for identical elements in the array, set to TRUE.
strict − Possible values are TRUE or FALSE. Search for identical elements in the array, set to TRUE.
The array_search() function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.
The following is an example −
 Live Demo
<?php
$arr = array("p"=>20,"q"=>20,"r"=>30,"s"=>40);
echo array_search(20,$arr,true);
?>
The following is the output −
p
Let us see another example −
 Live Demo
<?php
$arr = array(30, 2, 5, 7, 90, 35, 78);
echo array_search(35,$arr,true);
?>
The following is the output −
5
Let us see another example with array having string values −
 Live Demo
<?php
$arr = array("MAC", "WINDOWS","LINUX", "SOLARIS");
$search = "WINDOWS";
echo array_search($search,$arr,true);
?>
The following is the output −
1
Electron - Building UIs

The User Interface of Electron apps is built using HTML, CSS and JS. So we can leverage all the available tools for front-end web development here as well. You can use the tools such as Angular, Backbone, React, Bootstrap, and Foundation, to build the apps.
You can use Bower to manage these front-end dependencies. Install bower using −
$ npm install -g bower

Now you can get all the available JS and CSS frameworks, libraries, plugins, etc. using bower. For example, to get the latest stable version of bootstrap, enter the following command −
$ bower install bootstrap

This will download bootstrap in bower_components. Now you can reference this library in your HTML. Let us create a simple page using these libraries.
Let us now install jquery using the npm command −
$ npm install --save jquery

Further, this will be required in our view.js file. We already have a main.js setup as follows −
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')

let win

function createWindow() {
   win = new BrowserWindow({width: 800, height: 600})
   win.loadURL(url.format ({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true
   }))
}

app.on('ready', createWindow)
Open your index.html file and enter the following code in it −
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8">
      <title>Hello World!</title>
      <link rel = "stylesheet" 
         href = "./bower_components/bootstrap/dist/css/bootstrap.min.css" />
   </head>
   
   <body>
      <div class = "container">
         <h1>This page is using Bootstrap and jQuery!</h1>
         <h3 id = "click-counter"></h3>
         <button class = "btn btn-success" id = "countbtn">Click here</button>
         <script src = "./view.js" ></script>
      </div>
   </body>
</html>
Create view.js and enter the click counter logic in it −
let $ = require('jquery')  // jQuery now loaded and assigned to $
let count = 0
$('#click-counter').text(count.toString())
$('#countbtn').on('click', () => {
   count ++ 
   $('#click-counter').text(count)
}) 
Run the app using the following command −
$ electron ./main.js

The above command will generate the output as in the following screenshot −
You can build your native app just like you build websites. If you do not want users to be restricted to an exact window size, you can leverage the responsive design and allow users to use your app in a flexible manner.

    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    9 Lectures 
     41 mins

 Ashraf Said

    8 Lectures 
     32 mins

 Ashraf Said

    25 Lectures 
     1 hours 

 Ashraf Said

    17 Lectures 
     1 hours 

 Ashraf Said

    8 Lectures 
     25 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
How to set the top margin of an element with JavaScript?

Use the marginTop property in JavaScript, to set the top margin. Can you try to run the following code to set the top margin of an element with JavaScript?
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #myID {
            border: 2px solid #000000;
         }
      </style>
   </head>
   <body>
      <div id="myID">This is demo text.</div><br>
      <button type="button" onclick="display()">Add top margin</button>
      <script>
         function display() {
            document.getElementById("myID").style.marginTop = "150px";
         }
      </script>
   </body>
</html>
Apply operations on a collection in Julia - map() and map!() Methods - GeeksforGeeks

26 Mar, 2020
The map() is an inbuilt function in julia which is used to transform the specified collection by using specified operation to each element.
Syntax: map(f, c...)
Parameters:
f: Specified operation.
c: Specified collection.
Returns: It returns the transformed elements.
Example:
# Julia program to illustrate # the use of map() method  # Getting the transformed elements.println(map(x -> x * 2, [5, 10, 15]))println(map(+, [1, 2, 3], [10, 20, 30]))println(map(x -> x / 5, [5, 10, 15]))println(map(-, [10, 20, 30], [1, 2, 3]))
Output:
[10, 20, 30]
[11, 22, 33]
[1.0, 2.0, 3.0]
[9, 18, 27]
The map!() is an inbuilt function in julia. This function is same as map() function but stores the result in destination rather than a new collection. The destination must be at least as large as the first collection.
Syntax:map!(function, destination, collection...)
Parameters:
function: Specified operation.
destination: The destination where the result get stored.
collection: Specified collection.
Returns: It returns the transformed elements.
Example:
# Julia program to illustrate # the use of map !() method  # Getting the transformed elements.a = zeros(3);map !(x -> x * 3, a, [1, 2, 3]);println(a)  b = ones(3);map !(x -> x / 3, b, [3, 6, 9]);println(b)
Output:
[3.0, 6.0, 9.0]
[1.0, 2.0, 3.0]

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get array dimensions and size of a dimension in Julia - size() Method
Exception handling in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Working with Excel Files in Julia
Get number of elements of array in Julia - length() Method
Getting last element of an array in Julia - last() Method
Join an array of strings into a single string in Julia - join() Method
File Handling in Julia
How to extract a div tag and its contents by id with BeautifulSoup? - GeeksforGeeks

03 Mar, 2021
Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify HTML webpages. This article depicts how beautifulsoup can be employed to extract a div and its content by its ID. For this, find() function of the module is used to find the div by its ID.
Approach:
Import module
Scrap data from a webpage
Parse the string scraped to HTML
Find the div with its ID
Print its content
Syntax : find(tag_name, **kwargs)
Parameters:
The tag_name argument tell Beautiful Soup to only find tags with given names. Text strings will be ignored, as will tags whose names that don’t match.
The **kwargs arguments are used to filter against each tag’s ‘id’ attribute.
Below is the implementation:
Example 1:
Python3
#importing modulefrom bs4 import BeautifulSoup  markup = '''<html><body><div id="container">Div Content</div></body></html>'''soup = BeautifulSoup(markup, 'html.parser')  #finding the div with the iddiv_bs4 = soup.find('div', id = "container")  print(div_bs4.string)
Output:
Div Content
Example 2:
Python3
#importing modulefrom bs4 import BeautifulSoup  markup =markup = """  <!DOCTYPE><html>  <head><title>Example</title></head>    <body>        <p>        Nested div      </p>          <div id="first"> Div with ID first          <div id="second"> Div with id second          </div>        </div>     </body></html>"""  # parsering string to HTML soup = BeautifulSoup(markup, 'html.parser')  #finding the div with the iddiv_bs4 = soup.find('div', id = "second")  print(div_bs4.string)
Output:
 Div with id second
Picked
Python BeautifulSoup
Python bs4-Exercises
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
Bayes's Theorem for Conditional Probability - GeeksforGeeks

28 Jun, 2021
We strongly recommend to refer below post as a pre-requisite for this.
Conditional Probability
Bayes’s formulaBelow is Bayes’s formula.
The formula provides the relationship between P(A|B) and P(B|A). It is mainly derived from conditional probability formula discussed in the previous post.Consider the below formulas for conditional probabilities P(A|B) and P(B|A) —-(1)
 —-(2)
Since P(B ∩ A) = P(A ∩ B), we can replace P(A ∩ B) in the first formula with P(B|A)P(A)
After replacing, we get the given formula.
Product Rule
Product rule states that
(1)   
So the joint probability that both X and Y will occur is equal to the product of two terms:
From the product rule : implies P(X|Y) = P(X)/P(Y) implies P(X|Y) = 1
Chain rule
When the above product rule is generalized we lead to chain rule. Let there are  n events . Then, the joint probability is given by
(2)   
Bayes’ Theorem
From the product rule,  and  . As  and  are same .
(3)   
where  .
Example : Box P has 2 red balls and 3 blue balls and box Q has 3 red balls and 1 blue ball. A ball is selected as follows:
(i)  Select a box
(ii) Choose a ball from the selected box such that each ball in
     the box is equally likely to be chosen. The probabilities of
     selecting boxes P and Q are (1/3) and (2/3), respectively.  
Given that a ball selected in the above process is a red ball, the probability that it came from the box P is (GATE CS 2005)(A) 4/19(B) 5/19(C) 2/9(D) 19/30
Solution:
R --> Event that red ball is selected
B --> Event that blue ball is selected
P --> Event that box P is selected
Q --> Event that box Q is selected

We need to calculate P(P|R)?


P(R|P) = A red ball selected from box P
       = 2/5
P(P) = 1/3
P(R) = P(P)*P(R|P) + P(Q)*P(R|Q)
     = (1/3)*(2/5) + (2/3)*(3/4)
     = 2/15 + 1/2
     = 19/30

Putting above values in the Bayes's Formula
P(P|R) = (2/5)*(1/3) / (19/30)
       = 4/19
Exercise A company buys 70% of its computers from company X and 30% from company Y. Company X produces 1 faulty computer per 5 computers and company Y produces 1 faulty computer per 20 computers. A computer is found faulty what is the probability that it was bought from company X?
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Surya Priy
caogdue13
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inequalities in LaTeX
Newton's Divided Difference Interpolation Formula
Arrow Symbols in LaTeX
Set Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
The nameof keyword in C#

The nameof operator returns a string literal of an element that can be a variable, type or member.
For example, the following is our variable −
var vehicle = "motorbike";
To get the string literal, use nameof −
nameof(vehicle);
The following is the code to implement nameof keyword −
 Live Demo
using System;

public class Program {
   static void Main() {
      var vehicle = "motorbike";
      Console.WriteLine(nameof(vehicle));

      var time = DateTime.Now.ToLocalTime();
      Console.WriteLine(nameof(time));

      var a = false;
      Console.WriteLine(nameof(a));
   }
}
vehicle
time
a
How to Restart a Service in Linux? - GeeksforGeeks

30 Jun, 2020
Everything which is executed or is running on a Linux machine is linked to a service. In many cases, we come across situations when we have to restart those services. Those situations could be like service is using too much RAM memory or consuming a lot of CPU or the service is malfunctioning or could be any other situation for testing purposes. So, in order to do that we have to follow the procedure which is given below.
The very first step is to open the terminal and look for the service to restart. Then just fire a command to restart the service and the service will stop and start again.
1. Open the terminal:
All the Linux distributions have an application menu, so just look for the terminal there and open the same. After finding the terminal, just click on the app icon to open it. In many Linux, the terminal will be at the top or bottom of the screen in the application dock.
2. Displaying the running service:
So to display the current running service just type the following command.
ls /etc/init.d
So typing this will give you all the services that are running currently.
3. Services you want to restart:
So just select the service you want to restart, you will generally find the service you want to restart on the left side of the screen(it depends on your Linux distribution). For instance let it be “apache2”
4. Restarting your service:
So Basically at this stage, you have selected the service you want to restart.So type the following command to restart the service
sudo systemctl restart apache2
5. Entering Authentication Details:
Type in the password of your linux user account then as soon as you press enter the service would be restarted.
So if the above method didn’t work then just type the following command
sudo systemctl stop service
Then press Enter, this will stop your service. Then enter the following command to start the service again.
sudo systemctl start service
This will start your service again.
Picked
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
How to Run a Python Script using Docker?
Top Programming Languages for Android App Development
Running Python script on GPU.
Add matching object values in JavaScript

Suppose, we have an array of objects like this −
const arr = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];
Each object is bound to have unique in itself (for it to be a valid object), but two different objects can have the common keys (for the purpose of this question).
We are required to write a JavaScript function that takes in one such array and returns an object with all the unique keys present in the array and their values cumulative sum as the value.
So, the resultant object should look like −
const output = {a: 6, b: 9, c: 6, d: 3};
Therefore, let’s write the code for this function −
The code for this will be −
const arr = [{a: 2, b: 5, c: 6}, {a: 3, b: 4, d:1}, {a: 1, d: 2}];
const sumArray = arr => {
   const res = {};
   for(let i = 0; i < arr.length; i++){
      Object.keys(arr[i]).forEach(key => {
         res[key] = (res[key] || 0) + arr[i][key];
      });
   };
   return res;
};
console.log(sumArray(arr));
The output in the console will be −
{ a: 6, b: 9, c: 6, d: 3 }
How to increase the length of an R data frame by repeating the number of rows?

If we strongly believe that new data collection will result in the same type of data then we might want to stretch our data frame in R with more rows. Although, this is not recommended because we lose unbiasedness in the data due to this process but it is done to save time and money that will be invested in new data collection. In R, we can use rep with seq_len function to repeat the number of rows of an R data frame.
Consider the below data frame −
> x1<-c("Fruits","Vegetables","Dry Fruits","Dairy")
> x2<-c(2,5,6,3)
> df<-data.frame(x1,x2)
> df
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3
Repeating the number of rows twice but one repetition follows the other −
> df[rep(seq_len(nrow(df)),times=2),]
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3
1.1 Fruits 2
2.1 Vegetables 5
3.1 Dry Fruits 6
4.1 Dairy 3
Repeating the number of rows five times but one repetition follows the other −
> df[rep(seq_len(nrow(df)),times=5),]
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3
1.1 Fruits 2
2.1 Vegetables 5
3.1 Dry Fruits 6
4.1 Dairy 3
1.2 Fruits 2
2.2 Vegetables 5
3.2 Dry Fruits 6
4.2 Dairy 3
1.3 Fruits 2
2.3 Vegetables 5
3.3 Dry Fruits 6
4.3 Dairy 3
1.4 Fruits 2
2.4 Vegetables 5
3.4 Dry Fruits 6
4.4 Dairy 3
Repeating each row with equal number of times −
> df[rep(seq_len(nrow(df)),each=5),]
x1 x2
1 Fruits 2
1.1 Fruits 2
1.2 Fruits 2
1.3 Fruits 2
1.4 Fruits 2
  2 Vegetables 5
2.1 Vegetables 5
2.2 Vegetables 5
2.3 Vegetables 5
2.4 Vegetables 5
3 Dry Fruits 6
3.1 Dry Fruits 6
3.2 Dry Fruits 6
3.3 Dry Fruits 6
3.4 Dry Fruits 6
4        Dairy 3
4.1      Dairy 3
4.2      Dairy 3
4.3      Dairy 3
4.4      Dairy 3
Repeating the number of rows, a different number of times −
> df[rep(seq_len(nrow(df)),times=c(2,3,4,5)),]
x1 x2
1 Fruits 2
1.1 Fruits 2
2 Vegetables 5
2.1 Vegetables 5
2.2 Vegetables 5
3 Dry Fruits 6
3.1 Dry Fruits 6
3.2 Dry Fruits 6
3.3 Dry Fruits 6
4 Dairy 3
4.1 Dairy 3
4.2 Dairy 3
4.3 Dairy 3
4.4 Dairy 3
What are the tokens in C ?

A token is nothing but a smallest element of a program which is meaningful to the compiler. The compiler that breaks a program into the smallest units is called tokens and these tokens proceed to the different stages of the compilation.
Tokens are classified into different types, which are mentioned below −
Keywords
Identifiers
Constants
Strings
Special Symbols
Operators
Given below is the C program the use of identifiers, keywords, variables etc.
 Live Demo
#include <stdio.h>
int main(){
   int a,b,c;
   printf("enter a and b values: \n");
   scanf("%d%d",&a,&b);
   c=a*b;
   printf("value of c=%d",c);
   return 0;
}
When the above program is executed, it produces the following result −
enter a and b values:4 5
value of c=20
In the above program,
main is the identifier.
int is the keyword.
{ } are the delimiters.
a,b,c are the variables.
All together are called as tokens.
Get Root Directory Path of a PHP project?

In order to get the root directory path, you can use _DIR_ or dirname().
The syntax is as follows −
echo _DIR_;
The second syntax is as follows−
echo dirname(__FILE__);
Both the above syntaxes will return the same result.
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
   echo dirname(__FILE__);
   echo "<br>";
   echo __DIR__;
?>
</body>
</html>
/home/KOq8Zd
/home/KOq8Zd
What is the correct way to define global variables in JavaScript?

A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.
Commonly, a global variable is declared like the following −
<html>
   <body onload = checkscope();>
      <script>
         <!--
         var myVar = "global";   // Declare a global variable
         function checkscope() {
            document.write(myVar);
         }
         //-->
     </script>
   </body>
</html>
But, what you can above is the traditional method of using global variables. The best practice is to use it like the following with “window” −
<html>
   <body onload = checkscope();>
      <script>
         window.myVar = "global";   // Declare a global variable
         function checkscope( ) {
            alert(myVar);
         }
      </script>
   </body>
</html>
Find the position of number that is multiple of certain number - GeeksforGeeks

11 Oct, 2020
In this type of question, a number is given and we have to find the position or index of all multiples of that number. For doing this question we use a function named numpy.argwhere().
Syntax:
numpy.argwhere(array)

Example 1: 
Sometimes we need to find the indexes of the element that are divisible by int or float number.
Python3
# Importing Pandas and Numpy librariesimport pandas as pdimport numpy as np  # Creating a Series of random numbersn_series = pd.Series(np.random.randint(1, 25, 15))print("Original Series:\n")print(n_series)  # Finding the indexes of numbers divisible by 3res_index = np.argwhere(n_series % 3==0)print("Positions of numbers that are multiples of 3:\n")print(res_index)
Output:
In the above example, we find the indexes of all numbers divisible by 3.
Example 2:
Python3
# Importing Pandas and Numpy librariesimport pandas as pdimport numpy as np  # Creating a Series of random numbersn_series = pd.Series(np.random.randint(1, 20, 10))print("Original Series:\n")print(n_series)  # Finding the indexes of numbers divisible by 3.5res_index = np.argwhere(n_series % 3.5==0)print("Positions of numbers that are multiples of 3.5:\n")print(res_index)
Output:
In the above example, we find the indexes of all numbers divisible by floating-point number 3.5
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Cache and main memory - GeeksforGeeks

19 Nov, 2018
RAM chip size = 1k ×8[1024 words of 8 bits each]
RAM to construct =16k ×16
Number of chips required = (16k x 16)/ ( 1k x 8)
                         = (16 x 2)
[16 chips vertically with each having 2 chips
horizontally]
So to select one chip out of 16 vertical chips, 
we need 4 x 16 decoder.

Available decoder is  2 x 4 decoder
To be constructed is 4 x 16 decoder

Hence 4 + 1 = 5 decoders are required.
   Cache size = 8 KB
   Block size = 32 bytes
   Number of cache lines = Cache size / Block size = (8 × 1024 bytes)/32 = 256

   

   total bits required to store meta-data of 1 line = 1 + 1 + 19 = 21 bits
   total memory required = 21 × 256 = 5376 bits
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Token, Patterns, and Lexems
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Compiler Design - Variants of Syntax Tree
Optimization of Basic Blocks
OSI Security Architecture
TCS NQT Coding Sheet
A Freshers Guide To Programming
How to remove string accents using Python 3?

02 Jul, 2021
String accents are special string characters adapted from languages of other accents. In this article, we are going to remove ascents from a string.
Examples:
Input: orčpžsíáýd
Output: orcpzsiayd
Input: stävänger
Output: stavanger
We can remove accents from the string by using a Python module called Unidecode. This module consists of a method that takes a Unicode object or string and returns a string without ascents.
Syntax:
output_string = unidecode.unidecode(target_string )
Below are some examples which depict how to remove ascents from a string:
Example 1:
Python3
# import required moduleimport unidecode # assign stringstring = "orčpžsíáýd" # display original stringprint('\nOriginal String:', string) # remove ascentsoutputString = unidecode.unidecode(string) # display new stringprint('\nNew String:', outputString)
Output:
Original String: orčpžsíáýd

New String: orcpzsiayd
Example 2:
Python3
# import required moduleimport unidecode # assign stringstring = "stävänger" # display original stringprint('\nOriginal String:', string) # remove ascentsoutputString = unidecode.unidecode(string) # display new stringprint('\nNew String:', outputString)
Output:
Original String: stävänger

New String: stavanger
Example 3:
Python3
# import required moduleimport unidecode # assign stringstringList = ["hell°",  "tromsø",  "stävänger", "ölut"] # display original stringprint('\nOriginal List of Strings:\n', stringList) for i in range(len(stringList)):    # remove ascents    stringList[i] = unidecode.unidecode(stringList[i]) # display new stringprint('\nNew List of Strings:\n', stringList)
Output:
Original List of Strings:
 ['hell°', 'tromsø', 'stävänger', 'ölut']

New List of Strings:
 ['helldeg', 'tromso', 'stavanger', 'olut']
anikakapoor
Picked
python-string
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js os.EOL

13 Oct, 2021
The os.EOL constant is an inbuilt application programming interface of the os module which is used to get end-of-line character or marker as specified by the operating system.
Syntax:
os.EOL
Return Value: It returns the EOL (end-of-line marker) as specified by the operating system on which it is running.
Below examples illustrate the use of os.EOL constant in Node.js:
Example 1:
// Node.js program to demonstrate the   // os.EOL constants  // Allocating os moduleconst os = require('os');  // Printing os.EOL character(s) by// stringifying to JSON otherwise it// will simply print as end of lineconsole.log(JSON.stringify(os.EOL));
Output:
"\r\n"

Example 2:
// Node.js program to demonstrate the   // os.EOL constants  // Allocating os moduleconst os = require('os');  // Printing os.EOL character(s) with stringconsole.log("Paragraphs always contains EOL"        + os.EOL + "EOL stands for end of line");  console.log("EOL varies from os to os" + os.EOL            + "For windows it is \\r\\n" + os.EOL            + "For POSIX it is \\n" + os.EOL);
Output:
Paragraphs always contains EOL
EOL stands for end of line
EOL varies from os to os
For windows it is \r\n
For POSIX it is \n


Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_eol
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Float max() method with example

29 Oct, 2019
The max() method is utilized to return the maximum value of the two specified float numbers.
Method Definition: (First_Number).max(Second_Number)
Return Type: It returns the maximum value of the two specified float numbers.
Example #1:
// Scala program of Float max()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying max method        val result = (5.9).max(9.0)                  // Displays output        println(result)          }} 
9.0

Example #2:
// Scala program of Float max()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying max method        val result = (5.0).max(5.0)                  // Displays output        println(result)          }} 
5.0

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a given matrix to 1D array in R

06 May, 2022
In this article, let’s discuss how to convert a Matrix to a 1D array in R. 
matrix() function in R is used to create a matrix
Syntax: matrix(data,nrow,ncol,byrow,dimnames)
Parameter:
data-is the input vector which becomes the data elements of the matrix
nrow-is the numbers of rows to be created
ncol-is the numbers of columns to be created
byrow-is a logical clue,if it is true then input vector elements are arranged by row
dimname-is the names assigned to rows and columns
vector() function is used to convert object into vector.
Syntax:
vector(object)
Create matrix
Pass the created matrix to vector function
Print array
Example 1:
R
rows=c("r1","r2")cols=c("c1","c2","c3","c4") M=matrix(c(2:9),nrow=2,byrow=TRUE,dimnames=list(rows,cols)) print("Original matrix:")print(M) output=as.vector(M) print("1D array :")print(output)
Output 
[1] "Original matrix:"
  c1 c2 c3 c4
r1  2  3  4  5
r2  6  7  8  9
[1] "1D array :"
[1] 2 6 3 7 4 8 5 9
We can also convert only a given number of rows, for that simply pass the required number as value to nrow.
Example: 
R
rows=c("r1","r2","r3","r4")cols=c("c1","c2","c3","c4") M=matrix(c(2:17),nrow=4,byrow=TRUE,dimnames=list(rows,cols)) print("Original matrix:")print(M) output=as.vector(M) print("1D array :")print(output)
Output: 
[1] "Original matrix:"
  c1 c2 c3 c4
r1  2  3  4  5
r2  6  7  8  9
r3 10 11 12 13
r4 14 15 16 17
[1] "1D array :"
[1]  2  6 10 14  3  7 11 15  4  8 12 16  5  9 13 17
 
gulshankumarar231
rkbhola5
Picked
R-Matrix
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C++ Program | Set 2

10 Jul, 2018
Predict the output of below C++ programs.
Question 1
#include<iostream>using namespace std; class A {  public:    A(int ii = 0) : i(ii) {}    void show() { cout << "i = " << i << endl;} private:    int i;}; class B { public:    B(int xx) : x(xx) {}    operator A() const { return A(x); } private:    int x;}; void g(A a){  a.show(); } int main() {  B b(10);  g(b);  g(20);  getchar();  return 0;} 
Output:i = 10i = 20
Since there is a Conversion constructor in class A, integer value can be assigned to objects of class A and function call g(20) works. Also, there is a conversion operator overloaded in class B, so we can call g() with objects of class B.
Question 2
#include<iostream>using namespace std;  class base {    int arr[10];     };  class b1: public base { };  class b2: public base { };  class derived: public b1, public b2 {};  int main(void){   cout<<sizeof(derived);  getchar();  return 0;}
Output: If integer takes 4 bytes, then 80.
Since b1 and b2 both inherit from class base, two copies of class base are there in class derived. This kind of inheritance without virtual causes wastage of space and ambiguities. virtual base classes are used to save space and avoid ambiguities in such cases. For example, following program prints 48. 8 extra bytes are for bookkeeping information stored by the compiler (See this for details)
#include<iostream>using namespace std;  class base {  int arr[10];     };  class b1: virtual public base { };  class b2: virtual public base { };  class derived: public b1, public b2 {};  int main(void){   cout<<sizeof(derived);  getchar();  return 0;}
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How can we see the source code of a particular MySQL stored procedure?

With the help of SHOW CREATE PROCEDURE statement, we can see the source code of a stored procedure. To make it understand we are using the stored procedure named allrecords() in the query as follows −
mysql> Show Create Procedure allrecords\G
*************************** 1. row ***************************
Procedure: allrecords
sql_mode:ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Create Procedure: CREATE DEFINERb=`root`@`localhost` PROCEDURE `allrecords`()

BEGIN
Select * from Student_info;
END

character_set_client: cp850
collation_connection: cp850_general_ci
  Database Collation: latin1_swedish_ci
1 row in set (0.00 sec)