code-rag-bench/online-tutorials huggingface dataset:
Kubernetes - Deployments

Deployments are upgraded and higher version of replication controller. They manage the deployment of replica sets which is also an upgraded version of the replication controller. They have the capability to update the replica set and are also capable of rolling back to the previous version.
They provide many updated features of matchLabels and selectors. We have got a new controller in the Kubernetes master called the deployment controller which makes it happen. It has the capability to change the deployment midway.
Updating − The user can update the ongoing deployment before it is completed. In this, the existing deployment will be settled and new deployment will be created.
Deleting − The user can pause/cancel the deployment by deleting it before it is completed. Recreating the same deployment will resume it.
Rollback − We can roll back the deployment or the deployment in progress. The user can create or update the deployment by using DeploymentSpec.PodTemplateSpec = oldRC.PodTemplateSpec.
Deployment strategies help in defining how the new RC should replace the existing RC.
Recreate − This feature will kill all the existing RC and then bring up the new ones. This results in quick deployment however it will result in downtime when the old pods are down and the new pods have not come up.
Rolling Update − This feature gradually brings down the old RC and brings up the new one. This results in slow deployment, however there is no deployment. At all times, few old pods and few new pods are available in this process.
The configuration file of Deployment looks like this.
apiVersion: extensions/v1beta1 --------------------->1
kind: Deployment --------------------------> 2
metadata:
   name: Tomcat-ReplicaSet
spec:
   replicas: 3
   template:
      metadata:
         lables:
            app: Tomcat-ReplicaSet
            tier: Backend
   spec:
      containers:
         - name: Tomcatimage:
            tomcat: 8.0
            ports:
               - containerPort: 7474

In the above code, the only thing which is different from the replica set is we have defined the kind as deployment.
$ kubectl create –f Deployment.yaml -–record
deployment "Deployment" created Successfully.

$ kubectl get deployments
NAME           DESIRED     CURRENT     UP-TO-DATE     AVILABLE    AGE
Deployment        3           3           3              3        20s

$ kubectl rollout status deployment/Deployment

$ kubectl set image deployment/Deployment tomcat=tomcat:6.0

$ kubectl rollout undo deployment/Deployment –to-revision=2


    41 Lectures 
     5 hours 

 AR Shankar

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    18 Lectures 
     1.5 hours 

 Nigel Poulton

    25 Lectures 
     1.5 hours 

 Pranjal Srivastava

    18 Lectures 
     1 hours 

 Pranjal Srivastava

    26 Lectures 
     1.5 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Java Examples - Display image using Applet

How to display image using Applet?
Following example demonstrates how to display image using getImage() method. It also uses addImage() method of MediaTracker class.
import java.applet.*; 
import java.awt.*;

public class appletImage extends Applet { 
   Image img;
   MediaTracker tr;
   public void paint(Graphics g) {
      tr = new MediaTracker(this);
      img = getImage(getCodeBase(), "demoimg.gif");
      tr.addImage(img,0);
      g.drawImage(img, 0, 0, this);
   } 
}
The above code sample will produce the following result in a java enabled web browser.
View in Browser. 

 Print
 Add Notes
 Bookmark this page
Python | Numpy matrix.sum() - GeeksforGeeks

20 May, 2019
With the help of matrix.sum() method, we are able to find the sum of values in a matrix by using the same method.
Syntax : matrix.sum()Return : Return sum of values in a matrix
Example #1 :In this example we are able to find the sum of values in a matrix by using matrix.sum() method.
# import the important module in pythonimport numpy as np             # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]')             # applying matrix.sum() methodgeek = gfg.sum()   print(geek)
20

Example #2 :
# import the important module in pythonimport numpy as np             # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')             # applying matrix.sum() methodgeek = gfg.sum(axis = 1)   print(geek)
[[14]
 [16]
 [15]]

Python numpy-Matrix Function
Python-numpy
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?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Using more than one CSS classes for an element in HTML

To add more than one CSS classes, you need to use the class attribute in HTML.
You can try to run the following code to learn how to implement more than one CSS classes for an element in HTML −
<!DOCTYPE html>
<html>
   <head>
      <style>
         h2.myClass1 {
            background-color: black
         }
         .myClass2 {
            color: red;
         }
      </style>
   </head>
   <body>
      <h2 class = "myClass1 myClass2">Tutorialspoint</h2>
      <h3>Simply Easy Learning</h3>
   </body>
</html>
Redis - Client Connection

Redis accepts clients’ connections on the configured listening TCP port and on the Unix socket, if enabled. When a new client connection is accepted, the following operations are performed −
The client socket is put in non-blocking state since Redis uses multiplexing and non-blocking I/O.
The client socket is put in non-blocking state since Redis uses multiplexing and non-blocking I/O.
The TCP_NODELAY option is set in order to ensure that we don't have delays in our connection.
The TCP_NODELAY option is set in order to ensure that we don't have delays in our connection.
A readable file event is created so that Redis is able to collect the client queries as soon as new data is available to be read on the socket.
A readable file event is created so that Redis is able to collect the client queries as soon as new data is available to be read on the socket.
In Redis config (redis.conf), there is a property called maxclients, which describes the maximum number of clients that can connect to Redis.
Following is the basic syntax of command.
config get maxclients  

1) "maxclients" 
2) "10000" 

By default, this property is set to 10000 (depending upon the maximum number of file descriptors limit of OS), although you can change this property.
In the following example, we have set the maximum number of clients to 100000, while starting the server.
redis-server --maxclients 100000 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Program to check if a string contains any special character in Python

When it is required to check if a string contains a specific character or not, a method named ‘check_string’ is defined that uses regular expression and the ‘compile’ method to check if the string has a special character or not. Outside the method, a string is defined, and the method is called by passing this string as a parameter.
Below is a demonstration of the same
import re

def check_string(my_string):

   regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
   if(regex.search(my_string) == None):
      print("String contains special characters.")
   else:
      print("String does not contain any special character.")

my_string = "PythonInterpreter"
print("The string is :")
print(my_string)
check_string(my_string)
The string is :
pythonInterpreter
String contains special characters.
The required packages are imported.
The required packages are imported.
A method named ‘check_string’ is defined that takes a string as a parameter.
A method named ‘check_string’ is defined that takes a string as a parameter.
It uses the ‘compile’ method to see if a special character is present in the string or not.
It uses the ‘compile’ method to see if a special character is present in the string or not.
Outside the method, a string is defined, and is displayed on the console.
Outside the method, a string is defined, and is displayed on the console.
It is passed as a parameter to the function.
It is passed as a parameter to the function.
The output is displayed on the console.
The output is displayed on the console.
Get the minimum and maximum value from a VARCHAR column and display the result in separate MySQL columns?

Let us first create a table −
mysql> create table DemoTable
(
   Value varchar(100)
);
Query OK, 0 rows affected (0.75 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('190');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('230');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('120');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('189');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
|   190 |
|   230 |
|   120 |
|   189 |
+-------+
4 rows in set (0.00 sec)
Following is the query to get the minimum and maximum value from a VARCHAR column and display the result in separate MySQL columns −
mysql> select min(cast(Value AS SIGNED)) AS Min,
max(cast(Value AS SIGNED)) AS Max
from DemoTable;
This will produce the following output −
+------+------+
| Min  | Max  |
+------+------+
|  120 | 230  |
+------+------+
1 row in set (0.03 sec)
Auxiliary Space with Recursive Functions - GeeksforGeeks

28 Feb, 2022
Prerequisite: RecursionMemory used by a program is sometimes as important as running time, particularly in constrained environments such as mobile devices. For example if we need to create an array of size n, it will require O(n) space. If we need a two-dimensional array of size n x n , it will require O(n2). Stack space in recursive calls counts too as extra space required by a program. For example :  
CPP
Java
Python3
C#
Javascript
int sum(int sum){   if (n <= 0)       return 0;   return n + sum(n-1);}
static int sum(int sum){   if (n <= 0)       return 0;   return n + sum(n - 1);} // This code is contributed by Pratham76
def sum(sum):    if (n <= 0):        return 0;    return n + sum(n - 1);  # This code is contributed by Rajput-Ji
static int sum(int sum){   if (n <= 0)       return 0;   return n + sum(n - 1);} // This code is contributed by rutvik_56
<script> function sum(sum){   if (n <= 0)       return 0;   return n + sum(n - 1);} </script>
In the above example function, each call adds a new level to the stack.  
     Sum(5)
    ->sum(4)
            ->sum(3)
            ->sum(2)
                ->sum(1)
                       ->sum(0)
Each of these calls is added to the call stack and takes up actual memory. So code like this would take O(n) time and O(n) auxiliary space. However, just because you have n calls total doesn’t mean it takes O(n) space. Consider the below functions, which adds adjacent elements between 0 and n : Example:  
CPP
// A non-recursive code that makes n calls// but takes O(1) extra space.int pairSumSequence(int n){    int sum = 0;    for (int i=0; i<n; i++)        sum += pairSum(i, i+1);    return sum;} int pairSum(int a, int b){    return a + b ;}
In this example there will be roughly O(n) calls to pairSum. However, those calls do not exist simultaneously on the call stack, so we need only O(1) space. This article is contributed by Ranju Kumari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
pratham76
rutvik_56
sanjoy_62
Rajput-Ji
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Proof that Dominant Set of a Graph is NP-Complete
Proof that Independent Set in Graph theory is NP Complete
3-coloring is NP Complete
Proof that Hamiltonian Cycle is NP-Complete
Complexity analysis of various operations of Binary Min Heap
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Difference between Deterministic and Non-deterministic Algorithms
Applications of Hashing
Tryit Editor v3.7

Tryit: HTML comment inside a paragraph
Tryit Editor v3.7

Tryit: HTML bookmarks
Adding two columns to existing PySpark DataFrame using withColumn - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to add two columns to the existing Pyspark Dataframe using WithColumns. 
WithColumns is used to change the value, convert the datatype of an existing column, create a new column, and many more.
Syntax: df.withColumn(colName, col)
Returns: A new :class:`DataFrame` by adding a column or replacing the existing column that has the same name. 
Example 1: Creating Dataframe and then add two columns.
Here we are going to create a dataframe from a list of the given dataset.
Python3
# Create a spark sessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('SparkExamples').getOrCreate()  # Create a spark dataframecolumns = ["Name", "Course_Name",           "Months",           "Course_Fees", "Discount",           "Start_Date", "Payment_Done"]data = [    ("Amit Pathak", "Python", 3, 10000, 1000,     "02-07-2021", True),    ("Shikhar Mishra", "Soft skills", 2,     8000, 800, "07-10-2021", False),    ("Shivani Suvarna", "Accounting", 6,     15000, 1500, "20-08-2021", True),    ("Pooja Jain", "Data Science", 12,     60000, 900, "02-12-2021", False),]  df = spark.createDataFrame(data).toDF(*columns)  # View the dataframedf.show()
Output:
Now Add the columns:
Here, we create two-column based on the existing columns.
Python3
new_df = df.withColumn('After_discount',                       df.Course_Fees - df.Discount).withColumn('Before_discount',                                                                df.Course_Fees)new_df.show()
Output:
Example 2: Creating Dataframe from csv and then add the columns.
Here we will use the cricket_data_set_odi.csv file as a dataset and create dataframe from this file.
Creating Dataframe for demonstration:
Python3
# import pandas to read json fileimport pandas as pd  # importing moduleimport pyspark  # importing sparksession from pyspark.sql# modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()    # create Dataframedf = spark.read.option("header",True).csv("Cricket_data_set_odi.csv")  # Display Schemadf.printSchema()  # Show Dataframedf.show()
Output:
Then, Adding the columns in an existing Dataframe:
Python3
new_df = df.withColumn(    'Hundred_run', df.Hundreds*100).withColumn(    'Avg_run', df.Runs / df.Matches)  new_df.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Intersect Method in C#

Use the Intesect method to get the common elements −
Create lists −
var list1 = new List{99, 87};
var list2 = new List{56, 87, 45, 99};
Now, use the Intersect() method to get the common elements from the above list −
list1.Intersect(list2);
Here is the complete code −
 Live Demo
using System.Collections.Generic;
using System.Linq;
using System;
public class Demo {
   public static void Main() {
   
      // two lists
      var list1 = new List<int>{99, 87};
      var list2 = new List<int>{56, 87, 45, 99};

      // common values
      var res = list1.Intersect(list2);
      foreach(int i in res) {
         Console.WriteLine(i);
      }
   }
}
99
87
setToolTip method in PyQt5

26 Mar, 2020
setToolTip() method is used to setting up a tooltip of a widget in PyqT5 application.
A tooltip is a hint in a desktop application (graphical user interface). Tooltips frequently appear when mouse hover over a widget without clicking it. Sometimes, when mouse arrow is held on the button it shows some information that information is a tooltip message.
Syntax : widget.setToolTip(Message)
Argument : It takes string as argument.
Below is the implementation of this method.
# importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Tooltip")          # set the geometry        self.setGeometry(0, 0, 300, 300)          # creating a button widget        self.widget = QPushButton('Widget', self)          # setting up the tooltip        self.widget.setToolTip("This is a button widget !")                  # show all the widgets        self.show()      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – QDateEdit

21 Jun, 2022
QDateEdit is the class that provide the date information, allowing user to input the date. It allows the user to edit dates by using the keyboard or the arrow keys to increase and decrease date. It is the widget majorly used for getting input dates. Below is how the date edit widget looks like  Example : A window having a QDateEdit and user can enter any date in it and when user press enter after changing the date, the entered date will get displayed in the label Below is the implementation 
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 500, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QDateEdit widget        date = QDateEdit(self)         # setting geometry of the date edit        date.setGeometry(100, 100, 150, 40)         # creating a label        label = QLabel("GeeksforGeeks", self)         # setting geometry        label.setGeometry(100, 150, 200, 60)         # making label multiline        label.setWordWrap(True)         # adding action to the date when enter key is pressed        date.editingFinished.connect(lambda: date_method())         # method called by date edit        def date_method():             # getting the date            value = date.date()             # setting text to the label            label.setText("Selected Date : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
surinderdawra388
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Remove double quotes from dictionary keys

03 Sep, 2021
Given dictionary with string keys, remove double quotes from it.
Input : test_dict = {‘”Geeks”‘ : 3, ‘”g”eeks’ : 9} Output : {‘Geeks’: 3, ‘geeks’: 9} Explanation : Double quotes removed from keys.
Input : test_dict = {‘”Geeks”‘ : 3} Output : {‘Geeks’: 3} Explanation : Double quotes removed from keys.  
Method #1 :  Using dictionary comprehension + replace()
The combination of above functionalities can be used to solve this problem. In this, we perform removal of double quotes using replace() with empty string. The dictionary comprehension is used for remaking dictionary.
Python3
# Python3 code to demonstrate working of# Remove double quotes from dictionary keys# Using dictionary comprehension + replace() # initializing dictionarytest_dict = {'"Geeks"' : 3, '"is" for' : 5, '"g"eeks' : 9} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # dictionary comprehension to make double quotes free# dictionaryres = {key.replace('"', ''):val for key, val in test_dict.items()}     # printing resultprint("The dictionary after removal of double quotes : " + str(res))
The original dictionary is : {'"Geeks"': 3, '"is" for': 5, '"g"eeks': 9}
The dictionary after removal of double quotes : {'Geeks': 3, 'is for': 5, 'geeks': 9}
Method #2 : Using re.sub() + dictionary comprehension
The combination of above functions is also an alternative to solve this task. In this, we employ regex to solve the problem. 
Python3
# Python3 code to demonstrate working of# Remove double quotes from dictionary keys# Using re.sub() + dictionary comprehensionimport re # initializing dictionarytest_dict = {'"Geeks"' : 3, '"is" for' : 5, '"g"eeks' : 9} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # regex making replacement of double quotes with empty stringres = {re.sub(r'"', '', key): val for key, val in test_dict.items()}     # printing resultprint("The dictionary after removal of double quotes : " + str(res))
The original dictionary is : {'"Geeks"': 3, '"is" for': 5, '"g"eeks': 9}
The dictionary after removal of double quotes : {'Geeks': 3, 'is for': 5, 'geeks': 9}
gabaa406
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
groff Command in Linux with Examples

01 Sep, 2020
In Linux/UNIX, Groff stands for GNU troff. Groff is basically used to create man pages. But its functionality is not limited to creating man pages, rather it acts as a formatting and typesetting engine. It acts as a compiler for the input supplied to it and it creates a formatted document as its output. 
Syntax: 
groff [-abcegijklpstzCEGNRSUVXZ] [-d cs] [-D arg] [-f fam] [-F dir] [-I dir] [-K arg] [-L arg] [-m name] [-M dir] [-n num] [-o list] [-P arg] [-r cn] [-T dev] [-w name] [-W name] [file ...]
groff -h | --help
groff -v | --version [option ...]


Note: To save the file press CTRL+D after writing the required data to the file. 
1. Using the simple groff command
$ groff
hello world

2. groff to format a html file. 
$ groff -Thtml
hello, world!

Save the file by CTRL+D after writing the necessary input. 
3. groff with piped output.  To pipe the output of groff command use the following command syntax
$ groff -Thtml > o.html
My first webpage

 
4. groff with .sp command. Invokes a specified number of spaces before the required line. 
$ groff > output
Hello world
.sp 10
This line will occur after 10 spaces.

5. groff with .br command. Used to invoke line break in the document. 
$groff >> output
Hi
.br
Welcome to GeeksforGeeks

6. groff with .ls command. Used to specify the spacing between two lines in the document. 
$groff > output
.ls 2
hello world
.br
welcome to gfg

7. groff with .bp command. Used to invoke page break within the document. 
$groff > output
hi
.bp
welcome to gfg

 
8. groff with .ce command. This command is used to position particular lines at the center of the page within the document. 
$ groff > output
.ce 1
This line is pushed towards the center of the document
hello geeks!

9. groff with .in command. This command is used to maintain the indentation of the content in the document. 
$ groff > output
hi
.br
.in 5
welcome to gfg

10. groff with .ti command. This command is basically a combination of .ce and .br . It can be used to insert a line break and center the immediate next line to ‘n’ steps where n is the argument passed to .ti command. 
groff > output
hello
.ti 5
welcome to geeksforgeeks!!!!

11. groff with .po command. This command is used to set the page offset ie space between left edge of the document paper and left margin in the document. 
$ groff > output
.po 10
hi
.br
welcome to gfg

12. groff with.ps command. This command is used to set the font size of the text. It can be preceded with – to decrease the font size. To increase the font size no explicit symbol is required before the command. 
groff > output
hi
.br
.ps 25
welcome to my page

groff is mainly used to format documents where groff along with predefined commands produces formatted output on plain text.
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Setup Apache Web Server On Any Android Device?

10 Nov, 2020
In this article, we will learn how we can set up Apache Web Server On Any Android Device. For doing this we have to install the Termux app available on the play store. Termux is an Android terminal emulator and Linux environment application that works directly with no rooting or setup required.  Termux provides a Linux-like shell to the user where he can do tasks like running commands and executing scripts. Termux provides pkg and apt package manager for installing packages, these package managers are just like apt and other package managers of Linux.
So let’s use one of the package managers provided by Termux to install an Apache web server on your Android device. Here below is the step-by-step guide to setup Termux and Apache on your device. 
Step 1: Download the Termux app from Google Play Store.
Step 2: After the installation is complete, open Termux and type the following commands to update pre-installed packages and to installed apache2 package.
sudo apt update
sudo apt install apache2

Step 3: After installing Apache start the Apache server using the following command to start the Apache server.
apachectl -k start 

Some errors will be thrown after the execution of this command you can safely ignore them.
Now open the browser and visit http://127.0.0.1:8080. The browser will return the following response which confirms that the server is active and the apache2 server is configured on your device.
Step 4 (Optional): If you are on a Wi-Fi network and want to access your Apache server from any device on the same network then use the following commands.
$ apt install vim

This command installs the vim text editor.
$ cd ..
$ vim usr/etc/apache2/httpd.conf

After executing these commands httpd.conf file will open, add ServerName to the httpd.conf here value of ServerName will be your local IP address over the WiFi network, like in case if your IP address is 192.168.1.2 then add the following line to httpd.conf and restart the apache server by using the same command used in step 3 and open the URL http://<your-IP-Address>:8080 like in this case the URL would be http://192.168.1.2:8080.
ServerName 192.168.1.2

Note: Replace 192.168.1.2 with the IP address of your android device.
Step 5: If You want to remove the default page served by Apache then go to the following directory
$ cd usr/share/apache2/default-site/htdocs

android
Android
How To
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to disable Messages when Loading a Package in R ?

17 May, 2021
R console displays many messages and warning upon load of some packages and libraries. These messages display the associated packages’ info, the warnings, the masked objects, which may be sometimes redundant and confusing for the user. Therefore, there are methods in R programming language to silence these notifications and ensure a smooth execution. 
suppressPackageStartupMessages() method in R language can be used to disable messages displayed upon loading a package in R. This method is used to suppress package startup messages. The package should be pre-installed in R, otherwise, a warning is displayed upon function call. It is a variant of the suppressMessages() method. However, it disables only the messages, and not warnings and errors encountered.
Syntax: suppressPackageStartupMessages(expr)
Parameter : 
expr – The expression to be evaluated, which in this case is equivalent to library(THE_PACKAGE_NAME) , in order to ignore the package load warnings.
Return type : TRUE if successful, FALSE otherwise. 
This method should be used after installing the specified package using the install.packages() command. Otherwise, it displays an error in that particular library, due to being unable to locate the package. The below screenshots show the warnings and messages displayed upon a load of package “tibble” in RStudio : 
Program:
R
suppressPackageStartupMessages(library("tibble"))
Output:
Multiple libraries’ messages can also be disabled by using suppressPackageStartupMessages({...}) in the console. 
The library() method in R is used to load a library into the working space. During the load of library, the quietly attribute can be set in order to eliminate the display of package startup messages. The package masking and attaching messages are displayed without any prior notification in case this parameter is enabled. It is a local parameter, with its scope defined only for the package it is defined with. It doesn’t affect the global settings of package installation. No warning and extra messages are displayed. However, the package should be present in the working space, otherwise, an error is returned. This is in contrast to the suppressPackageStartupMessages method because no message confirming package attaching is printed, and in most of the cases, no errors/warnings are printed even in case of any failure.
Syntax:
library (THE_PACKAGE_NAME, quietly = T)
The below screenshots show the warnings and messages displayed upon load of package “dplyr” in RStudio : 
Program:
R
install.packages("dplyr")  library (dplyr, quietly = T)
Output: 
Picked
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | keypress()

13 Feb, 2019
The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.Syntax:To trigger the keypress event for the selected elements:
$(selector).keypress()

To attach a function to the keypress event:
$(selector).keypress(function) 

<html><head><title>Jquery | Keypress() </title><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script></head><script>$(document).keypress(function(event){              alert('You pressed a key');    });</script><body></script></body></html>
Output:Code #2:To detect any specific key event.keyCode and event.which will return an ASCII value of the pressed key, Both are browser specific.Below code is used to check which key is pressed on the page.
<html><head><title>Jquery | Keypress() </title><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script></head><script>$(document).keypress(function(event){          var key = (event.keyCode ? event.keyCode : event.which);    var ch=String.fromCharCode(key)        alert('You pressed key : ' +ch);            });</script><body><br><br><center><h1>Try pressing any printable character from the keyboard </h1></center></body></html>
Output:If any key is pressed then output will be-Code #3Below code is used to check if Enter key is pressed inside a textbox on the page or not.
<html><head><title>Jquery | Keypress() </title><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script></head><body>   <center>         <br><br>    <h1>Press " Enter key " inside the textbox </h1>    <input id="textbox" type="text" size="50" /></center><script type="text/javascript">  $('#textbox').keypress(function(event){          var keycode = (event.keyCode ? event.keyCode : event.which);    if(keycode == '13'){        alert('You pressed  "enter" key in textbox');        }    event.stopPropagation();});  </script></body></html>
Output:When enter key is pressed inside the above textbox then output becomes like below-
Note: The keypress event is not triggered for all keys like non printing characters (e.g. ALT, CTRL, SHIFT, ESC). keydown() method can be used to check these keys.
jQuery-Events
JavaScript
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are storage classes of variables in C++?

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program.
auto
register
static
extern
mutable
In C, The auto storage class specifier lets you explicitly declare a variable with automatic storage. The auto storage class is the default for variables declared inside a block. A variable x that has automatic storage is deleted when the block in which x was declared exits.
You can only apply the auto storage class specifier to names of variables declared in a block or to names of function parameters. However, these names by default have automatic storage. Therefore the storage class specifier auto is usually redundant in a data declaration.
It was initially carried over to C++ for syntactical compatibility only, although later it got its own meaning, automatic type deduction.
In C, the register storage class specifier indicates to the compiler that the object should be stored in a machine register. The register storage class specifier is typically specified for heavily used variables, such as a loop control variable, in the hopes of enhancing performance by minimizing access time. However, the compiler is not required to honor this request. Because of the limited size and number of registers available on most systems, few variables can actually be put in registers.
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The extern storage class specifier lets you declare objects that several source files can use. An extern declaration makes the described variable usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.
The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. You cannot use the mutable specifier with names declared as static or const, or reference members.
class A
{
   public:
   A() : x(4), y(5) { };
   mutable int x;
   int y;
};

int main()
{
   const A var2;
   var2.x = 345;
   // var2.y = 2345;
}

the compiler would not allow the assignment var2.y = 2345 because var2 has been declared as const. The compiler will allow the assignment var2.x = 345 because A::x has been declared as mutable.
C++ Program to Find the peak element of an array using Binary Search approach

In this C++ program, we find out one of the peaks in the array can be found Using binary search approach. This algorithm returns the first peak found as a result with time complexity of the algorithm is O(log(n)).
Begin
   PeakElement() function has ‘arr’ the array of data, start and end index in the argument list.
   Assign the mid of subpart of the array.
   If mid is at the boundary index and value at mid is higher than its neighbor then return mid as peak.
   If the value at mid is greater than both of its neighbors then return mid as peak.
   If the value at the right of mid is greater than mid then send second sub-part of the array into PeakElement() as argument.
   If the value at the left of mid is greater than mid then send first sub-part of the array into PeakElement() as argument.
End
#include<iostream>
using namespace std;
int PeakElement(int a[], int start, int end) {
   int i, mid;
   mid = (end+start+1)/2;
   if((a[mid] > a[mid+1] && mid == start)||(a[mid] > a[mid-1] && mid == end)) {
      return a[mid];
   } else if(a[mid] < a[mid-1] && a[mid] > a[mid+1]) {
      return a[mid];
   } else if(a[mid] <= a[mid+1]) {
      return PeakElement(a, mid+1, end);
   } else if(a[mid] <= a[mid-1]) {
      return PeakElement(a, start,mid-1);
   }
}
int main() {
   int n, i, p;
   cout<<"\nEnter the number of data element: ";
   cin>>n;
   int arr[n];
   for(i = 0; i < n; i++) {
      cout<<"Enter element "<<i+1<<": ";
      cin>>arr[i];
   }
   p = PeakElement(arr, 0, n-1);
   cout<<"\nThe peak element of the given array is: "<<p;
   return 0;
}
Enter the number of data element: 5
Enter element 1: 45
Enter element 2: 26
Enter element 3: 70
Enter element 4: 60
Enter element 5: 15
The peak element of the given array is: 70
Prototype - unescapeHTML() Method

This method strips tags and converts the entity forms of special HTML characters to their normal form.
string.unescapeHTML();

Returns an unescaped HTML trimmed string.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var str = 'x &gt; 10';
            alert("First : " + str.unescapeHTML() );
            
            var str = "<h1>Pride &amp; Prejudice</h1>"
            alert("Second : " + str.unescapeHTML() );
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>
Click the button to see the result.

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
Armstrong Numbers between two integers?

An integer is called an Armstrong number of order n if it's every digit separate out and cubed and summed up then the sum will be same as the number i.e. abcd... = a3 + b3 + c3 + d3 + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example:
153 = 13 + 53 + 33 // 153 is an Armstrong number.
Input: Enter two numbers(intervals):999 9999
Output: Armstrong numbers between 999 and 9999 are: 1634 8208 9474
1634 = 13+63+33+43
= 1+216+27+64
= 1634
The approach implemented below is simple. We traverse through all numbers in the given range. For every number, we first count the number of digits in it. Let the number of digits in the current number be n. Them we find the sum of the cube of all digits. If the sum is equal to I, we print the number.
#include <stdio.h>
#include <math.h>
int main() {
   int low = 100;
   int high = 400;
   printf("The amstrong numbers between %d and %d is \n",low,high);
   for (int i = low+1; i < high; ++i) {
      int x = i;
      int n = 0;
      while (x != 0) {
         x /= 10;
         ++n;
      }
      int pow_sum = 0;
      x = i;
      while (x != 0) {
         int digit = x % 10;
         pow_sum += pow(digit, n);
         x /= 10;
      }
      if (pow_sum == i)
         printf("%d ", i);
   }
   printf("\n");
   return 0;
}
Check for null in MongoDB?

We will use the Null type here. Following are the null types with the alias −
Following is the syntax for type 10 i.e. null −
db.yourCollectionName.find({"yourFieldName":{ $type: 10 } });
The above syntax will find only those documents which have null value. Let us first create a collection with documents −
> db.mongoDbEqualDemo.insertOne({"Age":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9121a844af18acdffa3")
}
> db.mongoDbEqualDemo.insertOne({"Age":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9161a844af18acdffa4")
}
> db.mongoDbEqualDemo.insertOne({"Age":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9191a844af18acdffa5")
}
> db.mongoDbEqualDemo.insertOne({"Age":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e91e1a844af18acdffa6")
}
> db.mongoDbEqualDemo.insertOne({});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9261a844af18acdffa7")
}
> db.mongoDbEqualDemo.insertOne({"Age":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e92e1a844af18acdffa8")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.mongoDbEqualDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd7e9121a844af18acdffa3"), "Age" : 34 }
{ "_id" : ObjectId("5cd7e9161a844af18acdffa4"), "Age" : "" }
{ "_id" : ObjectId("5cd7e9191a844af18acdffa5"), "Age" : null }
{ "_id" : ObjectId("5cd7e91e1a844af18acdffa6"), "Age" : 56 }
{ "_id" : ObjectId("5cd7e9261a844af18acdffa7") }
{ "_id" : ObjectId("5cd7e92e1a844af18acdffa8"), "Age" : null }
Following is the query to check for equal to null values only −
> db.mongoDbEqualDemo.find({"Age":{ $type: 10 } });
This will produce the following output −
{ "_id" : ObjectId("5cd7e9191a844af18acdffa5"), "Age" : null }
{ "_id" : ObjectId("5cd7e92e1a844af18acdffa8"), "Age" : null }
How to remove Lua table entry by its key?

Let’s consider an example where we would like to remove a Lua table entry. The table itself behaves like a hashmap, where it has several key value pairs, and we would like to remove an entry from that table on the basis of the key.
Lua library does provide a function that we can use for our specific case. The function is table.remove() and it takes two arguments, the first argument is the name of the table and the second argument is the key that we want to remove.
Consider the example shown below −
 Live Demo
local mapone = { [1] = 10, [2] = 20, [3] = 30 }
for _,v in pairs(mapone) do print(v) end
table.remove(mapone,2)
for _,v in pairs(mapone) do print(v) end
In the above example, we had a table named mapone which behaves like a hashmap, with different key-value pairs, and we wanted to remove an entry from it by providing a key, we did just that when we called the table.remove() function.
10
20
30
10
30
It should be noted that the first three numbers are the values of the keys that were present in the map, and the last two numbers are values of the keys that remain in the map once we removed the key = 2.
It should also be noted that the table.remove() function only works in case we have integer keys.
In order to make it work on keys that are not integers, we would have to create our own function.
Consider the example shown below −
 Live Demo
local map = { foo = 1, bar = 2 , car = 3}
function table.removekey(table, key)
   local element = table[key]
   table[key] = nil
   return element
end
for i,v in pairs(map) do print(i,v) end
table.removekey(map,'bar')
for i,v in pairs(map) do print(i,v) end
foo 1
bar 2
car 3
foo 1
car 3
How to get current date/time in seconds in JavaScript?

To convert time in seconds, firstly get the current time. Then, multiply the hours to 3600 and minutes to 60; rest you can see below −
(hours*3600) + (min*60) + sec
You can try to run the following code to get the current time in seconds −
Live Demo
<html>
   <head>
      <title>JavaScript Get Seconds</title>
   </head>
   <body>
      <script>
         var dt = new Date();
         var sec = dt.getSeconds();
         document.write("Seconds: " + sec);
         var min = dt.getMinutes();
         document.write("<br>Minutes: " + min);
         var hrs = dt.getHours();
         document.write("<br>Hours: " + hrs);
         var total_seconds = (hrs*3600) + (min*60) + sec;
         document.write("<br>Total seconds: " + total_seconds) ;
      </script>
   </body>
</html>
Seconds: 35
Minutes: 37
Hours: 9
Total seconds: 34655
Creating and Configuring Wi-Fi Hotspot in Ubuntu - GeeksforGeeks

16 Feb, 2019
Below are some steps to create a Wi-Fi hotspot in Ubuntu:
Step 1) Make sure that the wireless device is turned ON in your system or not. If not, then turned it ON.
Step 2) Go to Settings and click the Wi-Fi tab in the top left pane.
Step 3) In the top right corner you can see a tribar icon of the Settings app. Click on it and choose the second option i.e Turn ON Wi-Fi Hotspot.
Step 4) It will give a warning. You have to just click Turn On.
Step 5) Now you can see the Name and password of the hotspot.
Step 6) To check for the active hotspot you can click on the quick settings menu as shown below:
Configuring Wi-Fi Hotspot in Ubuntu: Many have a problem in changing Wi-fi Hotspot password in Ubuntu as it is not easy as in Windows OS. When you turn on the hotspot in Ubuntu you are able to see name and password but there is no option to change the password. There are two ways for changing the Hotspot password. One is through the terminal and the other using editor.
Using Commands on Terminal: Open the terminal and type the below command. Replace mypassword with your desired password. Make sure that the password has at least 8 characters.$ nmcli connection modify Hotspot 802-11-wireless-security.key-mgmt wpa-psk 802-11-wireless-security.psk mypassword
$ nmcli connection modify Hotspot 802-11-wireless-security.key-mgmt wpa-psk 802-11-wireless-security.psk mypassword
Using Editor:Open the terminal and type the below command. It will open a tab as shown in the screenshot.$ nm-connection-editor
Network Connections window will open which looks like:Double click on the Hotspot which is shown under Wi-Fi category. Another window will open.Go to Wi-Fi security and change the password and press save button.
Open the terminal and type the below command. It will open a tab as shown in the screenshot.$ nm-connection-editor
Network Connections window will open which looks like:Double click on the Hotspot which is shown under Wi-Fi category. Another window will open.Go to Wi-Fi security and change the password and press save button.
Open the terminal and type the below command. It will open a tab as shown in the screenshot.$ nm-connection-editor

$ nm-connection-editor

Network Connections window will open which looks like:
Double click on the Hotspot which is shown under Wi-Fi category. Another window will open.
Go to Wi-Fi security and change the password and press save button.
GBlog
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Working with csv files in Python
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C