code-rag-bench/online-tutorials huggingface dataset:
How can I remove all empty values when I explode a string using PHP?

The array_filter() or PREG_SPLIT_NO_EMPTY option on preg_split() can be used to remove empty values from a string when it is exploded −
 Live Demo
<?php
$_POST['tag'] = ",abc,defg,,,hijk,lmnop,,0,,";
echo "--- version 1: array_filter ----\n";
// note that this also filters "0" out, since (bool)"0" is FALSE in php
// array_filter() called with only one parameter tests each element as a boolean value
$tags = array_filter( explode(",", $_POST['tag']) );
var_dump($tags);
echo "--- version 2: array_filter/strlen ----\n";
// this one keeps the "0" element
// array_filter() calls strlen() for each element of the array and tests the result as a boolean value
$tags = array_filter( explode(",", $_POST['tag']), 'strlen' );
var_dump($tags);
echo "--- version 3: PREG_SPLIT_NO_EMPTY ----\n";
$tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY);
var_dump($tags);
 
This will produce the following output −
--- version 1: array_filter ---- array(4) { [1]=> string(3) " abc " [2]=> string(4) " defg " 
[5]=> string(4) "hijk" [6]=> string(5) "lmnop" } --- version 2: array_filter/strlen ---- array(5) 
{ [1]=> string(3) "abc" [2]=> string(4) "defg" [5]=> string(4) "hijk" [6]=> string(5) "lmnop" [8]=> 
string(1) "0" } --- version 3: PREG_SPLIT_NO_EMPTY ---- array(5) { [0]=> string(3) "abc" [1]=> 
string(4) "defg" [2]=> string(4) "hijk" [3]=> string(5) "lmnop" [4]=> string(1) "0" }
How do I check to see if a value is an integer in MySQL?

To check if the given value is a string or not ,we use the cast() function. If the value is not numeric then it returns 0, otherwise it will return the numeric value. In this way, we can check whether the value is an integer or not.
mysql> select cast('John123456' AS UNSIGNED);
The following is the output. It shows that the value is not numeric, therefore 0 is returned.
+--------------------------------+
| cast('John123456' AS UNSIGNED) |
+--------------------------------+
|                              0 |
+--------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> select cast('123456' AS UNSIGNED);
The following is the output. It shows that the value is numeric, therefore the value itself is returned.
+----------------------------+
| cast('123456' AS UNSIGNED) |
+----------------------------+
|                     123456 |
+----------------------------+
1 row in set (0.00 sec)

This logic does work well for float as well.
The following is the query with float value.
mysql>  SELECT CAST('78.90' AS UNSIGNED);
Here is the output.
+---------------------------+
| CAST('78.90' AS UNSIGNED) |
+---------------------------+
|                        78 |
+---------------------------+
1 row in set, 1 warning (0.00 sec)

It works for all conditions for any value, even float.
Let us create a new table.
mysql> create table CheckingIntegerDemo
   -> (
   -> Value varchar(200)
   -> );
Query OK, 0 rows affected (0.88 sec)

Inserting records into table.
mysql> insert into CheckingIntegerDemo values('John123456');
Query OK, 1 row affected (0.10 sec)

mysql>  insert into CheckingIntegerDemo values('123456');
Query OK, 1 row affected (0.16 sec)

mysql> insert into CheckingIntegerDemo values('123.456');
Query OK, 1 row affected (0.16 sec)
To display all records.
mysql> select *from CheckingIntegerDemo;
Here is the output.
+------------+
| Value      |
+------------+
| John123456 |
| 123456     |
| 123.456    |
+------------+
3 rows in set (0.00 sec

In the above output, only 123456 is an integer and the remaining are not.
Syntax to check if the value is an integer.
select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$';
The query wherein we have used regular expression. This will output only the integer value.
mysql> select Value from CheckingIntegerDemo where Value REGEXP '^-?[0-9]+$';
The following is the output.
+--------+
| Value  |
+--------+
| 123456 |
+--------+
1 row in set (0.00 sec)
How to save MySQL query output to excel or .txt file?

To save MySQL query output into a text file, we can use the OUTFILE command.

Let us first create a table.
mysql> create table SaveintoTextFile
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.55 sec)
Inserting records into the table.
mysql> insert into SaveintoTextFile values(1,'John');
Query OK, 1 row affected (0.44 sec)

mysql> insert into SaveintoTextFile values(101,'Carol');
Query OK, 1 row affected (0.17 sec)

mysql> insert into SaveintoTextFile values(3,'David');
Query OK, 1 row affected (0.14 sec
To display all the records.
mysql> select *from SaveintoTextFile;
Here is the output.
+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|  101 | Carol |
|    3 | David |
+------+-------+
3 rows in set (0.00 sec)

The following is the syntax to display the result in a text file.
SELECT  col_name1,col_name2,.......N from yourTableName
 INTO OUTFILE "Path of my.cnf file-  secure-file-priv ";

Let us implement the above syntax in the following query. Here, our text file is “QueryOutput.txt”
mysql> SELECT id,name from SaveintoTextFile
    -> INTO OUTFILE "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/QueryOutput.txt";
Query OK, 3 rows affected (0.02 sec)
To check if the text file is created or not, check the “Uploads” folder.
Now, open the text file. The text would be visible in the file as shown in the following screenshot.
Program to find number of friend groups in a set of friends connections in Python

Suppose we have a a friends list, where friends[i] is a list of people i is friends with. The connection of friendships are two-way. And each person is friend with themselves and two people are in a friend group as long as there is some path of mutual friends connecting them. We have to find the total number of friend groups.
So, if the input is like friends = [[0, 1, 5],[1, 0],[2],[3, 4],[4, 3],[5, 0]], then the output will be 3, as The three friend groups are as below −
To solve this, we will follow these steps −
nodes := size of friends
visited := a list of size same as nodes and fill with False
ans := 0
Define a function dfs() . This will take vertex, visited
visited[vertex] := True
for each nei in friends[vertex], doif visited[nei] is false, thendfs(nei, visited)
if visited[nei] is false, thendfs(nei, visited)
dfs(nei, visited)
From the main method, do the following −
for i in range 0 to nodes, doif visited[i] is false, thendfs(i, visited)ans := ans + 1
if visited[i] is false, thendfs(i, visited)ans := ans + 1
dfs(i, visited)
ans := ans + 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, friends):
      nodes = len(friends)
      visited = [False for _ in range(nodes)]
      ans = 0
      def dfs(vertex, visited): visited[vertex] = True
         for nei in friends[vertex]:
            if not visited[nei]:
               dfs(nei, visited)
      for i in range(nodes):
         if not visited[i]:
            dfs(i, visited)
            ans += 1
      return ans
ob = Solution()
friends = [ [0, 1, 5], [1, 0], [2], [3, 4], [4, 3], [5, 0] ]
print(ob.solve(friends))
[[0, 1, 5],
[1, 0],
[2],
[3, 4],
[4, 3],
[5, 0]
]
3
Rust - Arithmetic Operators

Assume the values in variables a and b are 10 and 5 respectively.
NOTE − The ++ and -- operators are not supported in Rust.
fn main() {
   let num1 = 10 ;
   let num2 = 2;
   let mut res:i32;

   res = num1 + num2;
   println!("Sum: {} ",res);

   res = num1 - num2;
   println!("Difference: {} ",res) ;

   res = num1*num2 ;
   println!("Product: {} ",res) ;

   res = num1/num2 ;
   println!("Quotient: {} ",res);

   res = num1%num2 ;
   println!("Remainder: {} ",res);
}
Sum: 12
Difference: 8
Product: 20
Quotient: 5
Remainder: 0


    45 Lectures 
     4.5 hours 

 Stone River ELearning

    10 Lectures 
     33 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
JSF - f:param

f:param tag provides the options to pass parameters to a component or pass request parameters.
Pass parameter to a UI component
<h:outputFormat value = "Hello {0}!.">     
   <f:param value = "World" /> 
</h:outputFormat>
Pass request parameter
<h:commandButton id = "submit"  
   value = "Show Message" action = "#{userData.showResult}"> 
   <f:param name = "username" value = "JSF 2.0 User" /> 
</h:commandButton> 
id
Identifier for a component
binding
Reference to the component that can be used in a backing bean
name
An optional name for this parameter component
value
The value stored in this component
Let us create a test JSF application to test the above tag.
package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;
   public String data = "1";

   public String getData() {
      return data;
   }

   public void setData(String data) {
      this.data = data;
   }

   public String showResult() {
      FacesContext fc = FacesContext.getCurrentInstance();
      Map<String,String> params = 
         fc.getExternalContext().getRequestParameterMap();
      data =  params.get("username"); 
      return "result";
   }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
   <head>
      <title>JSF Tutorial!</title>
   </head>
   
   <body>
      <h2>f:param example</h2>
      <hr />
      
      <h:form>
         <h:outputFormat value = "Hello {0}!.">
            <f:param value = "World" />
         </h:outputFormat>
         <br/>
         
         <h:commandButton id = "submit" 
            value = "Show Message" action = "#{userData.showResult}">
            <f:param name = "username" value = "JSF 2.0 User" />
         </h:commandButton>
      </h:form>
   
   </body>
</html>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:f = "http://java.sun.com/jsf/core"    
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:ui = "http://java.sun.com/jsf/facelets">
   
   <head>
      <title>JSF Tutorial!</title>
   </head>
   
   <h:body>
      <h2>Result</h2>
      <hr />
      #{userData.data}
   </h:body>
</html>  
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Press Show Message button and you'll see the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
How to create Empty Values String in JavaScript?

To create empty values string in JavaScript, you can try to run the following code −
<html>
   <head>
      <script>
         var val;
         val = "";
         document.write("Value: "+val);
         document.write("<br>Type: "+typeof val);
      </script>
   </head>
   <body>
   </body>
</html>
XML - DOM

The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them.
A DOM document is a collection of nodes or pieces of information organized in a hierarchy. This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of information, the DOM is said to be tree based.
The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move, or remove nodes in the tree at any point in order to create an application.
The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM object and then extracts some information from it with JavaScript −
<!DOCTYPE html>
<html>
   <body>
      <h1>TutorialsPoint DOM example </h1>
      <div>
         <b>Name:</b> <span id = "name"></span><br>
         <b>Company:</b> <span id = "company"></span><br>
         <b>Phone:</b> <span id = "phone"></span>
      </div>
      <script>
         if (window.XMLHttpRequest)
         {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
         }
         else
         {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.open("GET","/xml/address.xml",false);
         xmlhttp.send();
         xmlDoc = xmlhttp.responseXML;

         document.getElementById("name").innerHTML=
            xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
         document.getElementById("company").innerHTML=
            xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
         document.getElementById("phone").innerHTML=
            xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
      </script>
   </body>
</html>
Contents of address.xml are as follows −
<?xml version = "1.0"?>
<contact-info>
   <name>Tanmay Patil</name>
   <company>TutorialsPoint</company>
   <phone>(011) 123-4567</phone>
</contact-info>
Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute the sample.htm file by opening it in any browser. This should produce the following output.
Here, you can see how each of the child nodes is extracted to display their values.

    84 Lectures 
     6 hours 

 Frahaan Hussain

    29 Lectures 
     2 hours 

 YouAccel

    27 Lectures 
     1 hours 

 Jordan Stanchev

    16 Lectures 
     2 hours 

 Simon Sez IT
 Print
 Add Notes
 Bookmark this page
groupmod command in Linux with examples - GeeksforGeeks

20 May, 2019
groupmod command in Linux is used to modify or change the existing group on Linux system. It can be handled by superuser or root user. Basically, it modifies a group definition on the system by modifying the right entry in the database of the group.
Syntax:
groupmod [option] GROUP
Files: The groupmod command has following files.
/etc/group: Group Account Information.
/etc/gshadow: Secured group account information.
/etc/login.def: Shadow passwd suite configuration.
/etc/passwd: User account information.
Exit Values:
0: Success.
2: Invalid command Syntax.
3: Invalid argument to option.
4: specified group doesn’t exist.
6: specified group doesn’t exist.
9: group name already in use.
10: can’t update group file.
Options: There are following option available in groupmod command.
-g, –gid GID: The group ID of the given GROUP will be changed to GID.
-n, –new-name NEW_GROUP: The name of group will change into newname.
-h, –help: This option display help massage and exist.
-o, –non-unique: This option used with the -g option that allow to change the group GID to a non-unique value.
-p, –password PASSWORD: This gives the encrypted password.
-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory.
Example: Below command will change the group group_old to group_new using -n option.
groupmod -n group_new group_old
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
SORT command in Linux/Unix with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
How to print integer array in android Log?

This example demonstrate about How to print integer array in android Log.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="30dp"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/list"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </ListView>
</LinearLayout>
In the code, we have taken listview to show integer array
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {
   ListView list;
   int[] array = {2, 5, 6, 8, 0, 7, 9, 4};
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      list = findViewById(R.id.list);
      ArrayList<String> arrayList = new ArrayList<String>();
      for(int s:array) {
         arrayList.add(String.valueOf(s));
      }
      Log.d("Array List: ", Arrays.toString(array));
      ArrayAdapter adapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_list_item_1, arrayList);
      list.setAdapter(adapter);
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, we had shown integer array and now check log in the android studio as shown below –
Click here to download the project code
Exit Status($?) variable in Linux - GeeksforGeeks

01 Oct, 2020
“$?” is a variable that holds the return value of the last executed command.  “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred.  The bash sets “$?” To the exit status of the last executed process. By convention 0 is a successful exit and non-zero indicates some kind of error. It can be used to check if the previous command has been executed without any errors. If it has executed successfully then it stores 0. “$?” is also useful in shell scripts as a way to decide what to do depending on how the last executed command worked by checking the exit status.
Working with “$?” operator
1. Its default value is 0 when the system starts and no command has been executed yet. Even if the last command has not been successfully executed and the system is restarted, we get its value as 0 when the following command is entered into the terminal. 
echo $?

2. It returns the exit status of the last executed command. In the example mentioned below, There is no command as eccho in UNIX and hence the last process was not successfully executed. So $? stores a non-zero value which is the exit status of the last executed command. 
eccho
echo $?
3. In the example mentioned below, If the file exists (can be either directory or file), then the return value by the “ls” command will be 0 (i.e, the command has been successfully executed) else it will display a number which is non-zero. The number depends on the program. Referring to the image below, consider that by default “file” doesn’t exist then $? stores a return value of 2 (the command was not successfully executed) but once created using touch it displays 0 as the ls command returns 0 since the file exists.
ls file
echo $?
touch file 
echo $?
4. Also, when we enter simple true and false values in the terminal,it displays 0 as true does nothing but exits with a status code 0. But if we give false then 1 will get printed as false exits with status code 1.
true
echo $?
false
echo $?

linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
'crontab' in Linux with Examples
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
tee command in Linux with examples
touch command in Linux with Examples
How to get last day of a month from date in PHP ?

19 May, 2020
Given a date and the task is to print the last day of the month. We will use date() and strtotime() function to get the last day of the month.
Used PHP functions:
date() function: Format a local time/date.
strtotime() function: Parse about any English textual datetime description into a Unix timestamp.
Examples:
Input: 2020-04-23
Output: Thursday

Input: '2018-09-11'
Output: Sunday
Approach:
Given a date stored in a variable as a string, the step is to convert it into date format using strtotime() function.
Once we get the date, we will employ date() method.Syntax:date( $format, $timestamp )
date( $format, $timestamp )
Within $format, we will pass “Y-m-t” and within $timestamp the date taken above. In terms of date “Y” gives a full numeric representation of a year in 4 digits, “m” provides numeric representation of a month and “t” gives the number of days in the given month.
By using “Y-m-t”, we will get the number of days in a month because of “t”, “m” and “Y” will provide the month and the year.
The last step is to use the date() again with “l” for format and the date achieved above as $timestamp.
Display the day.
Program:
<?php   // Given a date in string format $datestring = '2020-04-23';  // Converting string to date$date = strtotime($datestring);   // Last date of current month.$lastdate = strtotime(date("Y-m-t", $date ));    // Day of the last date $day = date("l", $lastdate);  echo $day;?>
Thursday

PHP-function
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find the first day of given year

02 Aug, 2019
Given a year as input, write a Python to find the starting day of the given year. We will use Python datetime library in order to solve this problem.
Example:
Input : 2010
Output :Friday

Input :2019
Output :Tuesday

Below is the implementation:
# Python program to find the first day of given year  # import datetime libraryimport datetime  def Startingday(year):          # Creating an object for 1st January of that particular year    # For that we are passing three argument (1) year (2) month    # i.e 1 for january (3) date i.e 1 for starting day of     # that particular year    a = datetime.datetime(year, 1, 1)      # for printing Startingday of a particular year     # we are using a.strftime("% A")    print("Starting day of year ", year, " is ", a.strftime("%A"))  # Driver Codeyear = 2010Startingday(year)
Starting day of year  2010  is  Friday

Python Calander-module
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 OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
map::begin() and end() in C++ STL

13 Jun, 2022
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
begin() function is used to return an iterator pointing to the first element of the map container. begin() function returns a bidirectional iterator to the first element of the container. Syntax :
mapname.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.
Examples:
Input  : mymap['a'] = 1;
         mymap['b'] = 2;
         mymap['c'] = 3;
         mymap.begin();
Output : returns an iterator to the element 'a' = 1

Input  : mymap['d'] = 1;
         mymap.begin();
Output : returns an iterator to the element 'd' = 1
Errors and Exceptions 1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. 
CPP
// Demonstrates begin() and end()#include <iostream>#include <map>using namespace std; int main(){    // declaration of map container    map<char, int> mymap;    mymap['a'] = 1;    mymap['b'] = 2;    mymap['c'] = 3;     // using begin() to print map    for (auto it = mymap.begin();         it != mymap.end(); ++it)        cout << it->first << " = "             << it->second << '\n';    return 0;}
Output:
a = 1
b = 2
c = 3
end() function is used to return an iterator pointing to past the last element of the map container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator. Syntax :
mapname.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the next of last element.
Examples:
Input  : mymap['a'] = 1;
         mymap['b'] = 2;
         mymap['c'] = 3;
         mymap.end();
Output : returns an iterator to next to c 
(after last element)
Errors and Exceptions 1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. 
CPP
// CPP program to illustrate// Demonstrates begin() and end()#include <iostream>#include <map>using namespace std; int main(){    // declaration of map container    map<char, int> mymap;    mymap['a'] = 1;    mymap['b'] = 2;    mymap['c'] = 3;     // using begin() to print map    for (auto it = mymap.begin();         it != mymap.end(); ++it)        cout << it->first << " = "             << it->second << '\n';    return 0;}
Output:
a = 1
b = 2
c = 3
Let us see the differences in a tabular form -:
Its syntax is -:
iterator begin();
mayank007rawa
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
View Computer’s Important Network Information Using Python

11 Oct, 2020
While working in a network, we do some troubleshooting with the network or Internet problem. This time we need to check your own system network connection information.
We can find the network connection in the Control Panel in Windows. The best way to find this information we can use ipconfig command in CMD. When you use ipconfig /all then you can get enough information to resolve your network problem.
Examples:
Method 1:
We will use the subprocess module to interact with cmd and to retrieve information into your python ide. We can read the cmd command through the subprocess module.
Approach:
import moduleGet the output for the command “‘ipconfig’,’/all’ ” using subprocess.check_output()Now get the Split the string and arrange your data with your own needs.
import module
Get the output for the command “‘ipconfig’,’/all’ ” using subprocess.check_output()
Now get the Split the string and arrange your data with your own needs.
Python3
# import moduleimport subprocess  # Traverse the ipconfig informationdata = subprocess.check_output(['ipconfig','/all']).decode('utf-8').split('\n')  # Arrange the bytes datafor item in data:     print(item.split('\r')[:-1])
Output:
Method 2:
Ifcfg module is a cross-platform (Windows/Unix) library for parsing ifconfig and ipconfig output in Python. It is useful for pulling information such as IP, Netmask, MAC Address, Hostname, etc.
Installation:
pip install ifcfg


Implementation:
Python3
import ifcfgprint(ifcfg.interfaces())
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Pagination in DataGrid Component in ReactJS ?

26 Apr, 2021
Pagination helps in viewing a segment of data from the assigned data source. Pagination improves the user experience as users can switch between pages to see data. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can use the following approach in ReactJS to use Pagination in DataGrid Component.
Approach: Follow these simple steps in order to use Pagination in DataGrid Component in ReactJS. In the following example, With the help of the rowsPerPageOptions prop, we can do the Pagination in DataGrid Component like we have passed [2, 5, 7] as a value which means we can show users the option to see 2 or 5 or 7 rows on a single page. The default pageSize is 100, but we can change this value with the pageSize prop.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:
npm install @material-ui/data-grid
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import * as React from 'react';import { DataGrid } from '@material-ui/data-grid';  const columns = [  { field: 'id', headerName: 'ID', width: 170 },  { field: 'name', headerName: 'NAME', width: 170 },  { field: 'age', headerName: 'AGE', width: 170 },];  const rows = [  { id: 1, name: 'Gourav', age: 12 },  { id: 2, name: 'Geek', age: 43 },  { id: 3, name: 'Pranav', age: 41 },  { id: 4, name: 'Abhay', age: 34 },  { id: 5, name: 'Pranav', age: 73 },  { id: 6, name: 'Disha', age: 61 },  { id: 7, name: 'Raghav', age: 72 },  { id: 8, name: 'Amit', age: 24 },  { id: 9, name: 'Anuj', age: 48 },];  export default function App() {    return (    <div style={{ height: 500, width: '80%' }}>      <h4>        How to use Pagination in DataGrid        Component in ReactJS?      </h4>      <DataGrid rows={rows} columns={columns}         pageSize={5} rowsPerPageOptions={[2, 5, 7]}      />    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://material-ui.com/components/data-grid/pagination/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to detect network speed using JavaScript?

16 Jul, 2020
To detect the network speed using javascript, we will use the following approach.
Approach: Open the web page for which you want to know the connection speed. The page should be the one for which you want to add the javascript code for detecting the speed. Assign or set up the address of the image which you want to use for speed test to the variable. The variables for storing the test’s start time, end time, and download size should be created. Set the “downloadSize” equivalent to the image file size(In bytes). The end of the download action is assigned to activate when the image downloading is completed. It calculates the speed of the download process, and converts it to “kbps” and “mbps”.
Below is example illustrate the above approach:Example:
<!DOCTYPE html><html>    <head>        <title>          To detect network speed using JavaScript        </title>    </head>    <body>        <script type="text/javascript">            var userImageLink = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200714180638/CIP_Launch-banner.png";            var time_start, end_time;                        // The size in bytes            var downloadSize = 5616998;            var downloadImgSrc = new Image();              downloadImgSrc.onload = function () {                end_time = new Date().getTime();                displaySpeed();            };            time_start = new Date().getTime();            downloadImgSrc.src = userImageLink;            document.write("time start: " + time_start);            document.write("<br>");              function displaySpeed() {                var timeDuration = (end_time - time_start) / 1000;                var loadedBits = downloadSize * 8;                                /* Converts a number into string                   using toFixed(2) rounding to 2 */                var bps = (loadedBits / timeDuration).toFixed(2);                var speedInKbps = (bps / 1024).toFixed(2);                var speedInMbps = (speedInKbps / 1024).toFixed(2);                alert("Your internet connection speed is: \n"                       + bps + " bps\n" + speedInKbps                       + " kbps\n" + speedInMbps + " Mbps\n");            }        </script>    </body></html>
Output:
HTML-Misc
javascript-basics
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Java program to check whether the given number is an Armstrong number

An Armstrong number is a number which equals to the sum of the cubes of its individual digits. For example, 153 is an Armstrong number as −
153 = (1)3 + (5)3 + (3)3
153 1 + 125 + 27
154 153
1. Take integer variable Arms
2. Assign value to the variable
3. Split all digits of Arms
4. Find cube-value of each digits
5. Add all cube-values together
6. Save the output to Sum variable
7. If Sum equals to Arms print Armstrong Number
8. If Sum not equals to Arms print Not Armstrong Number
import java.util.Scanner;
public class ArmstrongNumber {
   public static void main(String args[]) {
      int number = 153;
      int check, rem, sum = 0;
      System.out.println("Enter the number to be verified:");
      Scanner sc = new Scanner(System.in);
      number = sc.nextInt();
      check = number;
      while(check != 0) {
         rem = check % 10;
         sum = sum + (rem * rem * rem);
         check = check / 10;
      }
      if(sum == number)
         System.out.println("Given number is an armstrong number.");
      else
         System.out.println("Given number is not an armstrong number.");
   }
}
Enter the number to be verified:
153
Given number is an armstrong number.
C++ Program to Implement Fermat’s Little Theorem

Fermat's little theorem is one of the fundamental results of elementary number theory and is the basis for the Fermat primality test. The theorem is named after Pierre de Fermat, who stated it in 1640. The Theorem states that if p is a prime number, then for any integer a, the number a p–a is an integer multiple of p.
Begin
   Function power() is used to compute a raised to power b under modulo M
   function modInverse() to find modular inverse of a under modulo m :
   Let m is prime
   If a and m are relatively prime, then
      modulo inverse is a^(m - 2) mod m
End
#include <iostream>
using namespace std;
int pow(int a, int b, int M) {
   int x = 1, y = a;
   while (b > 0) {
      if (b % 2 == 1) {
         x = (x * y);
         if (x > M)
            x %= M;
      }
      y = (y * y);
      if (y > M)
         y %= M;
         b /= 2;
   }
   return x;
}
int modInverse(int a, int m) {
   return pow(a, m - 2, m);
}
int main() {
   int a, m;
   cout<<"Enter number to find modular multiplicative inverse: ";
   cin>>a;
   cout<<"Enter Modular Value: ";
   cin>>m;
   cout<<modInverse(a, m)<<endl;
}
Enter number to find modular multiplicative inverse: 26
Enter Modular Value: 7
3
C++ Vector Library - push_back() Function

The C++ function std::vector::push_back() inserts new element at the end of vector and increases size of vector by one.
Following is the declaration for std::vector::push_back() function form std::vector header.
void push_back (const value_type& val);

void push_back (const value_type& val);
void push_back (value_type&& val);

None
None.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::push_back() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v;

   /* Insert 5 elements */
   for (int i = 0; i < 5; ++i)
      v.push_back(i + 1);

   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
PL/SQL - Basic Syntax

In this chapter, we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-parts −
Declarations
This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed.
Exception Handling
This section starts with the keyword EXCEPTION. This optional section contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −
DECLARE 
   <declarations section> 
BEGIN 
   <executable command(s)>
EXCEPTION 
   <exception handling> 
END;

DECLARE 
   message  varchar2(20):= 'Hello, World!'; 
BEGIN 
   dbms_output.put_line(message); 
END; 
/ 
The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt, it produces the following result −
Hello World  

PL/SQL procedure successfully completed.

PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters.

By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. You cannot use a reserved keyword as an identifier.
A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −
Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. All programming languages allow some form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.
DECLARE 
   -- variable declaration 
   message  varchar2(20):= 'Hello, World!'; 
BEGIN 
   /* 
   *  PL/SQL executable statement(s) 
   */ 
   dbms_output.put_line(message); 
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World

PL/SQL procedure successfully completed.
A PL/SQL unit is any one of the following −
PL/SQL block
Function
Package
Package body
Procedure
Trigger
Type
Type body
Each of these units will be discussed in the following chapters.
 Print
 Add Notes
 Bookmark this page
How to define a variable in C++?

To define a variable in  C++, you need to use the following syntax −
datatype variable_name;
You need to know what type of data is your variable is going to hold and what it will be called. The variable name has constraints on what you can name it. Following are the rules for naming variables −
Variable names in C++ can range from 1 to 255 characters.
All variable names must begin with a letter of the alphabet or an underscore(_).
After the first initial letter, variable names can also contain letters and numbers.  
Variable names are case sensitive.
No spaces or special characters are allowed.
You cannot use a C++ keyword (a reserved word) as a variable name.
Here are some examples of acceptable variable names −
mohd       Piyush    abc   move_name    a_123
myname50   _temp      j      a23b9      retVal
Examples of defining variables −
int my_var;
float my_float;
double num;
How to Create 5 Star Skills Rating Bar using CSS ? - GeeksforGeeks

22 Oct, 2021
In this article, we will create a 5 Star Rating Bar using CSS and HTML. A 5-star rating bar is used to collect user opinions or feedback. Users can give a rating out of 5 as per their satisfaction. We will create the layout or design of the rating bar.
Approach:
For the Star Icons, we are using Font-Awesome Icon Library.
Create the layout using HTML.
For stylings use CSS properties.
CSS library: To use Font Awesome Icons, we have to add the library in the HTML file using the link tag.
<link href=”https://pro.fontawesome.com/releases/v5.10.0/css/all.css” rel=”stylesheet”/>
By adding the link, we can access the icons provided by this library. You can get the link for your own project on the Font-Awesome website or you can use the same link as we have mentioned above.
 Syntax: To use Star Icon, use the following syntax.
<i class="fas fa-star"></i>
Note: Please refer to CSS Icons article for a better understanding.
Example: We have created a 5 Star Rating Bar using the above approach. We have added a class clicked in the icon tag. This class is used to change the colour of the star. We have added the CSS properties in the style tag.
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>Rating Bar</title>    <link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"        rel="stylesheet" />              <style>        .rating {            font-size: 40px;        }          .clicked {            color: rgb(135, 187, 32);        }    </style></head>  <body>    <h1>5 Star Rating Bar</h1>    <div class="rating">        <i class="fa fa-star clicked"></i>        <i class="fa fa-star clicked"></i>        <i class="fa fa-star clicked"></i>        <i class="fa fa-star clicked"></i>        <i class="fa fa-star"></i>    </div></body>  </html>
Output: 
5 Star Rating Bar using CSS
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
AngularJS - HTML DOM

The following directives are used to bind application data to the attributes of HTML DOM elements −
ng-disabled
disables a given control.
ng-show
shows a given control.
ng-hide
hides a given control.
ng-click
represents a AngularJS click event.
Add ng-disabled attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.
<input type = "checkbox" ng-model = "enableDisableButton">Disable Button
<button ng-disabled = "enableDisableButton">Click Me!</button>

Add ng-show attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.
<input type = "checkbox" ng-model = "showHide1">Show Button
<button ng-show = "showHide1">Click Me!</button>

Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.
<input type = "checkbox" ng-model = "showHide2">Hide Button
<button ng-hide = "showHide2">Click Me!</button>

Add ng-click attribute to an HTML button and update a model. Bind the model to HTML and see the variation.
<p>Total click: {{ clickCounter }}</p>
<button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>

The following example shows use of all the above mentioned directives.
<html>
   <head>
      <title>AngularJS HTML DOM</title>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      
      <div ng-app = "">
         <table border = "0">
            <tr>
               <td><input type = "checkbox" ng-model = "enableDisableButton">Disable Button</td>
               <td><button ng-disabled = "enableDisableButton">Click Me!</button></td>
            </tr>
            <tr>
               <td><input type = "checkbox" ng-model = "showHide1">Show Button</td>
               <td><button ng-show = "showHide1">Click Me!</button></td>
            </tr>
            <tr>
               <td><input type = "checkbox" ng-model = "showHide2">Hide Button</td>
               <td><button ng-hide = "showHide2">Click Me!</button></td>
            </tr>
            <tr>
               <td><p>Total click: {{ clickCounter }}</p></td>
               <td><button ng-click = "clickCounter = clickCounter + 1">Click Me!</button></td>
            </tr>
         </table>
      </div>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      
   </body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
Total click: {{ clickCounter }}

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    40 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Python Pandas - Return a new Timedelta with milliseconds ceiling resolution

To return a new Timedelta ceiled to this resolution, use the timedelta.ceil() method. For milliseconds ceiling resolution, set the freq parameter to the value ms.
At first, import the required libraries −
import pandas as pd
TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')

Display the Timedelta
print("Timedelta...\n", timedelta)
Return the ceiled Timestamp with milliseconds ceiling resolution
timedelta.ceil(freq='ms')

Following is the code
import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# return the ceiled Timestamp
# with milliseconds ceiling resolution
res = timedelta.ceil(freq='ms')

# display the ceiled Timestamp
print("\nTimedelta (milliseconds ceiled)...\n", res)
This will produce the following code
Timedelta...
2 days 10:45:20.035000055

Timedelta (milliseconds ceiled)...
2 days 10:45:20.036000