code-rag-bench/online-tutorials huggingface dataset:
Convert Kotlin Array to Java varargs

Varargs, also known as "variable arguments" is a new mechanism in Java by
which methods in Java can accept zero or multiple number of arguments.
Before this mechanism, the only option available to achieve this type of
functionality was "method overloading", but that also required multiple lines
of boilerplate code.
In this article, we will see how we can use Varags in Kotlin to call a function multiple times based on different types of arguments. The following example demonstrates how we can use this Varags keyword.
fun main() {
   // calling the function with 4 arguments and
   // passing 3 arguments as recurring call to the function
   val sumOf4Numbers = sum(12, sum(2, 4, 6))
   println("Sum of 4 numbers: " +sumOf4Numbers)
   // calling the same function with 3 arguments and
   // passing 2 arguments as recurring call to the function
   val sumOf3Numbers = sum(12, sum(2, 6))
   println("Sum of 3 numbers: " +sumOf3Numbers)
   // calling the same function with 2 arguments
   val sumOf2Numbers = sum(12, 2)
   println("Sum of 2 numbers: " +sumOf2Numbers)
   // calling the same function without any argument
   val sumOf0Numbers = sum()
   println("Sum of 0 numbers: " +sumOf0Numbers)
}

fun sum(vararg xs: Int): Int = xs.sum()
Once the above piece of code is executed, it will generate the following
output
Sum of 4 numbers: 24
Sum of 3 numbers: 20
Sum of 2 numbers: 14
Sum of 0 numbers: 0
<climits> (limits.h) in C/C++

The header files “limits.h” exists in C language while <climits> in C++ language. Several macros are defined in these header files. The limits specify that variable cannot store values beyond the limits.
Some macros in “limits.h” or <climits> header file are as follows
Here is an example of <climits> in C++ language,
 Live Demo
#include<iostream>
#include <bits/stdc++.h>
#include<climits>
using namespace std;
int main() {
   int x = 28;
   int a = CHAR_BIT*sizeof(x);
   stack<bool> s;
   cout << "The number is : " << x << endl;
   for (int i=1; i<=a; i++) {
      s.push(x%2);
      x = x/2;
   }
   cout << "The number of bits in a byte : " << CHAR_BIT << endl;
   for (int i=1; i<=a; i++) {
      cout << s.top();
      s.pop();
      if (i % CHAR_BIT == 0)
      cout << " ";
   }
   cout << "\n\nThe minimum value of short int :" << SHRT_MIN;
   return 0;
}
The number is : 28
The number of bits in a byte : 8
00000000 00000000 00000000 00011100

The minimum value of short int :-32768
In the above program, two macros of <climits> are represented. One is CHAR_BIT and another is SHRT_MIN. CHAR_BIT defines the number of bits in char and SHRT_MIN defines the minimum value for short int.
int x = 28;
int a = CHAR_BIT*sizeof(x);
....
cout << "\n\nThe minimum value of short int :" << SHRT_MIN;
Difference between Wait and Sleep in Java

Wait() - The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify() method or the notifyAll() method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
Sleep() - This method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors. It sends the current thread into the “Not Runnable” state for a specified amount of time.
synchronized(lockedObject){
   while(condition == true){
      lockedObject.wait() //releases lockedObject lock
   }
   Thread.sleep(100); //puts current thread on Sleep
}
Python Program for Detect Cycle in a Directed Graph - GeeksforGeeks

02 Jan, 2019
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true.
Python
# Python program to detect cycle # in a graph  from collections import defaultdict  class Graph():    def __init__(self, vertices):        self.graph = defaultdict(list)        self.V = vertices      def addEdge(self, u, v):        self.graph[u].append(v)      def isCyclicUtil(self, v, visited, recStack):          # Mark current node as visited and         # adds to recursion stack        visited[v] = True        recStack[v] = True          # Recur for all neighbours        # if any neighbour is visited and in         # recStack then graph is cyclic        for neighbour in self.graph[v]:            if visited[neighbour] == False:                if self.isCyclicUtil(neighbour, visited, recStack) == True:                    return True            elif recStack[neighbour] == True:                return True          # The node needs to be poped from         # recursion stack before function ends        recStack[v] = False        return False      # Returns true if graph is cyclic else false    def isCyclic(self):        visited = [False] * self.V        recStack = [False] * self.V        for node in range(self.V):            if visited[node] == False:                if self.isCyclicUtil(node, visited, recStack) == True:                    return True        return False  g = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)if g.isCyclic() == 1:    print "Graph has a cycle"else:    print "Graph has no cycle"  # Thanks to Divyanshu Mehta for contributing this code
Graph has a cycle

Please refer complete article on Detect Cycle in a Directed Graph for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Python | Get the first key in dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python Program for Merge Sort
Python | Find most frequent element in a list
Python - Convert JSON to string
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python program to find smallest number in a list
How to navigate URL in an iframe with JavaScript ? - GeeksforGeeks

23 Apr, 2021
To navigate URL in iframe with JavaScript, we have to set the src attribute or return the value of src attribute in an iframe element. The src attribute defines the URL of document that can be shown in an iframe.
Syntax:
document.getElementById("selector").src = "URL";
URL values: The possible values of URLs are –
Absolute URL: It points to another website (For example: https://www.geeksforgeeks.org/c-plus-plus/).
Relative URL: It points to a file within a website (For example: /gfg.php).
Return value: It returns the complete url of the document that is embedded in the iframe.
 
Example 1: Below is the code that illustrates using Absolute URL.
HTML
<!DOCTYPE html><html>  <body style="text-align:center;">    <iframe id="gfgFrame" src=""         style="height: 50vh; width: 600px;">    </iframe>      <p>Click to visit GeeksForGeeks website</p>      <button onclick="navigate()">        Click it    </button>      <script>        function navigate() {            document.getElementById("gfgFrame").src                = "https://www.geeksforgeeks.org/";        }    </script></body>  </html>
Output:
Example 2: Below is the code that illustrates the Relative URL.
HTML
<!DOCTYPE html><html>  <body style="text-align:center;">    <iframe id="gfgFrame" src=""         style="height: 50vh; width: 600px;">    </iframe>    <br>      <button onclick="navigate()">        Click it    </button>      <script>        function navigate() {            document.getElementById                ("gfgFrame").src = "home.html";        }    </script></body>  </html>
Output:
HTML-Questions
HTML-Tags
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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 ?
Difference between var, let and const keywords in JavaScript
GATE | GATE CS 2013 | Question 8 - GeeksforGeeks

28 Jun, 2021
Consider the languages L1 =  and L2 = {a}. Which one of the following represents L1 L2* U L1*
(A) A(B) B(C) C(D) DAnswer: (A)Explanation: L1 L2* U L1*
Result of L1 L2* is .
{} indicates an empty language. Concatenation of  with any other language is . It works as 0 in multiplication.
L1* = * which is {}.
Union of  and {} is {}Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Matplotlib.figure.Figure.set_figwidth() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_figwidth() method figure module of matplotlib library is used to set the width of the figure in inches.
Syntax: set_figwidth(self, val, forward=True)
Parameters: This method accept the following parameters that are discussed below:
val : This parameter is the float value.
forward : This parameter contains the boolean value.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_figwidth() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np     fig = plt.figure()        ax = Subplot(fig, 111) fig.add_subplot(ax)    fig.set_figwidth(7.6)     fig.suptitle("""matplotlib.figure.Figure.set_figwidth()function Example\n\n""", fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np           fig = plt.figure(figsize =(7, 6))         ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])      xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))     fig.set_figwidth(4.8)     fig.suptitle("""matplotlib.figure.Figure.set_figwidth()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Boolean compare() method in Java with Examples - GeeksforGeeks

08 Oct, 2018
The compare() method of Boolean class is a built in method in Java which is used to compare two boolean values. It is a static method, so it can be called without creating any object of the Boolean class i.e. directly using the class name.
Syntax:
Boolean.compare(boolean a, boolean b)
Parameters: It takes two boolean values a and b in the parameter which are to be compared.
Return Type: The return type of the function is int. It returns
0 if ‘a’ is equal to ‘b’,
a negative value if ‘a’is false and ‘b’ is true,
a positive value if ‘a’ is true and ‘b’ is false.
Below are programs to illustrate the compare() method of Boolean class:
Program 1:
// Java code to implement// compare() method of Boolean class  class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // first value        boolean a = true;          // second value        boolean b = true;          // compare method        System.out.println(a + " comparing with " + b                           + " = " + Boolean.compare(a, b));    }}
true comparing with true = 0

Program 2:
// Java code to implement// compare() method of Java class  class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // first value        boolean a = true;          // second value        boolean b = false;          // compare method        System.out.println(a + " comparing with " + b                           + " = " + Boolean.compare(a, b));    }}
true comparing with false = 1

Program 3:
// Java code to implement// compare() method of Java class  class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // first value        boolean a = false;          // second value        boolean b = true;          // compare method        System.out.println(a + " comparing with " + b                           + " = " + Boolean.compare(a, b));    }}
false comparing with true = -1

Java - util package
Java-Byte
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Shrink Text on Hover using HTML and CSS - GeeksforGeeks

29 Jul, 2020
Text can be Shrinked or condensed using some HTML and CSS properties, you can use this animation in your websites as headings or sub-headings, the below sections will guide you on how to create the desired effect.
HTML Code: In this section we have simple div  element which contains the text separated with span tags.
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width, initial-scale=1.0">  <title>Shrink Text</title></head>  <body>  <div>    <span>G</span><span>EEKS</span>    <span>F</span><span>OR</span>    <span>G</span><span>EEKS</span>  </div>      </body></html>
CSS Code: In this code fisr we design the div  element using basic CSS  properties and then to create the shrink effect we use the nth-child() Selector and set the letter spacing to -1em when we hover over the text.
<style>  *{    margin: 0;    padding: 0;  }  /* designing the text*/  div{    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);    display: flex;    font-size: 2.5em;    color: rgb(4, 110, 4);  }  /*creating the shrink animation*/  span:nth-child(even){    overflow: hidden;    letter-spacing: 0;    transition:  1s;  }    div:hover span:nth-child(even){    letter-spacing: -1em;  } </style>
Final Code: It is the combination of the above two code sections.
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width, initial-scale=1.0">  <title>Shrink Text</title></head><style>  *{    margin: 0;    padding: 0;  }  /* designing the text*/  div{    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);    display: flex;    font-size: 2.5em;    color: rgb(4, 110, 4);  }  /*creating the shrink animation*/  span:nth-child(even){    overflow: hidden;    letter-spacing: 0;    transition:  1s;  }    div:hover span:nth-child(even){    letter-spacing: -1em;  } </style>  <body>  <div>    <span>G</span><span>EEKS</span>    <span>F</span><span>OR</span>    <span>G</span><span>EEKS</span>  </div>  </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
CSS
HTML
Web Technologies
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?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
How to Install OpenSSH 8 Server from Source in Linux? - GeeksforGeeks

06 Oct, 2021
The OpenSSH is an open-source implementation of the SSH protocol that encrypts all traffic to eliminate eavesdropping, connection hijacking, and other attacks. It was developed by the OpenBSD Project and made available under a BSD-style license.
Remote operations can be performed using ssh, scp, and sftp.
Key management with ssh-add, ssh-keysign, ssh-keyscan, and ssh-keygen are included.
The service side includes sshd, sftp-server, and ssh-agent.
In this article, we will show you how to build and install OpenSSH from source in Debian-based Linux (Ubuntu/Kali/Linuxmint/Elementary).
First of all, we will install all the dependencies, before installing OpenSSH (make to build and install the source code, wget to download the tarball, etc).
sudo apt update
sudo apt install build-essential zlib1g-dev libssl-dev libpam0g-dev libselinux1-dev wget
Now create a new folder sshd in the /var/lib directory
sudo mkdir /var/lib/sshd
Then update file permission and ownership of the directory
sudo chmod -R 700 /var/lib/sshd/ && chown -R root:sys /var/lib/sshd/
To verify the changes, run :
ls -l -d /var/lib/sshd/
Here, we can see that sys is an owner and only the user has read, write and execute permissions for this directory.
Note: You click on these links to read more about file permission and ownership in Linux/Unix systems.
Now create a system user sshd
useradd -r -c 'sshd PrivSep' \
        -d /var/lib/sshd \
        -s /bin/false \
        -u 50 sshd
Here,
-r:  create a system user
-c:  add a comment
-d: specifies the directory
-s: specifies the user’s shell
-u: creates a new user sshd with UID 50
Download and configure OpenSSH tarball from HTTP mirrors provided by  OpenSSH. As of August 2021, version 8.7 is the latest but you can download any newer version, if available.
 wget -c -q https://cdn.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-8.7p1.tar.gz
 tar -xzf openssh-8.7p1.tar.gz && cd openssh-8.7p1
 ./configure –with-md5-passwords –with-pam –with-selinux –with-privsep-path=/var/lib/sshd/ –sysconfdir=/etc/ssh 
Finally, install the project using the make command.
make
sudo make install
To verify  the installation, run :
ssh -V
Blogathon-2021
how-to-install
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Types of Grammar

Theory of Computation
Grammar is a finite set of formal rules for generating syntactically correct sentences or meaningful correct sentences.
A Grammar can contain mainly two elements - Terminal and Non Terminal.
It is a portion of the sentence generated by using a grammar. It is denoted by using small letters, such as a, b, c, d, etc.
It takes part in the formation of a sentence, but not part of it. It is denoted by using capital letters, such as A, B, C, D, etc. It is also called auxiliary symbols.
A grammar G is a 4-tuple
G = (N,Σ,P,S)
N - It is a finite, non-empty set of symbols called variables or non-terminals or syntactic categories,
Σ - It is an alphabet of symbols called terminals, where N ∩ Σ = φ,
P - It is a finite set of "productions" or "rules",
S - It is the start or initial non terminal symbol of the grammar.
These are some notations that help you to understand the concept of grammar-
Non-terminal symbols represent as A, B, C, .... ∈ V
Terminal symbols represent as a, b, c, ... ∈ T
Generic symbols represent as X, Y, Z, ...∈ V ∪ T
Strings over T represents as p, q, r, s, ... ∈ T∗
Strings over V ∪ T represents α, β, γ, δ, ... ∈ (V ∪ T)∗
Let's say G is a grammar with start variable S and terminals Σ, then the language generated by L is -
L(G) = {w | w ∈ ∑* and S ⇒+w}
The Noam Chomsky classifies the types of grammar in four types - Type0, Type1, Type2 and Type3. It is also called Chomsky hierarchy of grammar. These are types of grammar used in the theory of computation.
where, A and B are non-terminal symbols, α and β are string of terminals and non-terminals and a is terminal symbol.
Apply uppercase to a column in Pandas dataframe in Python

In this tutorial, we are going to see how to make a column of names to uppercase in DataFrame. Let's see different ways to achieve our goal.
We can assign a column to the DataFrame by making it uppercase using the upper() method.
Let's see the code.
# importing the pandas package
import pandas as pd
# data for DataFrame
data = {
   'Name': ['Hafeez', 'Aslan', 'Kareem'],
   'Age': [19, 21, 18],
   'Profession': ['Developer', 'Engineer', 'Artist']
}
# creating DataFrame
data_frame = pd.DataFrame(data)
# displaying the DataFrame
print('---------------------Before-------------------')
print(data_frame)
print()
# making the Name column strings to upper case
data_frame['Name'] = data_frame['Name'].str.upper()
# displaying the DataFrame
print('---------------------After-------------------')
print(data_frame)
If you run the above program, you will get the following results.
---------------------Before-------------------
Name Age Profession
0 Hafeez 19 Developer
1 Aslan 21 Engineer
2 Kareem 18 Artist
---------------------After-------------------
Name Age Profession
0 HAFEEZ 19 Developer
1 ASLAN 21 Engineer
2 KAREEM 18 Artist
We can also achieve the same thing using apply() method of DataFrame. Let's see the related code.
# importing the pandas package
import pandas as pd
# data for DataFrame
data = {
   'Name': ['Hafeez', 'Aslan', 'Kareem'],
   'Age': [19, 21, 18],
   'Profession': ['Developer', 'Engineer', 'Artist']
}
# creating DataFrame
data_frame = pd.DataFrame(data)
# displaying the DataFrame
print('---------------------Before-------------------')
print(data_frame)
print()
# making the Name column strings to upper case
data_frame['Name'] = data_frame['Name'].apply(lambda name : name.upper())
# displaying the DataFrame
print('---------------------After-------------------')
print(data_frame)
If you run the above program, you will get the following results.
---------------------Before-------------------
Name Age Profession
0 Hafeez 19 Developer
1 Aslan 21 Engineer
2 Kareem 18 Artist
---------------------After-------------------
Name Age Profession
0 HAFEEZ 19 Developer
1 ASLAN 21 Engineer
2 KAREEM 18 Artist
I hope you learned something from the tutorial. If you have any doubts regarding the tutorial, ask them in the comment section.
What are the default values of static variables in C? - GeeksforGeeks

28 May, 2017
In C, if an object that has static storage duration is not initialized explicitly, then:— if it has pointer type, it is initialized to a NULL pointer;— if it has arithmetic type, it is initialized to (positive or unsigned) zero;— if it is an aggregate, every member is initialized (recursively) according to these rules;— if it is a union, the first named member is initialized (recursively) according to these rules.
For example, following program prints:Value of g = 0Value of sg = 0Value of s = 0
#include<stdio.h>int g;  //g = 0, global objects have static storage durationstatic int gs; //gs = 0, global static objects have static storage durationint main(){  static int s; //s = 0, static objects have static storage duration  printf("Value of g = %d", g);  printf("\nValue of gs = %d", gs);  printf("\nValue of s = %d", s);    getchar();  return 0;}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
References:The C99 standard
C-Storage Classes and Type Qualifiers
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Command line arguments in C/C++
fork() in C
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
std::string class in C++
Structures in C
'this' pointer in C++
Batch Script - Aliases

Aliases means creating shortcuts or keywords for existing commands. Suppose if we wanted to execute the below command which is nothing but the directory listing command with the /w option to not show all of the necessary details in a directory listing.
Dir /w

Suppose if we were to create a shortcut to this command as follows.
dw = dir /w

When we want to execute the dir /w command, we can simply type in the word dw. The word ‘dw’ has now become an alias to the command Dir /w.
Alias are managed by using the doskey command.
DOSKEY [options] [macroname=[text]]

Wherein
macroname − A short name for the macro.
macroname − A short name for the macro.
text − The commands you want to recall.
text − The commands you want to recall.
Following are the description of the options which can be presented to the DOSKEY command.
/REINSTALL
Installs a new copy of Doskey
/LISTSIZE = size
Sets size of command history buffer.
/MACROS
Displays all Doskey macros.
/MACROS:ALL
Displays all Doskey macros for all executables which have Doskey macros.
/MACROS:exename
Displays all Doskey macros for the given executable.
/HISTORY
Displays all commands stored in memory.
/INSERT
Specifies that new text you type is inserted in old text.
/OVERSTRIKE
Specifies that new text overwrites old text.
/EXENAME = exename
Specifies the executable.
/MACROFILE = filename
Specifies a file of macros to install.
macroname
Specifies a name for a macro you create.
text
Specifies commands you want to record.
Create a new file called keys.bat and enter the following commands in the file. The below commands creates two aliases, one if for the cd command, which automatically goes to the directory called test. And the other is for the dir command.
@echo off
doskey cd = cd/test
doskey d = dir

Once you execute the command, you will able to run these aliases in the command prompt.
The following screenshot shows that after the above created batch file is executed, you can freely enter the ‘d’ command and it will give you the directory listing which means that your alias has been created.
An alias or macro can be deleted by setting the value of the macro to NULL.
@echo off
doskey cd = cd/test
doskey d = dir
d= 

In the above example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will deleted.
An alias or macro can be replaced by setting the value of the macro to the new desired value.
@echo off
doskey cd = cd/test
doskey d = dir

d = dir /w

In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias ‘d’ will now take on the new value.
 Print
 Add Notes
 Bookmark this page
Use of & in scanf() but not in printf() - GeeksforGeeks

09 Jan, 2018
Why there is need of using ‘&’ in case if scanf function while not in case of printf function.
Examples:
scanf("%d %d", &a, &b);
printf("%d %d", a, b);

As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value.But in case of printf function as we are only going to print the values of the variables in output console, there are no changes going to be made in variable a and b’s values. So it is not required to send their addresses.
C-Functions
c-input-output
C Language
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
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
UDP Server-Client implementation in C
How to dynamically allocate a 2D array in C?
Input-output system calls in C | Create, Open, Close, Read, Write
How to restart MySQL server?

Restart the MySQL Server with the help of restart command.
The syntax is as follows
Restart
Let us first check the MySQL version.
The query is as follows
SELECT version();
Now, implement the above command in order to restart the MySQL Server.
The query is as follows
mysql> restart;
Query OK, 0 rows affected (0.00 sec)
Now, MySQL Server is being restarted. If you try to perform any query during the restart command, you will get an error.
The query is as follows
mysql> show databases;
ERROR 2013 (HY000): Lost connection to MySQL server during query
If the MySQL restart process is complete, then a new connection id will be assigned to MySQL.
The query is as follows
mysql> select version();
The following is the output
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id: 8
Current database: sample
+-----------+
| version() |
+-----------+
| 8.0.12    |
+-----------+
1 row in set (0.05 sec)
C++ this Pointer

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.
Let us try the following example to understand the concept of this pointer −
#include <iostream>
 
using namespace std;

class Box {
   public:
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume() {
         return length * breadth * height;
      }
      int compare(Box box) {
         return this->Volume() > box.Volume();
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   if(Box1.compare(Box2)) {
      cout << "Box2 is smaller than Box1" <<endl;
   } else {
      cout << "Box2 is equal to or larger than Box1" <<endl;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1


    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
Program to iterate over a List using Java 8 Lambda

Let us first create a List and add elements −
ArrayList<String>arrayList = new ArrayList<String>();
arrayList.add("100");
arrayList.add("200");
arrayList.add("300");
arrayList.add("400");
arrayList.add("500");
Now, iterate over it with Lambda Expressions −
ArrayList<String>list = arrayList;
System.out.println("Iterating...");
list.stream().forEach(elem -> System.out.println(elem));
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>arrayList = new ArrayList<String>();
      arrayList.add("100");
      arrayList.add("200");
      arrayList.add("300");
      arrayList.add("400");
      arrayList.add("500");
      arrayList.add("600");
      arrayList.add("700");
      arrayList.add("800");
      arrayList.add("900");
      arrayList.add("1000");
      System.out.println("ArrayList...");
      for (String s: arrayList)
         System.out.println(s);
      ArrayList<String>list = arrayList;
      System.out.println("Iterating...");
      list.stream().forEach(elem -> System.out.println(elem));
   }
}
ArrayList...
100
200
300
400
500
600
700
800
900
1000
Iterating...
100
200
300
400
500
600
700
800
900
1000
Sort a List in reverse order in Java

A list can be sorted in reverse order i.e. descending order using the java.util.Collections.sort() method. This method requires two parameters i.e. the list to be sorted and the Collections.reverseOrder() that reverses the order of an element collection using a Comparator.
The ClassCastException is thrown by the Collections.sort() method if there are mutually incomparable elements in the list.
A program that demonstrates this is given as follows:
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) {
      List aList = new ArrayList();
      aList.add("James");
      aList.add("Harry");
      aList.add("Susan");
      aList.add("Emma");
      aList.add("Peter");
      System.out.println("The unsorted ArrayList is: " + aList);
      Collections.sort(aList, Collections.reverseOrder());
      System.out.println("The sorted ArrayList in reverse order is: " + aList);
   }
}
The output of the above program is as follows:
The unsorted ArrayList is: [James, Harry, Susan, Emma, Peter]
The sorted ArrayList in reverse order is: [Susan, Peter, James, Harry, Emma]
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The unsorted ArrayList is printed and then the ArrayList elements are sorted in reverse order using Collections.sort() and Collections.reverseOrder(). Finally, the sorted ArrayList is printed. A code snippet which demonstrates this is as follows:
List aList = new ArrayList();
aList.add("James");
aList.add("Harry");
aList.add("Susan");
aList.add("Emma");
aList.add("Peter");
System.out.println("The unsorted ArrayList is: " + aList);
Collections.sort(aList, Collections.reverseOrder());
System.out.println("The sorted ArrayList in reverse order is: " + aList);
TypeScript - Prototype property

The prototype property allows you to add properties and methods to an object.
function employee(id:number,name:string) { 
   this.id = id 
   this.name = name 
} 
var emp = new employee(123,"Smith") 
employee.prototype.email="smith@abc.com" 
console.log("Employee 's Id: "+emp.id) 
console.log("Employee's name: "+emp.name) 
console.log("Employee's Email ID: "+emp.email)

On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10 
function employee(id, name) { 
   this.id = id; 
   this.name = name; 
} 
var emp = new employee(123, "Smith"); 
employee.prototype.email = "smith@abc.com"; 
console.log("Employee 's Id: " + emp.id); 
console.log("Employee's name: " + emp.name); 
console.log("Employee's Email ID: " + emp.email);

Its output is as follows −
Employee’s Id: 123 
Emaployee’s name: Smith 
Employee’s Email ID: smith@abc.com


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
MYSQL select DISTINCT values from two columns?

To select distinct values in two columns, you can use least() and greatest() function from MySQL.
Let us create a table with two columns −
mysql> create table SelectDistinctTwoColumns
   −> (
   −> StudentId int,
   −> EmployeeId int
   −> );
Query OK, 0 rows affected (0.60 sec)
Now you can insert records in the table. The query to insert records is as follows −
mysql> insert into SelectDistinctTwoColumns values(100,101);
Query OK, 1 row affected (0.39 sec)

mysql> insert into SelectDistinctTwoColumns values(102,103);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SelectDistinctTwoColumns values(104,105);
Query OK, 1 row affected (0.18 sec)

mysql> insert into SelectDistinctTwoColumns values(100,101);
Query OK, 1 row affected (0.14 sec)

mysql> insert into SelectDistinctTwoColumns values(102,103);
Query OK, 1 row affected (0.12 sec)

mysql> insert into SelectDistinctTwoColumns values(106,107);
Query OK, 1 row affected (0.36 sec)

mysql> insert into SelectDistinctTwoColumns values(104,105);
Query OK, 1 row affected (0.17 sec)

mysql> insert into SelectDistinctTwoColumns values(105,104);
Query OK, 1 row affected (0.35 sec)
Display all records from table with the help of select statement. The query is as follows −
mysql> select *from SelectDistinctTwoColumns;
The following is the output −
+-----------+------------+
| StudentId | EmployeeId |
+-----------+------------+
| 100       | 101        |
| 102       | 103        |
| 104       | 105        |
| 100       | 101        |
| 102       | 103        |
| 106       | 107        |
| 104       | 105        |
| 105       | 104        |
+-----------+------------+
8 rows in set (0.00 sec)
Look at the above output. Some duplicate value in both the columns can be seen. Here is the query that selects distinct value from columns −
mysql> select distinct least(StudentId, EmployeeId) as FirstColumn,
   −> greatest(StudentId, EmployeeId) as SecondColumn from SelectDistinctTwoColumns;
The following is the output −
+-------------+--------------+
| FirstColumn | SecondColumn |
+-------------+--------------+
|         100 |          101 |
|         102 |          103 |
|         104 |          105 |
|         106 |          107 |
+-------------+--------------+
4 rows in set (0.00 sec)
Convert number to characters in JavaScript

Suppose we have a login system where users are required to provide a unique userID to uniquely identify them. And for obvious security reasons, we want to obfuscate the userID so that it is fairly hard to guess the number.
Basically, we are required to write two functions.
encode(),
encode(),
decode()
decode()
The first function should convert our number input into a base 26 alphabet mapping. And the second function should convert the alphabet mapping back into the original number.
Although this isn't very practical as most of the Hashing algorithms do not provide to and fro conversions, but for the purpose of this question, we are not considering that.
For example − If the number is 31, then,
encode(31) = 'ea'
and, decode('ea') = 31
The code for this will be −
const num = 31;
const encode = num => {
   let res = '';
   const legend = 'zabcdefghijklmnopqrstuvwxy';
   while(num){
      const rem = num % (legend.length);
      res += legend[rem];
      num = (Math.floor(num / legend.length));
   };
   return res;
};
const decode = str => {
   let num = 0;
   const legend = 'zabcdefghijklmnopqrstuvwxy';
   for(let i = 0; i < str.length; i++){
      const ind = legend.indexOf(str[i]);
      num += (ind * Math.pow(legend.length, i));
   };
   return num;
}
console.log(encode(num));
console.log(decode('ea'));
And the output in the console will be −
ea
31
Model View Controller Pattern

Model View Controller is the most commonly used design pattern. Developers find it easy to implement this design pattern.
Following is a basic architecture of the Model View Controller −
Let us now see how the structure works.
It consists of pure application logic, which interacts with the database. It includes all the information to represent data to the end user.
View represents the HTML files, which interact with the end user. It represents the model’s data to user.
It acts as an intermediary between view and model. It listens to the events triggered by view and queries model for the same.
Let us consider a basic object called “Person” and create an MVC design pattern.
Model.py
import json

class Person(object):
   def __init__(self, first_name = None, last_name = None):
      self.first_name = first_name
      self.last_name = last_name
   #returns Person name, ex: John Doe
   def name(self):
      return ("%s %s" % (self.first_name,self.last_name))
		
   @classmethod
   #returns all people inside db.txt as list of Person objects
   def getAll(self):
      database = open('db.txt', 'r')
      result = []
      json_list = json.loads(database.read())
      for item in json_list:
         item = json.loads(item)
         person = Person(item['first_name'], item['last_name'])
         result.append(person)
      return result
It calls for a method, which fetches all the records of the Person table in database. The records are presented in JSON format.
It displays all the records fetched within the model. View never interacts with model; controller does this work (communicating with model and view).
from model import Person
def showAllView(list):
   print 'In our db we have %i users. Here they are:' % len(list)
   for item in list:
      print item.name()
def startView():
   print 'MVC - the simplest example'
   print 'Do you want to see everyone in my db?[y/n]'
def endView():
   print 'Goodbye!'
Controller interacts with model through the getAll() method which fetches all the records displayed to the end user.
from model import Person
import view

def showAll():
   #gets list of all Person objects
   people_in_db = Person.getAll()
   #calls view
   return view.showAllView(people_in_db)

def start():
   view.startView()
   input = raw_input()
   if input == 'y':
      return showAll()
   else:
      return view.endView()

if __name__ == "__main__":
   #running controller function
   start()

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Finding Natural Logarithm of Given Number in Golang - GeeksforGeeks

01 Apr, 2020
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You are allowed to find the natural logarithm of the specified number with the help of Log() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access Log() function.
Syntax:
func Log(a float64) float64
If you pass +Inf in this function, then this function will return +Inf.
If you pass 0 in this function, then this function will return -Inf.
If the value of a<0, then this function will return NaN.
If you pass NaN in this function, then this function will return NaN.
Example 1:
// Golang program to illustrate how to find the// natural logarithm of the given number  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Finding natural logarithm    // of the given number    // Using Log() function    res_1 := math.Log(0)    res_2 := math.Log(1)    res_3 := math.Log(math.Inf(1))    res_4 := math.Log(math.NaN())    res_5 := math.Log(6)      // Displaying the result    fmt.Printf("Result 1: %.1f", res_1)    fmt.Printf("\nResult 2: %.1f", res_2)    fmt.Printf("\nResult 3: %.1f", res_3)    fmt.Printf("\nResult 4: %.1f", res_4)    fmt.Printf("\nResult 5: %.1f", res_5)  }
Output:
Result 1: -Inf
Result 2: 0.0
Result 3: +Inf
Result 4: NaN
Result 5: 1.8

Example 2:
// Golang program to illustrate how to find the// natural logarithm of the given number  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Finding natural logarithm     // of the given number    // Using Log() function    nvalue_1 := math.Log(4)    nvalue_2 := math.Log(8)    res := nvalue_1 + nvalue_2    fmt.Printf("%.5f + %.5f = %.5f",            nvalue_1, nvalue_2, res)  }
Output:
1.38629 + 2.07944 = 3.46574
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Anonymous function in Go Language
time.Parse() Function in Golang With Examples
Rune in Golang
Structures in Golang
Strings in Golang
Default value of StringBuilder in C#

Use the default operator to get the default value of StringBuilder.
StringBuilder str = default(StringBuilder);
Above, we have used the default keywords to get the default value.
Let us see the complete code −
 Live Demo
using System;
using System.Text;

public class Demo {
   public static void Main() {
      StringBuilder str = default(StringBuilder);
      Console.WriteLine("Default for StringBuilder = "+str);
   }
}
Default for StringBuilder =
The following is the output. It shows a blank space i.e. Null.
Default for StringBuilder = Null
How we can find all the triggers associated with a particular MySQL table?

We can find all the triggers associated with a particular table with the help of the following query −
mysql> Select * from INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA = 'query'AND EVENT_OBJECT_TABLE = 'Student_info'\G
*************************** 1. row ***************************

           TRIGGER_CATALOG: def
            TRIGGER_SCHEMA: query
              TRIGGER_NAME: studentinfo_after_delete
        EVENT_MANIPULATION: DELETE
      EVENT_OBJECT_CATALOG: def
       EVENT_OBJECT_SCHEMA: query
        EVENT_OBJECT_TABLE: student_info
              ACTION_ORDER: 1
          ACTION_CONDITION: NULL
          ACTION_STATEMENT: 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
        ACTION_ORIENTATION: ROW
             ACTION_TIMING: AFTER
ACTION_REFERENCE_OLD_TABLE: NULL
ACTION_REFERENCE_NEW_TABLE: NULL
  ACTION_REFERENCE_OLD_ROW: OLD
  ACTION_REFERENCE_NEW_ROW: NEW
                   CREATED: 2017-11-21 14:19:34.91
                  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
                   DEFINER: root@localhost
      CHARACTER_SET_CLIENT: cp850
      COLLATION_CONNECTION: cp850_general_ci
        DATABASE_COLLATION: latin1_swedish_ci

1 row in set (0.00 sec)
The above result set is showing the list of triggers on the ‘student_info’ table in the database named ‘query’.
What is the difference between anonymous and inline functions in JavaScript?

Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. This is how JavaScript anonymous functions can be used −
var myfunc = function() {
   alert(‘This is anonymous');
}
Another example can be the following −
setTimeout(function() {
   alert('Demo');
}, 3000);
An inline function is a javascript function, which is assigned to a variable created at runtime. You can difference Inline Functions easily with Anonymous since an inline function is assigned to a variable and can be easily reused.This is how JavaScript inline functions can be used −
var myfunc = function() {
   alert ('inline')
};
$('a').click(myfunc);