code-rag-bench/online-tutorials huggingface dataset:
Create empty DataFrame with only column names in R - GeeksforGeeks

05 Apr, 2021
In this article, we are going to create an empty data frame with column names in the R programming language.
The basic syntax for creating a data frame is using data.frame().
Syntax: data.frame(input_data,nrow,ncol)
Parameter:
input_data may be values ot list or vector.
nrow specifies the number of rows
ncol specifies the number of columns.
Steps –
Create an empty dataframe
Define the column names to a variable
Assign that variable to the dataframe.
Display data frame so created
We can assign column names to dataframe by using colnames()
Syntax:
colnames(dataframe_name)
Given below is the implementation using the above approach.
Example 1:
R
# created vector with 5 characterscolumns= c("id","names","address","phone","aadhar no")   # pass this vector length to ncol parameter# and nrow with 0myData = data.frame(matrix(nrow = 0, ncol = length(columns)))   # assign column namescolnames(myData) = columns  # displayprint(myData)
Output:
[1] id        names     address   phone     aadhar no
<0 rows> (or 0-length row.names)
If we specify nrow parameter with morethan 0, it will take NA as that many rows.
Example 2:
R
# created vector with 5 characterscolumns= c("id","names","address","phone","aadhar no")   # pass this vector length to ncol parameter # and nrow with 1myData = data.frame(matrix(nrow=1, ncol = length(columns)))   # assign column namescolnames(myData) = columns  # displayprint(myData)  # pass this vector length to ncol parameter and # nrow with 6myData = data.frame(matrix(nrow=6, ncol = length(columns)))   # assign column namescolnames(myData) = columns  # displayprint(myData)
Output:
  id names address phone aadhar no
1 NA    NA      NA    NA        NA
  id names address phone aadhar no
1 NA    NA      NA    NA        NA
2 NA    NA      NA    NA        NA
3 NA    NA      NA    NA        NA
4 NA    NA      NA    NA        NA
5 NA    NA      NA    NA        NA
6 NA    NA      NA    NA        NA
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Explain the visibility of global variables in imported modules in Python?

Globals in Python are global to a module, not across all modules. (Unlike C, where a global is the same across all implementation files unless you explicitly make it static.). If you need truly global variables from imported modules, you can set those at an attribute of the module where you're importing it.
import module1
module1.a=3
On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:
global_module.py
module1.py:
import global_module
def fun():
    print global_module.var
Other files:
import global_module
import module1
global_module.var = 3
module1.fun()
AWK - Control Flow

Like other programming languages, AWK provides conditional statements to control the flow of a program. This chapter explains AWK's control statements with suitable examples.
It simply tests the condition and performs certain actions depending upon the condition. Given below is the syntax of if statement −
if (condition)
   action

We can also use a pair of curly braces as given below to execute multiple actions −
if (condition) {
   action-1
   action-1
   .
   .
   action-n
}

For instance, the following example checks whether a number is even or not −
[jerry]$ awk 'BEGIN {num = 10; if (num % 2 == 0) printf "%d is even number.\n", num }'
On executing the above code, you get the following result −
10 is even number.

In if-else syntax, we can provide a list of actions to be performed when a condition becomes false.
The syntax of if-else statement is as follows −
if (condition)
   action-1
else
   action-2

In the above syntax, action-1 is performed when the condition evaluates to true and action-2 is performed when the condition evaluates to false. For instance, the following example checks whether a number is even or not −
[jerry]$ awk 'BEGIN {
   num = 11; if (num % 2 == 0) printf "%d is even number.\n", num; 
      else printf "%d is odd number.\n", num 
}'
On executing this code, you get the following result −
11 is odd number.

We can easily create an if-else-if ladder by using multiple if-else statements. The following example demonstrates this −
[jerry]$ awk 'BEGIN {
   a = 30;
   
   if (a==10)
   print "a = 10";
   else if (a == 20)
   print "a = 20";
   else if (a == 30)
   print "a = 30";
}'
On executing this code, you get the following result −
a = 30

 Print
 Add Notes
 Bookmark this page
How to change the Entry Widget Value with a Scale in Tkinter?

Tkinter Entry widget is an input widget that supports only single-line user input. It accepts all the characters in the text field unless or until there are no restrictions set for the input. We can change the value of the Entry widget with the help of the Scale widget. The Scale widget contains a lower value and a threshold that limits the user to adjust the value in a particular range.
To update the value in the Entry widget while updating the value of Scale widget, we have to create a variable that has to be given to both the scale and the entry widget.
#Import the Tkinter Library
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of window
win.geometry("700x350")

#Create an Integer Variable to set the initial value of Scale
var = IntVar(value=10)

#Create an Entry widget
entry = ttk.Entry(win,width= 45,textvariable=var)
scale = Scale(win, from_=10, to=200, width= 20, orient="horizontal", variable=var)

entry.place(relx= .5, rely= .5, anchor= CENTER)
scale.place(relx= .5, rely= .6, anchor = CENTER)

win.mainloop()
Running the above code will display an Entry widget and a Scale which can be used to update the value in the Entry widget.
How to make a 4D plot with Matplotlib using arbitrary data?

To make a 4D plot, we can create x, y, z and c standard data points. Create a new figure or activate an existing figure.
Use figure() method to create a figure or activate an existing figure.
Use figure() method to create a figure or activate an existing figure.
Add a figure as part of a subplot arrangement.
Add a figure as part of a subplot arrangement.
Create x, y, z and c data points using numpy.
Create x, y, z and c data points using numpy.
Create a scatter plot using scatter method.
Create a scatter plot using scatter method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.random.standard_normal(100)
c = np.random.standard_normal(100)
img = ax.scatter(x, y, z, c=c, cmap='YlOrRd', alpha=1)
plt.show()
GATE | GATE CS 2011 | Question 65 - GeeksforGeeks

22 Jul, 2021
Consider the following table of arrival time and burst time for three processes P0, P1 and P2.
Process   Arrival time   Burst Time
P0            0 ms          9 ms
P1            1 ms          4 ms
P2            2 ms          9 ms
The pre-emptive shortest job first scheduling algorithm is used. Scheduling is carried out only at arrival or completion of processes. What is the average waiting time for the three processes?(A) 5.0 ms(B) 4.33 ms(C) 6.33(D) 7.33Answer: (A)Explanation: See Question 4 of https://www.geeksforgeeks.org/operating-systems-set-6/
Watch GeeksforGeeks Video Explanation :
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0017:10 / 39:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=y1BbjvO_xog" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 64
How to Change or Set System Locales in Linux? - GeeksforGeeks

26 Mar, 2021
Locale is basically a set of environmental variables that defines the user’s language, region, and any special variant preferences that the user wants to see in their Linux interface. System libraries and locale-aware applications on the system use these environmental variables.
Locale settings usually consist of at least a language code, a country/region code, time/date format, numbers format setting, currency format setting, Color setting, etc. Here we will see how to set/change or view the system’s locale in Linux.
For viewing the information regarding the currently installed locale use the following command on the terminal:-
$ locale
We will get a list of variables that can be reset to a different value according to our choice later on.
The current status can be seen using the following command:
localectl status
We can also view more information about a specific variable that we saw when we run the locale command, for example, LC_TIME, which stores the time and date format, LC_PAPER which stores the paper size settings, LC_TELEPHONE which stores telephone settings format, etc.
You can get this information by using the following commands:-
$ locale -k LC_TIME
$ locale -k LC_TELEPHONE
$ locale -k LC_PAPER  
 Display a list of all available locales using the following command:-
$ locale -a
We might want to change or set the system local, for that we have to use the update-locale program. The LANG variable allows us to set up the locale for the entire system.
For setting up LANG to en_IN.UTF-8 and removes definitions for LANGUAGE we can use the following command:-
$ sudo update-locale LANG=LANG=en_IN.UTF-8 LANGUAGE
OR
$ sudo localectl set-locale LANG=en_IN.UTF-8
We can find global locale settings in /etc/default/locale on Ubuntu/Debian Linux distros that you can edit for configuring your system locale manually using the following command:-
$  sudo vi /etc/default/locale
We can also change the value of a locale that is preset, by editing the .bashrc profile by using the following command:-
sudo nano ~/.bashrc
We can set a global locale for a single user, by adding the following lines at the end of  the ~/.bash_profile file 
LANG="en_IN.utf8"
export LANG
If you want to get more information about the System locale, update-locale and localectl just view the manual pages using the following command:-
$ man locale
$ man update-locale
$ man localectl
Picked
How To
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 and Setup Spring Boot Project in Eclipse IDE?
How to Install Jupyter Notebook on MacOS?
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
cp command in Linux with examples
Python | Set Background Template in kivy - GeeksforGeeks

10 Feb, 2020
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.
Setting a good background template is a good thing to make your app look more attractive to the user. For inserting a background template in your App some modifications need to be done in the .kv file. Below is the code to set a background template for your app.
# Program to create a background template for the App  # import necessary modules from kivyfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.app import App  # create a background class which inherits the boxlayout classclass Background(BoxLayout):    def __init__(self, **kwargs):        super().__init__(**kwargs)    pass  # Create App class with name of your appclass SampleApp(App):  # return the Window having the background template.    def build(self):        return Background()  # run app in the main functionif __name__ == '__main__':    SampleApp().run()
.kv file
<Background>:    id: main_win    orientation: "vertical"    spacing: 10    space_x: self.size[0]/3        canvas.before:        Color:            rgba: (1, 1, 1, 1)        Rectangle:            source:'back.jfif'            size: root.width, root.height            pos: self.pos    Button:        text: "Click Me"        pos_hint :{'center_x':0.2, 'center_y':0.2}        size_hint: .30, 0        background_color: (0.06, .36, .4, .675)        font_size: 40
Output:
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
JavaScript SyntaxError - Missing ; before statement - GeeksforGeeks

24 Jul, 2020
This JavaScript exception missing ; before statement occurs if there is a semicolon (;) missing in script.
Message:
SyntaxError: Expected ';' (Edge)
SyntaxError: missing ; before statement (Firefox)

Error Type:
SyntaxError

Cause of Error: Somewhere in code, there is a missing semicolon (;). You need to provide it so that JavaScript can parse the source code without any error.
Example 1: In this example, the string is not escaped properly and JavaScript expecting a “;”, so the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        // invalid string        var GFG = 'This is GFG's platform';          document.write(GFG);    </script></body></html>
Output(In console of Edge Browser):
SyntaxError: Expected ';'

Example 2: In this example, the properties of an object is declared with the var declaration, Which is invalid. So the error has occurred, 
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        var GFG = {};        var GFG.prop_1 = 'Val_1';          document.write(JSON.stringify(GFG));    </script></body></html>
Output(In console of Edge Browser): 
SyntaxError: Expected ';'

JavaScript-Errors
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
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
What is the difference between break and continue statements in JavaScript?

The break statement is used to exit a loop early, breaking out of the enclosing curly braces.  The break statement exits out of a loop.  
Let’s see an example of break statement in JavaScript. The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace,
<html>
   <body>
      <script>
         var x = 1;
         document.write("Entering the loop<br /> ");
         while (x < 20) {
            if (x == 5) {
               break;     // breaks out of loop completely
            }
            x = x +1;
            document.write( x + "<br />");
         }

         document.write("Exiting the loop!<br /> ");
      </script>
   </body>
</html>
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise, the control comes out of the loop.
The continue statement breaks over one iteration in the loop. This example illustrates the use of a continue statement with a while loop. Notice how to continue statement is used to skip printing when the index held in variable x reaches 8 −
<html>
   <body>
      <script>
         var x = 1;
         document.write("Entering the loop<br /> ");

         while (x < 10)  {
            x = x+ 1;
            if (x == 8){
               continue;  // skip rest of the loop body
            }
            document.write( x + "<br />");
         }
         document.write("Exiting the loop!<br /> ");
      </script>
   </body>
</html>
WSDL - <types> Element

A web service needs to define its inputs and outputs and how they are mapped into and out of the services. WSDL <types> element takes care of defining the data types that are used by the web service. Types are XML documents, or document parts.
The types element describes all the data types used between the client and the server.
The types element describes all the data types used between the client and the server.
WSDL is not tied exclusively to a specific typing system.
WSDL is not tied exclusively to a specific typing system.
WSDL uses the W3C XML Schema specification as its default choice to define data types.
WSDL uses the W3C XML Schema specification as its default choice to define data types.
If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required.
If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required.
WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services.
WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services.
Here is a piece of code taken from W3C specification. This code depicts how a types element can be used within a WSDL.
<types>
   <schema targetNamespace = "http://example.com/stockquote.xsd"
      xmlns = "http://www.w3.org/2000/10/XMLSchema">
		
      <element name = "TradePriceRequest">
         <complexType>
            <all>
               <element name = "tickerSymbol" type = "string"/>
            </all>
         </complexType>
      </element>
		
      <element name = "TradePrice">
         <complexType>
            <all>
               <element name = "price" type = "float"/>
            </all>
         </complexType>
      </element>
		
   </schema>
</types>
Data types address the problem of identifing the data types and the formats you intend to use with your web services. Type information is shared between the sender and the receiver. The recipients of messages therefore need access to the information you used to encode your data and must understand how to decode the data.
 Print
 Add Notes
 Bookmark this page
Filter the rows – Python Pandas

To filter the rows and fetch specific column value, use the Pandas contains() method. At first, let us import the required library with alias −
import pandas as pd
Read the CSV file using the read_csv(). Our CSV file is on the Desktop −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")

Now, let us filter the rows with specific text −
dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]
Following is the code
import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)

# select rows containing text "Lamborghini"
dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]
print("\nFetching rows with text Lamborghini ...\n",dataFrame)
This will produce the following output −
DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi          95
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai         100
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100

Fetching rows with text Lamborghini ...
           Car       Place   UnitsSold
5  Lamborghini  Chandigarh          80
8  Lamborghini       Delhi         100
verify - Unix, Linux Command

verify [generic Postfix daemon options]


Addresses are verified by injecting probe messages into the
Postfix queue. Probe messages are run through all the routing
and rewriting machinery except for final delivery, and are
discarded rather than being deferred or bounced.


Address verification relies on the answer from the nearest
MTA for the specified address, and will therefore not detect
all undeliverable addresses.


The verify(8) server is designed to run under control
by the Postfix
master server. It maintains an optional persistent database.
To avoid being interrupted by "postfix stop" in the middle
of a database update, the process runs in a separate process
group.


The verify(8) server implements the following requests:




The address verification server can be coerced to store
unlimited amounts of garbage. Limiting the cache size
trades one problem (disk space exhaustion) for another
one (poor response time to client requests).


If the persistent database ever gets corrupted then the world
comes to an end and human intervention is needed. This violates
a basic Postfix principle.




The text below provides only a parameter summary. See
postconf(5) for more details including examples.







smtpd(8), Postfix SMTP server
cleanup(8), enqueue Postfix message
postconf(5), configuration parameters
syslogd(5), system logging



ADDRESS_VERIFICATION_README, address verification howto





Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Python 3 - Number exp() Method

The exp() method returns exponential of x: ex.
Following is the syntax for the exp() method −
import math

math.exp( x )

Note − This function is not accessible directly. Therefore, we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns exponential of x: ex.
The following example shows the usage of exp() method.
#!/usr/bin/python3
import math   # This will import math module

print ("math.exp(-45.17) : ", math.exp(-45.17))
print ("math.exp(100.12) : ", math.exp(100.12))
print ("math.exp(100.72) : ", math.exp(100.72))
print ("math.exp(math.pi) : ", math.exp(math.pi))
When we run the above program, it produces the following result −
math.exp(-45.17) :  2.4150062132629406e-20
math.exp(100.12) :  3.0308436140742566e+43
math.exp(100.72) :  5.522557130248187e+43
math.exp(math.pi) :  23.140692632779267


    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
DateTime.ToFileTimeUtc() Method in C#

The DateTime.ToFileTimeUtc() method in C# is used to convert the value of the current DateTime object to a Windows file time.
Following is the syntax −
public long ToFileTimeUtc ();
Let us now see an example to implement the DateTime.ToFileTimeUtc() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 05, 10, 6, 10, 25);
      Console.WriteLine("Date = {0}", d);
      long res = d.ToFileTimeUtc();
      Console.WriteLine("Windows file time (Utc) = {0}", res);
   }
}
This will produce the following output −
Date = 5/10/2019 6:10:25 AM
Windows file time (Utc) = 132019422250000000
Let us now see another example to implement the DateTime.ToFileTimeUtc() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      long res = d.ToFileTimeUtc();
      Console.WriteLine("Windows file time (Utc) = {0}", res);
   }
}
This will produce the following output −
Date = 10/16/2019 8:25:58 AM
Windows file time (Utc) = 132156879583999032
C/C++ Programming to Count trailing zeroes in factorial of a number?

Counting the number of trailing zeroes in a factorial number is done by counting the number of 2s and 5s in the factors of the number. Because 2*5 gives 10 which is a trailing 0 in the factorial of a number.
Factorial of 7 = 5040, the number of trailing 0’s is 1.
Based on our logic 7! = 2*3*4*5*6*7, it has 3 2s and 1 5s so the number of trailing 0’s is 1.
#include <iostream>
using namespace std;
int main() {
   int n = 45;
   int count = 0;
   for (int i = 5; n / i >= 1; i *= 5)
      count += n / i;
   cout<<"No of trailing 0s in " << n<< "! is " << count;
   return 0;
}
No of trailing 0s in 24! is 10
Socket.IO - Namespaces

Socket.IO allows you to "namespace" your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server.
Namespaces are created on the server side. However, they are joined by clients by sending a request to the server.
The root namespace '/' is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example −
var socket = io();

This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back.
We can create our own custom namespaces. To set up a custom namespace, we can call the 'of' function on the server side −
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
   res.sendFile('E:/test/index.html');});
   
var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
   console.log('someone connected');
   nsp.emit('hi', 'Hello everyone!');
});
http.listen(3000, function(){
   console.log('listening on localhost:3000');
});
Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side.
For example, to connect to the above namespace, use the following HTML −
<!DOCTYPE html>
<html>
   <head><title>Hello world</title></head>
   <script src="/socket.io/socket.io.js"></script>
   <script>
      var socket = io('/my-namespace');
      socket.on('hi',function(data){
         document.body.innerHTML = '';
         document.write(data);
      });
   </script>
   <body></body>
 </html>
Every time someone connects to this namespace, they will receive a 'hi' event displaying the message "Hello everyone!".

    35 Lectures 
     2.5 hours 

 Nicholas Lever
 Print
 Add Notes
 Bookmark this page
Data Structures | Binary Search Trees | Question 1

02 Feb, 2013
What is the worst case time complexity for search, insert and delete operations in a general Binary Search Tree?(A) O(n) for all(B) O(Logn) for all(C) O(Logn) for search and insert, and O(n) for delete(D) O(Logn) for search, and O(n) for insert and deleteAnswer: (A)Explanation: In skewed Binary Search Tree (BST), all three operations can take O(n). See the following example BST and operations.
          10
        /
       20
      /
     30
    / 
   40

Search 40. 
Delete 40
Insert 50.

Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bootstrap .form-control-static class

Use the class .form-control-static on a <p> when you need to place plain text next to a form label within a horizontal form.
You can try to run the following code to implement the .form-control-static class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form class = "form-horizontal" role = "form">
         <div class = "form-group">
            <label class = "col-sm-2 control-label">Email:</label>
            <div class = "col-sm-10">
               <p class = "form-control-static">amit@example.com</p>
            </div>
         </div>
         <div class = "form-group">
            <label for = "inputPassword" class = "col-sm-2 control-label">Password:</label>
            <div class = "col-sm-10">
               <input type = "password" class = "form-control" id = "inputPassword" placeholder = "Password">
            </div>
         </div>
      </form>
   </body>
</html>
What are unreachable catch blocks in Java?

A block of statements to which the control can never reach under any case can be called as unreachable blocks. Unreachable blocks are not supported by Java. The catch block mentioned with the reference of Exception class should and must be always last catch block because Exception is the superclass of all exceptions. When we are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e subclasses of Exception must come first and superclasses later. If we keep superclasses first and subclasses later, the compiler will throw an unreachable catch block error.
try {
   // statements
} catch(Exception e) {
   System.out.println(e);
} catch(NumberFormatException nfe) { //unreachable block. Not supported by Java, leads to an error.
   System.out.println(nfe);
}
A catch clause is considered reachable by the compiler if both of the following conditions are true
A checked exception that is thrown in the try block is assignable to the parameter of C.
There is no previous catch clause whose parameter type is equal to or a supertype of the parameter type of C
A catch clause is considered reachable by the compiler can be unreachable if both of the following conditions are true
The catch clause parameter type E does not include any unchecked exceptions.
All exceptions that are thrown in the try block whose type is a (strict) subtype of E are already handled by previous catch clauses.
Live Demo
public class UnreachableBlock{
   public static void main(String[] args) {
      try {
         int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
      } catch(NumberFormatException nfe) {
         System.out.println("This block handles NumberFormatException");
      } catch(Exception e) {
         System.out.println("This block handles all exception types");
      } catch (Throwable t) {
         System.out.println("Throwable is super class of Exception");
      }
   }
}
This block handles NumberFormatException
Create a New Maven Project from Command Prompt - GeeksforGeeks

14 Dec, 2020
Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT.In short, maven is a tool that can be used for building and managing any Java-based project. Maven makes the day-to-day work of Java developers easier and generally help with the comprehension of any Java-based project.
Steps for creating a New Maven Project from Command Prompt:
Step 1: Open Run and type ‘cmd‘ to open Command Prompt.
Step 2: Using ‘cd’ command, you have to browse to the folder where you want to set up your project and then type the below command:
mvn archetype:generate -DgroupId=ToolsQA -DartifactId=DemoMavenProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
In the above command, you are using ‘DartifactId‘ i.e. your project name and ‘DarchetypeArtifactId‘ is the type of Maven project. There are different types of maven projects like web projects, java projects, etc.
Once you press Enter after typing the above command, it will start creating the Maven project
Step 3: After successfully building, once go to the project location to see the newly created maven project. Now open the pom.xml file, which resides in the project folder. By default, the POM is generated like this:
HTML
<!---contributed by sambhav228------><project xmlns="https://maven.apache.org/POM/3.2.3"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="https://maven.apache.org/POM/3.2.3 http://maven.apache.org/maven-v3_2_3.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>ToolsQA</groupId>    <artifactId>DemoMavenProject</artifactId>    <packaging>jar</packaging>    <version>1.0-SNAPSHOT</version>    <name>DemoMavenProject</name>    <url>http://maven.apache.org</url>    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>3.8.1</version>            <scope>test</scope>        </dependency>    </dependencies></project>
Step 4: In the folder structure of the Maven project you can find your DemoMavenProject.
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?
How to execute PHP code using command line ?
REST API (Introduction)
PHP | Spreadsheet_Excel_Writer | setBold() Function - GeeksforGeeks

04 Oct, 2021
The setBold() function is an inbuilt function in PHP | Spreadsheet_Excel_Writer which is used to set the boldness of the text.
Syntax: 
void Format::setBold( $weight = 1 )
Parameters: This function accepts a single parameter $weight which is used to set the weight of the text. The default value of text weight is 1 (700). It ranges from 100 to 1000.
Return Value: This function returns TRUE on success and PEAR_ERROR on failure. 
Example 1:  
PHP
<?phprequire_once 'Spreadsheet/Excel/Writer.php'; // Create Spreadsheet_Excel_Writer Object$workbook = new Spreadsheet_Excel_Writer(); // Add Worksheet$worksheet =& $workbook->addWorksheet(); // Set Font Family Times New Roman$format_setBold =& $workbook->addFormat();$format_setBold->setFontFamily('Times New Roman'); // Set Bold Property$format_setBold->setBold(); // Set Shadow to text$format_setBold->setShadow(); // Write to Worksheet$worksheet->write(0, 0, "Information");$worksheet->write(1, 0, "Website Name", $format_setBold);$worksheet->write(1, 1, "Address", $format_setBold);$worksheet->write(2, 0, "GeeksforGeeks", $format_setBold);$worksheet->write(2, 1, "https://www.geeksforgeeks.org/",                                      $format_setBold);$workbook->send('test.xls'); $workbook->close();?>
Output: 
Example 2:  
PHP
<?phprequire_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_bold =& $workbook->addFormat(); // Set Bold$format_bold->setBold(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); // Write to Worksheet$worksheet->write(0, 0, "Details of GeeksforGeeks                          Contributors", $format_bold);$worksheet->write(1, 0, "Author", $format_bold);$worksheet->write(1, 1, "User Handle", $format_bold);$worksheet->write(2, 0, "Sarthak", $format_bold);$worksheet->write(2, 1, "sarthak_ishu11", $format_bold); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?>
Output: 
Reference: https://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.spreadsheet-excel-writer-format.setbold.php 
ruhelaa48
PHP-function
PHP-Spreadsheet
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
How to generate PDF file using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Python - Ways to convert array of strings to array of floats

String literals in python are surrounded by either single quotation marks, or double quotation marks. Assigning a string to a variable is done with the variable name followed by an equal sign and the string. You can assign a multiline string to a variable by using three quotes.
 Live Demo
# array of strings to array of floats using astype
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.astype
res = ini_array.astype(np.float)
# printing final result
print ("final array", str(res))
# array of strings to array of floats using fromstring  
import numpy as np  
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.fromstring
ini_array = ', '.join(ini_array)
ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' )
# printing final result
print ("final array", str(ini_array))
# converting array of strings to array of floats using asarray
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.asarray
final_array = b = np.asarray(ini_array,
   dtype = np.float64, order ='C')
# printing final result
print ("final array", str(final_array))
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
Find minimum element of HashSet in Java

To get the minimum element of HashSet, use the Collections.min() method.
Declare the HashSet −
Set<Integer> hs = new HashSet<Integer>();
Now let us add the elements −
hs.add(29);
hs.add(879);
hs.add(88);
hs.add(788);
hs.add(456);
Let us now get the minimum element −
Object obj = Collections.min(hs);
The following is an example to find the minimum element of HashSet −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create hash set
      Set<Integer> hs = new HashSet<Integer>();
      hs.add(29);
      hs.add(879);
      hs.add(88);
      hs.add(788);
      hs.add(456);
      System.out.println("Elements in set = "+hs);
      // finding minimum element
      Object obj = Collections.min(hs);
      System.out.println("Minimum Element = "+obj);
   }
}
Elements in set = [788, 88, 456, 29, 879]
Minimum Element = 29
How to find minimum element in an array using linear search in C language?

C programming language provides two types of searching techniques. They are as follows −
Linear search
Binary search
Searching for the key element is done in a linear fashion.
It is the simplest searching technique.
It does not expect the list to be sorted.
Limitation − It consumes more time and reduce the power of system.
Input (i/p): Unsorted list of elements, key.
Output (o/p):
Success – If key is found.
Unsuccessful – Otherwise.
Following is the C program to find minimum element in an array by using linear search −
 Live Demo
#include<stdio.h>
int main (){
   int a[50], n, i, key, flag = 0;
   printf("enter the no: of elements");
   scanf ("%d",&n);
   printf("enter the elements:");
   for (i=0; i<n; i++)
      scanf( "%d", &a[i]);
   printf("enter a key element:");
   scanf ("%d", &key);
   for (i=0; i<n; i++){
      if (a[i] == key){
         flag = 1;
         break;
      }
   }
   if (flag == 1)
      printf("search is successful:");
   else
      printf("search is unsuccessfull:");
   return 0;
}
When the above program is executed, it produces the following result −
enter the no: of elements 5
enter the elements:
12
34
56
78
89
enter a key element:56
search is successful:
Given below is another program to find the minimum element in array by using liner search −
 Live Demo
#include <stdio.h>
int min_ele(int numbers[], int n){
   int min = numbers[0];
   int i;
   for (i = 1; i <= n; i++){
      if (min > numbers[i])
      min = numbers[i];
   }
   return min;
}
int main(){
   int n;
   printf("Enter no: of elements in an array: ");
   scanf("%d",&n);
   int numbers[n];
   int i;
   int min ;
   printf("Enter %d numbers : ", n);
   printf("\n");
   for (i = 0; i < n; i++){
      scanf("%d", &numbers[i]);
   }
   min = min_ele(numbers,n);
   printf("\In an array the minimum number is: %d\n", min);
   return 0;
}
When the above program is executed, it produces the following result −
Enter no: of elements in an array: 5
Enter 5 numbers:
23
56
78
9
20
In an array the minimum number is: 9
JavaScript Chart.js

Chart.js is an open source JavaScript library. Using Chart.js, add animated, interactive graphs on your website.
Following is the code for Chart.js library in JavaScript −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<script
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</script>
</head>
<body>
<canvas id="myChart" width="500" height="300"></canvas>
<script type="text/javascript">
   var ctx = document.getElementById("myChart");
   var myChart = new Chart(ctx, {
      type: 'bar',
         data: {
            labels: ["2005", "2007" , "2009" , "2012", "2014"],
            datasets: [
               { label: 'HouseHold income',
               data: [5000,8000,10000,1200,15000],
               backgroundColor :['rgba(255, 129, 102, 1)',
               'rgba(234, 162, 235, 1)',
               'rgba(255, 206, 36, 1)',
               'rgba(75, 192, 192, 1)',
               'rgba(153, 102, 255, 1)',
            ],
         }
      ]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero:true
            }
         }]
      }
   }
});
</script>
</body>
</html>
Add a new column and set values in it on the basis of conditions in MySQL?

To set values on the basis of conditions, use IF() method. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Age int
   -> );
Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(16);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable values(17);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values(22);
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 −
+------+
| Age  |
+------+
|   19 |
|   16 |
|   17 |
|   22 |
+------+
4 rows in set (0.00 sec)
Following is the query to set values on the basis of condition −
mysql> select Age,if(Age > 18,'You are qualified!','Sorry, you are rejected!') AS Result from
DemoTable;
This will produce the following output −
+------+-------------------------+
| Age  | Result                  |
+------+-------------------------+
|   19 | You are qualified!      |
|   16 | Sorry, you are rejected!|
|   17 | Sorry, you are rejected!|
|   22 | You are qualified!      |
+------+-------------------------+
4 rows in set (0.00 sec)