code-rag-bench/online-tutorials huggingface dataset:
tracepath command in Linux with Examples

03 Apr, 2019
tracepath command in Linux is used to traces path to destination discovering MTU along this path. It uses UDP port or some random port. It is similar to traceroute, but it does not require superuser privileges and has no fancy options. tracepath6 is a good replacement for traceroute6 and classic example of the application of Linux error queues. The situation with IPv4 is worse because commercial IP routers do not return enough information in ICMP error messages. Probably, it will change, when they will be updated. For now, it uses Van Jacobson’s trick, sweeping a range of UDP ports to maintain trace history.
Syntax:
tracepath [-n] [-b] [-l pktlen] [-m max_hops] [-p port] destination

Example:
tracepath command without any option: It will print the general syntax of the command along with the various options that can be used with the tracepath command as well as gives a brief description about each option.
In the following example using tracepath command we are trying to trace path to destination for google.com.tracepath www.google.com
tracepath www.google.com
Options:
tracepath -n: This option prints primarily IP addresses numerically.Example:tracepath -n www.google.com
Example:
tracepath -n www.google.com
tracepath -b: This option print both of host names and IP addresses.Example:tracepath -b www.google.com
Example:
tracepath -b www.google.com
tracepath -l : This option sets the initial packet length to pktlen instead of 65535 for tracepath or 128000 for tracepath6.Example:tracepath -l 29 www.google.com
Example:
tracepath -l 29 www.google.com
tracepath -m : This option will set maximum hops (or maximum TTLs) to max_hops instead of 30.Example:tracepath -m 31 www.google.com
Example:
tracepath -m 31 www.google.com
tracepath -p: This option will set the initial destination port to use.Example:tracepath -p 8080 www.google.com
Example:
tracepath -p 8080 www.google.com
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Pandas - How to select multiple rows from a DataFrame

To select multiple rows from a DataFrame, set the range using the : operator. At first, import the require pandas library with alias −
import pandas as pd
Now, create a new Pandas DataFrame −
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b'])
Select multiple rows using the : operator −
dataFrame[0:2]
Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b'])

# DataFrame
print"DataFrame...\n",dataFrame

# select rows with loc
print"\nSelect rows by passing label..."
print(dataFrame.loc['z'])

# select rows with integer location using iloc
print"\nSelect rows by passing integer location..."
print(dataFrame.iloc[1])

# selecting multiple rows
print"\nSelect multiple rows..."
print(dataFrame[0:2])


This will produce the following output −
DataFrame...
     a    b
w   10   15
x   20   25
y   30   35
z   40   45

Select rows by passing label...
a   40
b   45
Name: z, dtype: int64

Select rows by passing integer location...
a   20
b   25
Name: x, dtype: int64

Select multiple rows...
     a    b
w   10   15
x   20   25
Lex Program to accept a valid integer and float value

30 Apr, 2019
Lex is a computer program that generates lexical analyzers.Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out

Let’s see to accept a valid integer and float valueusing lex program.
Examples:
Input : 
-77.99
Output :
 Valid Float Value

Input : 
fghj
Output : 
Not a valid Integer/ Float number

Below is the implementation:
/*lex code to accept a valid integer   and float value using lex program.*/    %{int valid_int=0, valid_float=0;%}  %%^[-+]?[0-9]* valid_int++;^[-+]?[0-9]*[.][0-9]+$ valid_float++;.;%%  int main(){  yylex();  if(valid_int!=0) printf("Valid Integer number\n");  else if(valid_float!=0) printf("Valid Float number\n");  else printf("Not valid Integer/Float number\n");  return 0;}
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Issues in the design of a code generator
Three address code in Compiler
Phases of a Compiler
Code Optimization in Compiler Design
Peephole Optimization in Compiler Design
SQL SERVER | Conditional Statements

27 Jan, 2022
While loop: In SQL SERVER, while loop can be used in similar manner as any other programming language. A while loop will check the condition first and then execute the block of SQL Statements within it as long as the condition evaluates true. 
Syntax:
WHILE condition
BEGIN
   {...statements...}
END;
Parameters: 1. Condition: The condition is tested in each pass through the loop. If condition evaluates to TRUE, the loop body is executed otherwise the loop is terminated. 2. Statements: The statements that needs to be executed in each pass through the loop. 
Example:  
Output:  
Break statement: BREAK statement as the name signifies is used to break the flow of control. It can be used in SQL in similar manner as any other programming language. 
Example: While loop with Break statement 
 
Output:  
Note : In the example, when variables value became five, BREAK Statement is executed and the control gets out from the Loop. 
Do-While loop: SQL server does not have the feature of do-while loop but by doing little modifications in while loop, the same behaviour can be achieved. 
Example 1:  
Output:  
Example 2:  
Output:  
CASE statement: In SQL Server, the CASE statement has the same functionality as IF-THEN-ELSE statement. 
Syntax:  
CASE Expression
   WHEN Con_1 THEN Output1 
   WHEN Con_2 THEN Output2
   WHEN Con_3 THEN Output3
   WHEN Con_4 THEN Output4
   ...
   WHEN Con_n THEN Outputn
   ELSE output
END
Parameters: 1. Expression: The value to be compared to the list of conditions(Optional). 2. Con_1, Con_2, ...Con_n: The conditions are required and are evaluated in the order they are listed. Once a condition is true, the CASE function will return the result and not evaluate the conditions any further. 3. Output1, Output2, ...Outputn: The output to be printed once the condition evaluates true. 
Example:  
Output:  
 
saurabh1990aror
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
Python program to concatenate two Integer values into one

13 May, 2020
Given two integers a and b. The task is to concatenate these two integers into one integer.
Examples:
Input : a = 806, b = 91
Output : 80691

Input : a = 5, b = 1091
Output : 51091


Method 1: One method of achieving this can be counting the number of digits of second number. Then multiply the first number with 10^digits and adding both the numbers. Below is the implementation.
# Python program to concatenate# two numbers    def numConcat(num1, num2):       # find number of digits in num2     digits = len(str(num2))       # add zeroes to the end of num1     num1 = num1 * (10**digits)       # add num2 to num1     num1 += num2       return num1    # Driver's codea = 906b = 91print(numConcat(a, b))
90691

Method 2: Another method can be converting both the numbers to the string. Then concatenate them and convert them back to integers. Below is the implementation.
# Python program to concatenate# two numbers    def numConcat(num1, num2):               # Convert both the numbers to        # strings        num1 = str(num1)        num2 = str(num2)                  # Concatenate the strings        num1 += num2                  return int(num1)    # Driver's codea = 906b = 91print(numConcat(a, b))
Output:
90691

riturajsaha
python-basics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <input type=”reset”>

02 Jun, 2022
The HTML <input type=”reset”> is used to defines a reset button. The reset button is used to reset all the form values to its initial values. 
Syntax: 
<input type="reset">> 
Example: 
HTML
<!DOCTYPE html><html> <head>    <title>        HTML Input Type reset    </title></head><style>    #Geek_p {        font-size: 30px;        color: green;    }</style> <body style="text-align:center;">     <h1 style="color:green;">            GeeksForGeeks        </h1>     <h2>HTML Input Type reset</h2>    <form>        Name:        <input type="text">        <br>        <br> Password:        <input type="password">        <br>        <br>         <input type="submit">        <input type="reset">    </form></body> </html>
Output:
 
Supported Browsers:
Google Chrome 1 and above
Firefox 1 and above
Edge 12 and above
Opera
Internet Explorer
Apple Safari 1 and above
kumargaurav97520
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to limit network bandwidth on linux

Have you ever shared network bandwidth with multiple devices? If you have ever been in a position where one application consumed all your traffic, then either you are a system admin or just a Linux user, you will need to discover how to control the upload and download speeds for applications to make sure that your bandwidth is not occupied entirely by a single application. This article gives an idea about how to limit network bandwidth on Linux.
One of the easiest way to control over the network traffic is via command line tool called “trickle“. It can be limit application bandwidth, upload or download speed, or prioritizing daemons (a computer program that runs as a background process). tickle works on the concept based on “Linux Pre-Loader”. It controls the network using send and receive the data through sockets.
To install trickle package, use the following command –
$ sudo apt-get install trickle
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
trickle
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 34.6 kB of archives.
After this operation, 158 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty/universe trickle amd64 1.07-10ubuntu2 [34.6 kB]
........
When using Trickle, choose the appropriate download and upload speeds to limit applications.
For instance, If you are using Firefox as your browser, then limit its downloading capacity to 25 KB/s, and upload badwidth to 15 KB/s. To use trickle in standalone mode, use the following command –
$ trickle -d 25 -u 15 firefox
The above command will open a custom Firefox launcher with network limitations.
Alternatively, control over the network traffic is by enforcing bandwidth limit on per-interface basis. This is most useful way when sharing upstream internet connection with someone else. Using wondershaper tool, you can enforce bandwidth limit on per-interface basis.
To install wondershaper, use the following command –
$ sudo apt-get install wondershaper
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
wondershaper
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 15.0 kB of archives.
After this operation, 77.8 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty/universe wondershaper all 1.1a-6 [15.0 kB]
....
Use the following command to control the Ethernet0 (Number-Zero) in Linux system-
$ sudo wondershaper eth0 1000 500
You can remove wondershaper limit using the following command –
$ sudo wondershaper clear eth0
Congratulations! Now, you know “How to limit Network Bandwidth on Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
Getting a subvector from a vector in C++

This is a C++ program for getting a subvector from a vector in C++
Begin
  Declare s as vector s(vector const &v, int m, int n) to
   initialize start and end position of vector to constructor.
      auto first = v.begin() + m.  
      auto last = v.begin() + n + 1.
      Declare a variable vector of vector type.
         Pass the value of first and last position of vector.
      Return vector.
   Declare a template T.
   Declare a function show().
      Pass constructor of vector v as parameter.
      for (auto i: v)
         print the value of variable i.
   Declare a vector v.
      Initiation values in v vector.
      Initialize two variables a = 3, b = 6.
      Print “Sub vector is:” .
      Declare another vector sub_vector.
         vector sub_vector = s(v, a, b) to initialize values to the
         sub vector by mentioning the start and end position of
         vector v.
   call show() function to display the values of sub_vector.
End.
 Live Demo
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
vector<T> s(vector<T> const &v, int m, int n) {
   auto first = v.begin() + m;
   auto last = v.begin() + n + 1;
   vector<T> vector(first, last);
   return vector;
}
template<typename T>
void show(vector<T> const &v) {
   for (auto i: v) {
      cout << i << ' ';
   }
   cout << '\n';
}
int main() {
   vector<int> v = {7,6,2,4,1 ,9,10,15,17};
   int a = 3, b = 6;
   cout<<"Sub vector is:"<<endl;
   vector<int> sub_vector = s(v, a, b);
   show(sub_vector);
   return 0;
}
Sub vector is:
4 1 9 10
Difference between Primitive and non-primitive datatypes in JavaScript?

The primitive data types are number, string, boolean, float etc. The non-primitive data types
(Reference Type) are Array, Object etc.
var number=10;
var stringValue="John";
var booleanValue=true;
var obj={};
var newArray=new Array();
console.log("The data type is="+typeof number);
console.log("The data type is="+typeof stringValue);
console.log("The data type is="+typeof booleanValue);
console.log("The data type is="+typeof obj);
console.log("The data type is="+typeof newArray);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo162.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo162.js
The data type is=number
The data type is=string
The data type is=boolean
The data type is=object
The data type is=object
Accessing each element of a collection in Julia - foreach() Method - GeeksforGeeks

26 Mar, 2020
The foreach() is an inbuilt function in julia which is used to call function f on each element of the specified iterable c.
Syntax: foreach(f, c...)
Parameters:
f: Specified set of instructions.
c: Specified iterable.
Returns: It returns the result of the operation of function f on each element of the specified iterable c.
Example 1:
# Julia program to illustrate # the use of foreach() method  # Getting the result of the operation# of function f on each element of # the specified array a.a = [1, 2, 3];foreach(x -> println(x ^ 3), a)
Output:
1
8
27

Example 2:
# Julia program to illustrate # the use of foreach() method  # Getting the result of the operation# of function f on each element of # the specified iterable c.a = 1:3;foreach(x -> println(x ^ 2), a)
Output:
1
4
9

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

24 Oct, 2019
Data Flow Testing is a type of structural testing. It is a method that is used to find the test paths of a program according to the locations of definitions and uses of variables in the program. It has nothing to do with data flow diagrams.It is concerned with:
Statements where variables receive values,
Statements where these values are used or referenced.
To illustrate the approach of data flow testing, assume that each statement in the program assigned a unique statement number. For a statement number S-
DEF(S) = {X | statement S contains the definition of X}
USE(S) = {X | statement S contains the use of X} 
If a statement is a loop or if condition then its DEF set is empty and USE set is based on the condition of statement s.
Data Flow Testing uses the control flow graph to find the situations that can interrupt the flow of the program.Reference or define anomalies in the flow of the data are detected at the time of associations between values and variables. These anomalies are:
A variable is defined but not used or referenced,
A variable is used but never defined,
A variable is defined twice before it is used
Advantages of Data Flow Testing:Data Flow Testing is used to find the following issues-
To find a variable that is used but never defined,
To find a variable that is defined but never used,
To find a variable that is defined multiple times before it is use,
Deallocating a variable before it is used.
Disadvantages of Data Flow Testing
Time consuming and costly process
Requires knowledge of programming languages
Example:
1. read x, y;
2. if(x>y)
3. a = x+1
else
4. a = y-1
5. print a; 
Control flow graph of above example:
Define/use of variables of above example:
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Software Engineering | Requirements Engineering Process
Levels in Data Flow Diagrams (DFD)
Software Engineering | Requirements Elicitation
Differences between Verification and Validation
DFD for Library Management System
Software Engineering | White box Testing
Software Testing | Basics
Software Engineering | Classification of Software Requirements
Apache Drill - COALESCE(x, y [ , y ]...)

The following program shows the query for this function −
0: jdbc:drill:zk = local> select coalesce(3,1,7) from (values(1));
+---------+
| EXPR$0  |
+---------+
|   3     |
+————————-+

Here first arg is non null, so it returns the value 3.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
PHP Operators

Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, 
such as addition, subtraction, multiplication etc.
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand 
gets set to the value of the assignment expression on the right.
The PHP comparison operators are used to compare two values (number or string):
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
The PHP logical operators are used to combine conditional statements.
PHP has two operators that are specially designed for strings.
The PHP array operators are used to compare arrays.
The PHP conditional assignment operators are used to set a value depending on conditions:
Multiply 10 with 5, and output the result.
echo 10  5;

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to Generate Unique Random Numbers in Excel? - GeeksforGeeks

09 Nov, 2021
Excel is powerful data visualization and analysis program we use to create reports or data summaries. So, sometimes happen that we have to create a report and assign a random id or number in a spreadsheet then we can create a random number without any repeat and manually.
Now, we have to generate a random number in column A, we will select  a cell and type our formula =RAND() and then press enter 
Drag the number till row you want the random number.
After that in the second column convert all the random numbers into values using
 =RANK.EQ(select random number column)
After that press enters and drag till random number.
Congratulations! You have created unique random numbers.
Download and install Kutools for excel in your system from here. 
Open excel and go to the Kutools tab and select the Insert data option.
After that enter the from and to limit for creating a random number.
Hurrah!! Your number will be printed in the spreadsheet.
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Get Length of Array in Excel VBA?
How to Remove Duplicates From Array Using VBA in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Easily Calculate the Dot Product in Excel?
Create a Pie Chart using Recharts in ReactJS - GeeksforGeeks

27 Jul, 2021

Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).  
To create Pie Chart using Recharts, we create a dataset which contains actual data. Then we define the slices using pie element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices.
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 required modules using the following command.
npm install --save recharts

Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
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 React from 'react'; 
import { PieChart, Pie} from 'recharts'; 
  
  
const App = () => { 
  
// Sample data 
const data = [ 
  {name: 'Geeksforgeeks', students: 400}, 
  {name: 'Technical scripter', students: 700}, 
  {name: 'Geek-i-knack', students: 200}, 
  {name: 'Geek-o-mania', students: 1000} 
]; 
  
  
return ( 
        <PieChart width={700} height={700}> 
          <Pie data={data} dataKey="students" outerRadius={250} fill="green" /> 
        </PieChart> 
); 
} 
  
export default App; 






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:
Output

React-Questions


Recharts


JavaScript


ReactJS


Web Technologies

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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
How to shallow copy the objects in JavaScript?

Underscore.js, a library of javascript, has introduced a method called _.extend() to shallow copy the objects in javascript. This method copy all of the properties in the source objects over to the destination object, and return the destination object. Here the reference is used to copy but not the duplication. 
_.extend(object*);
It accepts objects and shallow copy them. We can provide as many objects as we can.
In the following example, three individual objects were copied shallowly and executed in the output.
Live Demo
<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
   var res = JSON.stringify(_.extend(
      {name: 'Ram', designation: "content developer"},
      {age: 50},
      {salary: 1200000}));
      document.write((res));
   </script>
</body>
</html>
{"name":"Ram","designation":"content developer","age":50,"salary":1200000}
Live Demo
<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
      var res = JSON.stringify(_.extend(
            {name: 'Ram', designation: "content developer"},
            {age: 50,salary: 1200000},
            {country: "India"}));
      document.write((res));
   </script>
</body>
</html>
{"name":"Ram","designation":"content developer","age":50,"salary":1200000,"country":"India"}
Python | Ways to format elements of given list - GeeksforGeeks

15 Oct, 2021
Given a List of float values, the task is to truncate all float values to 2-decimal digit. Let’s see the different methods to do the task. Method #1 : Using List comprehension  
Python3
# Python code to truncate float# values to 2-decimal digits. # List initializationInput = [100.7689454, 17.232999, 60.98867, 300.83748789] # Using list comprehensionOutput = ["%.2f" % elem for elem in Input] # Printing outputprint(Output)
['100.77', '17.23', '60.99', '300.84']
 
  Method #2 : Using Map  
Python3
# Python code to truncate float# values to 2 decimal digits. # List initializationInput = [100.7689454, 17.232999, 60.98867, 300.83748789] # Using mapOutput = map(lambda n: "%.2f" % n, Input) # Converting to listOutput = list(Output) # Print outputprint(Output)
['100.77', '17.23', '60.99', '300.84']
 
  Method #3 : Using format  
Python3
# Python code to truncate float# values to 2 decimal digits. # List initializationInput = [100.7689454, 17.232999, 60.98867, 300.83748789] # Using formatOutput = ['{:.2f}'.format(elem) for elem in Input] # Print outputprint(Output)
['100.77', '17.23', '60.99', '300.84']
 
  Method #4 : Using Iteration  
Python3
# Python code to truncate float# values to 2 decimal digits. # List initializationInput = [100.7689454, 17.232999, 60.98867, 300.83748789] # Output list initializationOutput = [] # Iteratingfor elem in Input:    Output.append("%.2f" % elem) # Printing outputprint(Output)
['100.77', '17.23', '60.99', '300.84']
 
surinderdawra388
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
C++ Program for Comb Sort - GeeksforGeeks

27 Jan, 2022
Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200, 000 random lists) [Source: Wiki]Although, it works better than Bubble Sort on average, worst case remains O(n2). 
CPP
// C++ implementation of Comb Sort#include <bits/stdc++.h>using namespace std; // To find gap between elementsint getNextGap(int gap){    // Shrink gap by Shrink factor    gap = (gap * 10) / 13;     if (gap < 1)        return 1;    return gap;} // Function to sort a[0..n-1] using Comb Sortvoid combSort(int a[], int n){    // Initialize gap    int gap = n;     // Initialize swapped as true to make sure that    // loop runs    bool swapped = true;     // Keep running while gap is more than 1 and last    // iteration caused a swap    while (gap != 1 || swapped == true) {        // Find next gap        gap = getNextGap(gap);         // Initialize swapped as false so that we can        // check if swap happened or not        swapped = false;         // Compare all elements with current gap        for (int i = 0; i < n - gap; i++) {            if (a[i] > a[i + gap]) {                swap(a[i], a[i + gap]);                swapped = true;            }        }    }} // Driver programint main(){    int a[] = { 8, 4, 1, 56, 3, -44, 23, -6, 28, 0 };    int n = sizeof(a) / sizeof(a[0]);     combSort(a, n);     printf("Sorted array: \n");    for (int i = 0; i < n; i++)        printf("%d ", a[i]);     return 0;}
Sorted array: 
-44 -6 0 1 3 4 8 23 28 56
 
Please refer complete article on Comb Sort for more details! 
sumitgumber28
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
Jump Game III in C++

Suppose we have an array of non-negative integers arr, we are initially positioned at start index of the array. When we are present at index i, we can jump to i + arr[i] or i - arr[i], check if we can reach to any index with value 0. We have to keep in mind that we cannot jump outside of the array at any time. So if the input is like: arr = [4,2,3,0,3,1,2] and start from 5, then output will be true, as move 5 → 4 → 1 → 3, or 5 → 6 → 4 → 1 → 3.
To solve this, we will follow these steps −
n := size of arr
define a queue q, insert start into q, define a set called visited, and insert start into the set visited
while queue is not empty,curr := front element of q, delete front element from qif array[curr] is 0, then return trueif curr + arr[curr] < n and curr + arr[curr] is not present in visited set, theninsert curr + arr[curr] into qinsert curr + arr[curr] into visitedif curr - arr[curr] >= 0 and curr - arr[curr] is not present in visited set, theninsert curr - arr[curr] into qinsert curr - arr[curr] into visited
curr := front element of q, delete front element from q
if array[curr] is 0, then return true
if curr + arr[curr] < n and curr + arr[curr] is not present in visited set, theninsert curr + arr[curr] into qinsert curr + arr[curr] into visited
insert curr + arr[curr] into q
insert curr + arr[curr] into visited
if curr - arr[curr] >= 0 and curr - arr[curr] is not present in visited set, theninsert curr - arr[curr] into qinsert curr - arr[curr] into visited
insert curr - arr[curr] into q
insert curr - arr[curr] into visited
return false
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool canReach(vector<int>& arr, int start) {
      int n = arr.size();
      queue <int> q;
      q.push(start);
      set <int> visited;
      visited.insert(start);
      while(!q.empty()){
         int curr = q.front();
         q.pop();
         if(arr[curr] == 0)return true;
         if(curr + arr[curr] < n && !visited.count(curr + arr[curr])){
            q.push(curr + arr[curr]);
            visited.insert(curr + arr[curr]);
         }
         if(curr - arr[curr] >= 0 && !visited.count(curr - arr[curr])){
            q.push(curr - arr[curr]);
            visited.insert(curr - arr[curr]);
         }
      }
      return false;
   }
};
main(){
   vector<int> v = {4,2,3,0,3,1,2};
   Solution ob;
   cout << (ob.canReach(v, 5));
}
[4,2,3,0,3,1,2]
5
1
echo- Unix, Linux Command

echo - display a line of text.
echo [SHORT-OPTION]... [STRING]...
echo LONG-OPTION
echo is a fundamental command found in most operating systems that offer a command line. It is frequently used in scripts, batch files, 
and as part of individual commands; anywhere you may need to insert text.
Many command shells such as bash, ksh and csh implement echo as a built-in command.
Example-1:
To print string "Hello, World!" on console
$ echo "Hello, World!"
output:Hello, World!
Example-2:
To print value of x, where x=10.
$ echo $x
output:10
Example-3:
Use option ‘\b‘ – backspace with backslash interpretor ‘-e‘ removes all the spaces in between.
$ echo -e 'Here \bthe \bspaces \bare \bbackspaced.'
output:Herethespacesarebackspaced.
Example-4:
Use option ‘\n‘ – New line with backspace interpretor ‘-e‘ treats new line from where it is used.
$  echo -e 'Here \nthe \nspaces \nare \nnewlined.'
output:Herethespacesarenewlined.
Example-5:
Use option ‘\t‘ – horizontal tab with backspace interpretor ‘-e‘ to have horizontal tab spaces.
$  echo -e 'Here \tthe \tspaces \thave \thorizontal \ttab \tspaces.'
output:Here    the     spaces  have    horizontal     tab   spaces.
Example-6:
Use option ‘\v‘ – vertical tab with backspace interpretor ‘-e‘ to have vertical tab spaces.
$  echo -e 'Here \vthe \vspaces \vhave \vvertical \vtab \vspaces.'
output:Here     the         spaces                have                     vertical                              tab                                  spaces.
Example-7:
Use option ‘\r‘ – carriage return with backspace interpretor ‘-e‘ to have specified carriage return in output
$  echo -e 'Here the \rcontent before this is removed.'  
output:content before this is removed.
Example-8:
Use option ‘\c‘ – suppress trailing new line with backspace interpretor ‘-e‘ to continue without emitting new line.
$  echo -e "Here the content after "," is not printed , \c This is not printed on console"
output:Here the content after , is not printed ,
Example-9:
To print all the files/folder using echo command (ls command alternative).
ubuntu@ubuntu:/usr$ echo *
output:bin games include lib local sbin share src
Example-10:
To echo output to a file and not standard output. in below example output is redirected to test file.
$ echo "Hello World!" > test
output:$ cat testHello World!

    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
Split a string in equal parts (grouper in Python)

In this tutorial, we are going to write a program that splits the given string into equal parts. Let's
see an example.
string = 'Tutorialspoint' each_part_length = 5
Tutor ialsp ointX
string = 'Tutorialspoint' each_part_length = 6
Tutori alspoi ntXXXX

We are going to use the zip_longest method from the itertools module to achieve the result.
The method zip_longest takes iterators as argument. We can also pass the fillvalue for partitioning the string. It will return list of tuples that contains characters of equal number.
The zip_longest return a tuple on each iteration until the longest iterator in the given in exhausted. And the tuple contains given length of characters from the iterators.
 Live Demo
# importing itertool module
import itertools
# initializing the string and length
string = 'Tutorialspoint'
each_part_length = 5
# storing n iterators for our need
iterator = [iter(string)] * each_part_length
# using zip_longest for dividing
result = list(itertools.zip_longest(*iterator, fillvalue='X'))
# converting the list of tuples to string
# and printing it
print(' '.join([''.join(item) for item in result]))
If you run the above code, then you will get the following result.
Tutor ialsp ointX
 Live Demo
# importing itertool module
import itertools
# initializing the string and length
string = 'Tutorialspoint'
each_part_length = 6
# storing n iterators for our need
iterator = [iter(string)] * each_part_length
# using zip_longest for dividing
result = list(itertools.zip_longest(*iterator, fillvalue='X'))
# converting the list of tuples to string
# and printing it
print(' '.join([''.join(item) for item in result]))
If you run the above code, then you will get the following result.
Tutori alspoi ntXXXX
If you have doubts in the tutorial, mention them in the comment section.
C Program to validate an IP address

In this program we will see how to validate an IP address using C. The IPv4 addresses are represented in dot-decimal notation. There are four decimal numbers (all are ranging from 0 to 255). These four numbers are separated by three dots.
An example of a valid IP is: 192.168.4.1
To validate the IP address we should follow these steps
Tokenize the string (IP address) using the dot “.” delimiter
Tokenize the string (IP address) using the dot “.” delimiter
If the sub strings are containing any non-numeric character, then return false
If the sub strings are containing any non-numeric character, then return false
If the number in each token is not in range 0 to 255, then return false
If the number in each token is not in range 0 to 255, then return false
If there are exactly three dots and four parts then it is a valid IP address
If there are exactly three dots and four parts then it is a valid IP address
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int validate_number(char *str) {
   while (*str) {
      if(!isdigit(*str)){ //if the character is not a number, return
         false
         return 0;
      }
      str++; //point to next character
   }
   return 1;
}
int validate_ip(char *ip) { //check whether the IP is valid or not
   int i, num, dots = 0;
   char *ptr;
   if (ip == NULL)
      return 0;
      ptr = strtok(ip, "."); //cut the string using dor delimiter
      if (ptr == NULL)
         return 0;
   while (ptr) {
      if (!validate_number(ptr)) //check whether the sub string is
         holding only number or not
         return 0;
         num = atoi(ptr); //convert substring to number
         if (num >= 0 && num <= 255) {
            ptr = strtok(NULL, "."); //cut the next part of the string
            if (ptr != NULL)
               dots++; //increase the dot count
         } else
            return 0;
    }
    if (dots != 3) //if the number of dots are not 3, return false
       return 0;
      return 1;
}
int main() {
   char ip1[] = "192.168.4.1";
   char ip2[] = "172.16.253.1";
   char ip3[] = "192.800.100.1";
   char ip4[] = "125.512.100.abc";
   validate_ip(ip1)? printf("Valid\n"): printf("Not valid\n");
   validate_ip(ip2)? printf("Valid\n"): printf("Not valid\n");
   validate_ip(ip3)? printf("Valid\n"): printf("Not valid\n");
   validate_ip(ip4)? printf("Valid\n"): printf("Not valid\n");
}
Valid
Valid
Not valid
Not valid
HTML DOM Input Range value property

The HTML DOM Input range value property is associated with the input element having type=”range” and the value attribute. It is used to return the value of slider control value attribute or to set it. The value attribute can be the default value or the value set by dragging the slider.
Following is the syntax for −
Setting the value property −
rangeObject.value = text;
Here, text is used for specifying the value for the range slider control.
Let us look at an example for the input range value property −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Input range Value property</h1>
<form>
VOLUME <input type="range" id="RANGE1" name="VOL">
</form>
<p>Get the above element value by clicking the below button</p>
<button onclick="getValue()">Get Value</button>
<p id="Sample"></p>
<script>
   function getValue() {
      var t = document.getElementById("RANGE1").value;
      document.getElementById("Sample").innerHTML = "The value for the radio button is : "+t;
   }
</script>
</body>
</html>
This will produce the following output −
On clicking the “Get Value” button −
In the above example −
We have created an input field contained inside a form having type=“range”, id=“RANGE1”, name=“VOL” −
<form>
VOLUME <input type="range" id="RANGE1" name="VOL">
<form>
We have then created a button “Get Value” that will execute the getValue() method when clicked by the user −
<button type="button" onclick="getValue()">Get Value</button>
The getValue() method gets the input element using the getElementById() method and assigns its “value” attribute value to variable t. This variable is then displayed in the paragraph with id “Sample” using its innerHTML property −
function getValue() {
   var t = document.getElementById(“RANGE1").value;
   document.getElementById("Sample").innerHTML = "The value for the input field is : "+t;
}
spaCy - Doc.noun_chunks Property

This doc property is used to iterate over the base noun phrases in a particular document. If the document has been syntactically parsed, then this property will yield base noun-phrase Span objects.
An example of Doc.noun_chunks property is as follows −
import spacy
nlp_model = spacy.load("en_core_web_sm")
doc = nlp_model("The website is Tutorialspoint.com.")
chunks = list(doc.noun_chunks)
chunks[0].text
The output is mentioned below −
'The website'

Here is an example of Doc.noun_chunks property −
chunks[1].text
'Tutorialspoint.com'

 Print
 Add Notes
 Bookmark this page
mapfile Command in Linux With Examples - GeeksforGeeks

09 Apr, 2021
mapfile also called (read array) is a command of the Bash shell used to read arrays. It reads lines from the standard input into an array variable. Also, mapfile must read from substitution (< <) and not from a pipe. Also, mapfile is faster and more convenient when compared to a read loop. It returns 1 or 0 depending on whether the command was successful or not. If no array name is not specified, the default variable MAPFILE is used as the target array variable.
Syntax: mapfile [array]
Alternatively, we can use read array [arrayname] instead of mapfile.
Example 1. Reading an array from a file:
$ mapfile MYFILE < example.txt
$ echo ${MYFILE[@]}
$ echo ${MYFILE[0]}
Output:
Example 2. Capture the output into an array:
$ mapfile GEEKSFORGEEKS < <(printf "Item 1\nItem 2\nItem 3\n")
$ echo  ${GEEKSFORGEEKS[@]}
Here, Item1, Item2, and Item 3 have been stored in the array GEEKSFORGEEKS.
Output:
Example 3. Strip newlines and store item using -t:
$ mapfile -t GEEKSFORGEEKS< <(printf "Item 1\nItem 2\nItem 3\n")
$ printf "%s\n" "${GEEKSFORGEEKS[@]}"
Output:
Example 4. Read the specified number of lines using -n:
$ mapfile -n 2 GEEKSFORGEEKS < example.txt
$ echo  ${GEEKSFORGEEKS[@]}
It reads at most 2 lines. If 0 is specified then all lines are considered.
Output:
linux-command
Shell
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Finding all subsets of a given set in Java - GeeksforGeeks

30 May, 2021
Problem: Find all the subsets of a given set.
Input: 
S = {a, b, c, d}
Output:
{}, {a} , {b}, {c}, {d}, {a,b}, {a,c},
{a,d}, {b,c}, {b,d}, {c,d}, {a,b,c}, 
{a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d}
The total number of subsets of any given set is equal to 2^ (no. of elements in the set). If we carefully notice it is nothing but binary numbers from 0 to 15 which can be shown as below:  
 
Starting from right, 1 at ith position shows that the ith element of the set is present as 0 shows that the element is absent. Therefore, what we have to do is just generate the binary numbers from 0 to 2^n – 1, where n is the length of the set or the numbers of elements in the set.
 
Java
// A Java program to print all subsets of a setimport java.io.IOException; class Main{    // Print all subsets of given set[]    static void printSubsets(char set[])    {        int n = set.length;         // Run a loop for printing all 2^n        // subsets one by one        for (int i = 0; i < (1<<n); i++)        {            System.out.print("{ ");             // Print current subset            for (int j = 0; j < n; j++)                 // (1<<j) is a number with jth bit 1                // so when we 'and' them with the                // subset number we get which numbers                // are present in the subset and which                // are not                if ((i & (1 << j)) > 0)                    System.out.print(set[j] + " ");             System.out.println("}");        }    }     // Driver code    public static void main(String[] args)    {        char set[] = {'a', 'b', 'c'};        printSubsets(set);    }}
Output:  
{ }
{ a }
{ b }
{ a b }
{ c }
{ a c }
{ b c }
{ a b c }
Time complexity: O(n * (2^n)) as the outer loop runs for O(2^n) and the inner loop runs for O(n). Related Post: Finding all subsets of a Set in C/C++This article is contributed by Nikhil Tekwani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
ruhulazam1
moonlight23
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays