code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas dataframe.mod() - GeeksforGeeks

23 Jul, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.mod() function returns modulo of dataframe and other, element-wise (binary operator mod). This function is essentially same as the Dataframe % other, but with support to substitute a fill_value for missing data in one of the inputs. This function can be used with either a series or a dataframe. 
Syntax: DataFrame.mod(other, axis=’columns’, level=None, fill_value=None) Parameters : Other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex level fill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missingReturns : result : DataFrame 
Example #1: Use mod() function to find the modulo of each value in the dataframe withe a constant. 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[12, 4, 5, 44, 1],                   "B":[5, 2, 54, 3, 2],                   "C":[20, 16, 7, 3, 8],                   "D":[14, 3, 17, 2, 6]}) # Print the dataframedf
Lets use the dataframe.mod() function to find the modulo of dataframe with 3  
Python3
# find mod of dataframe values with 3df.mod(3)
Output :  
  Example #2: Use mod() function to find the modulo with a series over the column axis.  
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[12, 4, 5, 44, 1],                   "B":[5, 2, 54, 3, 2],                   "C":[20, 16, 7, 3, 8],                   "D":[14, 3, 17, 2, 6]}) # Print the dataframedf
Let’s create the series object 
Python3
# create a seriessr = pd.Series([3, 2, 4, 5]) # setting its column index similar to the dataframesr.index =["A", "B", "C", "D"] # print the seriessr
Lets use the dataframe.mod() function to find the modulo of dataframe with series  
Python3
# find mod of dataframe values with series# axis = 1 indicates column axisdf.mod(sr, axis = 1)
Output :  
 
sagar0719kumar
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
How to control PC from anywhere using Python? - GeeksforGeeks

12 Jul, 2021
Prerequisite – Socket programming in Python
In this solution, we use the concept of Socket Programming for establishing communication between two computers. 
Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are the endpoints built for sending and receiving data and it is a combination of IP address and port. We will import the socket module to use Socket Programming in Python. The following are the methods required to build the solution:
Methods in Socket Module:
Other Socket Methods:
So we have to develop two python programs one is master.py (server)and another is slave.py (client), using master.py we can control the system having slave.py program. To control the pc from anywhere using python please the follow the step mentioned below:
Step 1: Create and Execute the “master.py” in one terminal
Python3
import timeimport socketimport sysimport os # Initialize s to sockets = socket.socket() # Initialize the hosthost = socket.gethostname() # Initialize the portport = 8080 # Bind the socket with port and hosts.bind(('', port)) print("waiting for connections...") # listening for connectionss.listen() # accepting the incoming connectionsconn, addr = s.accept() print(addr, "is connected to server") # take command as inputcommand = input(str("Enter Command :")) conn.send(command.encode()) print("Command has been sent successfully.") # receive the confirmationdata = conn.recv(1024) if data:    print("command received and executed successfully.")
Step 2: Create and Execute the “slave.py” is another terminal
Python3
import timeimport socketimport sysimport os # Initialize s to sockets = socket.socket() # Initialize the hosthost = "127.0.0.1" # Initialize the portport = 8080 # bind the socket with port and hosts.connect((host, port)) print("Connected to Server.") # receive the command from master programcommand = s.recv(1024)command = command.decode() # match the command and execute it on slave systemif command == "open":    print("Command is :", command)    s.send("Command received".encode())         # you can give batch file as input here    os.system('ls')
Output:
terminal running master.py
terminal running slave.py
adnanirshad158
saurabh1990aror
sooda367
Python-socket
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
How to escape single quotes in MySQL?

We can escape single quotes with the help of the SELECT statement. For instance, when single quotes are encountered in a name, eg. “Carol’s”.
Let us see the syntax.
SELECT ‘SomeValue’;
Here is an example that display how to include text with single quotes.
mysql> SELECT 'Carol\'s Taylor.';
The following is the output.
+-------------------+
| Carol's Taylor    |
+-------------------+
| Carol's Taylor    |
+-------------------+
1 row in set (0.00 sec)
How to extract data from a string with Python Regular Expressions?

The following code extracts data like first_id, second_id, category from given strings
import re
s = 'TS001B01.JPG'
match = re.match(r'(TS\d+)([A|B])(\d+)\.JPG', s)
first_id = match.group(1)
category = match.group(2)
second_id = match.group(3)
print first_id
print category
print second_id
This gives output
TS001
B
01
How to remove a list of characters in string in Python?

The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:
>>> "Hello people".replace("e", "")
"Hllo popl"
If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:
>>> import re
>>> re.sub("e|l", "", "Hello people")
"Ho pop"
If you already have the characters you want to remove in a list, you can use join() to create the regex as well. For Example,
>>> import re
>>> char_list = ['a', 'e', 'i', 'o', 'u']
>>> re.sub("|".join(char_list), "", "Hello people")
"Hll ppl"
Note: You can also use the [] to create group of characters to replace in regex.
Prime numbers and Fibonacci in C++

In this problem, we are given a number n. Our task is to print all prime and Fibonacci numbers less than or equal to n.
Let’s take an example to understand the problem
Input: n = 30
Output: 2 3 5 13
Explanation
Fibonacci numbers less than 30 are : 1 1 2 3 5 8 13 21.
Out of these numbers, prime numbers are 2 3 5 13.
To solve this problem, we have to check if all numbers of the Fibonacci series less than n is a prime number.
For this, we will find all prime numbers less than or equal to n. And check if the generated numbers are contained in the Fibonacci series or not.
If a number is in the Fibonacci series, then it is in form 5i2 + 4 or 5i2 - 4.
Program to show the implementation of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isSquare(int n) {
   int sr = sqrt(n);
   return (sr * sr == n);
}
void printPrimeAndFibnacciNumbers(int n) {
   bool primeNumbers[n + 1];
   memset(primeNumbers, true, sizeof(primeNumbers));
   for (int p = 2; p * p <= n; p++) {
      if (primeNumbers[p] == true) {
         for (int i = p * 2; i <= n; i += p)
            primeNumbers[i] = false;
      }
   }
   for (int i=2; i<=n; i++)
   if (primeNumbers[i] && (isSquare(5*i*i+4) > 0 || isSquare(5*i*i-4) > 0))
      cout<<i<<"\t";
}
int main() {
   int N = 50;
   cout<<"All prime Fibonacci numbers less than "<<N<<" are :\n";
   printPrimeAndFibnacciNumbers(N);
   return 0;
}
All prime Fibonacci numbers less than 50 are :
23513
Smallest Distance Between Two Words in Python

Suppose we have two strings, word0, and word1 and a text. We have to find the smallest
distance between any two occurrences of word0 and word1 in the given text. Here the distance
is measured in number of words. If they are not present in the text then return -1.
So, if the input is like text = "cat dog abcd dog cat cat abcd dog wxyz", word0 = "abcd", word1 =
"wxyz", then the output will be 1, as there is one word "dog" between "abcd" and "wxyz"
To solve this, we will follow these steps −
word_list := a list of words from text
ans := size of word_list
L := null
for R in range 0 to size of word_list - 1, doif word_list[R] is word0 or word_list[R] is word1, thenif L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1L := R
if word_list[R] is word0 or word_list[R] is word1, thenif L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1L := R
if L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1
ans := minimum of ans and R - L - 1
L := R
return -1 if ans is same as size of word_list otherwise ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, text, word0, word1):
      word_list = text.split()
      ans = len(word_list)
      L = None
      for R in range(len(word_list)):
         if word_list[R] == word0 or word_list[R] == word1:
            if L is not None and word_list[R] != word_list[L]:
               ans = min(ans, R - L - 1)
               L = R
      return -1 if ans == len(word_list) else ans
ob = Solution()
text = "cat dog abcd dog cat cat abcd dog wxyz"
word0 = "abcd"
word1 = "wxyz"
print(ob.solve(text, word0, word1))
"cat dog abcd dog cat cat abcd dog wxyz", "abcd", "wxyz"
1
Implementing Linear Search in JavaScript

Following is the code for implementing linear search in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample{
      color:red;
   }
</style>
</head>
<body>
<h1>Implementing linear search</h1>
<div class="sample">[1,19,5,11,22,55]</div><br>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to search for 22 in the above array</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let arr = [1,19,5,11,22,55];
   BtnEle.addEventListener("click", () => {
      for(let i=0;i<arr.length;i++){
         if(arr[i]===22){
            resEle.innerHTML = 'Element found at : '+i;
            break;
         }
      }
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
UUID timestamp() Method in Java with Examples

27 Dec, 2018
The timestamp() method of UUID class in Java is generally used to get the stamp value associated with a particular UUID.
Syntax:
public long timestamp()
Parameters: This method does not take any parameter.
Return Value: This method returns the time stamp value of this UUID.
Exception: This method throws UnsupportedOperationException if this UUID is not a part of version 1 UUID.
Below programs illustrate the working of timestamp() method:
Program 1:
// Java code to illustrate timestamp() method  import java.util.*;  public class UUID_Demo {    public static void main(String[] args)    {          // Creating two UUIDs        UUID UUID_1            = UUID                  .fromString(                      "58e0a7d7-eebc-11d8-9669-0800200c9a66");          // Displaying the UUID        System.out.println("UUID: "                           + UUID_1);          // Displaying the timestamp value        System.out.println("The timestamp value is: "                           + UUID_1.timestamp());    }}
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The timestamp value is: 133118681719810007

Program 2:
// Java code to illustrate timestamp() method  import java.util.*;  public class UUID_Demo {    public static void main(String[] args)    {          // Creating two UUIDs        UUID UUID_1            = UUID                  .fromString(                      "5fc03087-d265-11e7-b8c6-83e29cd24f4c");          // Displaying the UUID        System.out.println("UUID: "                           + UUID_1);          // Displaying the timestamp Value        System.out.println("The timestamp value is: "                           + UUID_1.timestamp());    }}
UUID: 5fc03087-d265-11e7-b8c6-83e29cd24f4c
The timestamp value is: 137309646498050183

Java - util package
Java-Functions
Java-UUID
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.diff()

20 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.diff() is used to find the first discrete difference of objects over the given axis. We can provide a period value to shift for forming the difference.
Syntax: DataFrame.diff(periods=1, axis=0)
Parameters:periods : Periods to shift for forming differenceaxis : Take difference over rows (0) or columns (1).
Returns: diffed : DataFrame
Example #1: Use diff() function to find the discrete difference over the index axis with period value equal to 1.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                    "C":[4, 3, 8, 5],                   "D":[5, 4, 2, 8]})  # Print the dataframedf
Now find the discrete difference over the index axis.
# To find the discrete differencedf.diff(axis = 0, periods = 1)
Output :
The output is a dataframe with cells containing the discrete difference over the index axis. The value present in each cell is the difference of current cell value with the previous row corresponding cell. Notice, the first row is NaN filled. This is because there is no row above that to find the difference with so it is treated as NaN. 
Example #2: Use diff() function to find the discrete difference over the column axis with period value equal to 1.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                    "C":[4, 3, 8, 5],                    "D":[5, 4, 2, 8]})  # To find the discrete differencedf.diff(axis = 1, periods = 1)
Output :
The output is a dataframe with cells containing the discrete difference over the column axis. The value present in each cell is the difference of current cell value with the previous column corresponding cell. Notice, the first column is NaN filled. This is because there is no column to the left of it to find the difference with so it is treated as NaN.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Convert integer to string in Python
How to sort strings in JavaScript?

17 Jun, 2019
We can sort the strings in JavaScript by following methods described below:
Using sort() method
Using loop
Using sort() method: In this method, we use predefined sort() method of JavaScript to sort the array of string. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method.
Examples:
Original StringSuraj, Sanjeev, Rajnish, Yash, RaviAfter sortingRajnish, Ravi, Sanjeev, Suraj, Yash
Original String40, 100, 1, 5, 25, 10After sorting1, 10, 100, 25, 40, 5
Below program illustrates the above approach:
Program:
<script>// JavaScript code to sort strings      // Original stringvar string = ["Suraj", "Sanjeev", "Rajnish", "Yash", "Ravi"];      // Print original string arraydocument.write("Original String</br>");document.write(string);      document.write("</br>");      // Use sort() method to sort the stringsstring.sort();      document.write("</br>After sorting</br>");      // Print sorted string arraydocument.write(string);      </script>                    
Output:
Original String
Suraj, Sanjeev, Rajnish, Yash, Ravi

After sorting
Rajnish, Ravi, Sanjeev, Suraj, Yash

Using loop: We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array.Examples:
Original StringSuraj,Sanjeev,Rajnish,Yash,RaviAfter sortingRajnish,Ravi,Sanjeev,Suraj,Yash
Original String40, 100, 1, 5, 25, 10After sorting1,5,10,25,40,100
Below program illustrates the above approach:
Program:
<script>// JavaScript code to sort the strings  // Function to perform sortfunction string_sort(str) {    var i = 0, j;    while (i < str.length) {        j = i + 1;        while (j < str.length) {            if (str[j] < str[i]) {                var temp = str[i];                str[i] = str[j];                str[j] = temp;            }            j++;        }        i++;    }}      // Driver code      // Original stringvar string = ["Suraj", "Sanjeev", "Rajnish", "Yash", "Ravi"];      // Print original string arraydocument.write("Original String</br>");document.write(string);      document.write("</br>");      // Call string_sort methodstring_sort(string);      document.write("</br>After sorting</br>");      // Print sorted string arraydocument.write(string);      </script>                                  
Output:
Original String
Suraj, Sanjeev, Rajnish, Yash, Ravi

After sorting
Rajnish, Ravi, Sanjeev, Suraj, Yash

javascript-string
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to save connection result in a variable in Node.js ?

07 Apr, 2021
We are going to use the query function in MySQL library in node.js that will return our output as expected. Using this approach, we can save connection result in a variable in Node.js.
Setting up environment and Execution:
Step 1: Initialize node project using the following command.
npm init
Step 2: Turn on MySQL Database
Step 3: After creating the NodeJS application, Install the mysql module using the following command.
npm install mysql
Database Table: Our sample gfg_table database with look like this.
Step 4: Create an index.js file with the following code.
index.js
const mysql = require("mysql");  var db_con = mysql.createConnection({    host: "localhost",    user: "root",    password: "",    database: "gfg_db"});  let output;  const setOutput = (rows) => {    output = rows;    console.log(output);}  db_con.connect(async(err) => {    if (err) {        console.log("Database Connection Failed !!!", err);        return;    }      console.log("Connected to Database");      let query = 'SELECT * FROM users';    db_con.query(query, (err, rows) => {        if (err) {            console.log("internal error", err);            return;        }                  // This is the important function        setOutput(rows);    });});
Step 5: Run the index.js file using the following command.
node index.js
Output:
Node.js-Methods
NodeJS-MySQL
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How can I plot a single point in Matplotlib Python?

To plot a single data point in matplotlib, we can take the following steps −
Initialize a list for x and y with a single value.
Initialize a list for x and y with a single value.
Limit X and Y axis range for 0 to 5.
Limit X and Y axis range for 0 to 5.
Lay out a grid in the current line style.
Lay out a grid in the current line style.
Plot x and y using plot() method with marker="o", markeredgecolor="red", markerfacecolor="green".
Plot x and y using plot() method with marker="o", markeredgecolor="red", markerfacecolor="green".
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [4]
y = [3]
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.grid()
plt.plot(x, y, marker="o", markersize=20, markeredgecolor="red", markerfacecolor="green")
plt.show()
CSS Buttons - bttn.css Usage

bttn.css library provides a huge collection of simple styles for buttons. This library is completely free for both personal and commercial use. These buttons can be customized easily.
To load the btns.css library, go to the link btns.css and paste the following line in the <head> section of the webpage.
<head>
   <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
</head>

Create a button using html button tag and add styles bttn-slant, bttn-royal with size specifier bttn-lg.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
   </head>
   
   <body>
      <button class = "bttn-slant">Submit</button>
   </body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
   </head>
   
   <body>
      <button class = "bttn-pill bttn-lg">Large</button>
      <button class = "bttn-pill bttn-md">Medium</button>
      <button class = "bttn-pill bttn-sm">Small</button>
      <button class = "bttn-pill bttn-xs">Extra Small</button>
   </body>
</html>
It will produce the following output −
Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
   </head>
   
   <body>
      <button class = "bttn-pill bttn-lg bttn-primary">Primary</button>
      <button class = "bttn-pill bttn-md bttn-warning">Warning</button>
      <button class = "bttn-pill bttn-sm bttn-danger">Danger</button>
      <button class = "bttn-pill bttn-xs bttn-success">Success</button>
      <button class = "bttn-pill bttn-xs bttn-royal">Royal</button>
   </body>
</html>
It will produce the following output −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Pascal - Multi-dimensional Array

Pascal programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −
type 
   array-identifier = array [index-type1, index-type2, ...] of element-type;
var
   a1, a2, ... : array-identifier;
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
var
   threedim: array[1..5, 1..10, 1..4] of integer;
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x, y you would write something as follows −
var
   arrayName: array[1..x, 1..y] of element-type;
Where element-type can be any valid Pascal data type and arrayName will be a valid Pascal identifier. A two-dimensional array can be visualized as a table, which will have x number of rows and y number of columns. A 2-dimensional array that contains three rows and four columns can be shown as below −
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Multidimensional arrays, like one-dimensional array, are initialized by through assignment, either by specifying a particular subscript or using a for-do loop.
For example,
var
   a: array [0..3, 0..3] of integer;
   i, j : integer;

begin  
   for i:= 0 to 3 do  
      for j:= 0 to 3 do  
         a[i,j]:= i * j;  
   ...
end;  
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −
var
   val: integer;
   val := a[2, 3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two-dimensional array −
program ex2dimarray;
var 
   a: array [0..3, 0..3] of integer;
   i,j : integer;  

begin  
   for i:=0 to 3 do
      for j:=0 to 3 do
         a[i,j]:= i * j;  
   
   for i:=0 to 3 do
   begin  
      for j:=0 to 3 do  
         write(a[i,j]:2,' ');  
      writeln;  
   end;  
end.
When the above code is compiled and executed, it produces the following result −
0 0 0 0
0 1 2 3
0 2 4 6
0 3 6 9

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
C library function - gets()

The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.
Following is the declaration for gets() function.
char *gets(char *str)
str − This is the pointer to an array of chars where the C string is stored.
str − This is the pointer to an array of chars where the C string is stored.
This function returns str on success, and NULL on error or when end of file occurs, while no characters have been read.
The following example shows the usage of gets() function.
#include <stdio.h>

int main () {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return(0);
}
Let us compile and run the above program that will produce the following result −
Enter a string : tutorialspoint.com
You entered: tutorialspoint.com


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to Protect Files and Directories from Deleting in Linux

Are you working as a Linux Admin? Do you generally defend script documents or any important files? You might be aware that, Chattr (change Attribute) is a command line Linux utility that is used to set/unset exact attributes to a file in Linux process to comfortable unintended deletion or change of major files and folders, although you’re logged in as a root user.
This article helps you to look after your records or folders that may support in disallowing an unauthorized user to delete your touchy contents.
In the below example abc.txt is the file name
To protect file, use the following command –
$ sudo chattr +i abc.txt
Now try to remove file, using rm command as shown below –
$ rm abc.txt
The sample output should be like this –
rm: remove write-protected regular file 'abc.txt'?
To remove the protection to file, use the following command –
$ sudo chattr -i abc.txt

To verify the above command, use the following command as shown below-
$ rm abc.txt
The above command removes the file without giving information.
In the below example abc is a directory name
To protect directory, use the following command –
$ sudo chattr -R +i abc
To verify the above command, use the following command as shown below –
$ rm -r abc
The sample output should be like this –
rm: descend into write-protected directory 'abc'?

To remove protection to the directory, use the following command-
$ sudo chattr -R -i abc
To verify the above command, use the following command as shown below –
$ rm -r abc
The above command remove the file without giving information.
In the above article, we have learnt about – Learn how to protect files & directories from delete. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
Deploying a Simple UI for Python. Streamlit Sharing: A Python Project... | by Max Reynolds | Towards Data Science

Creating a user interface for a Python project is seamless with Streamlit, a relatively new browser-based Python framework that lets you elegantly showcase a project without writing any HTML, CSS, or Javascript code.
Now, with Streamlit Sharing, you can deploy your project for free without needing to spin up a server or use any cloud services like Heroku.
In previous articles, we built a simple maze-solver app. In short, it allows users to upload an image of a maze and it shows a solution. A few of the Streamlit features used to facilitate user interaction are:
For a more in-depth look at how Streamlit features are implemented for this app:
towardsdatascience.com
Streamlit recently introduced the Streamlit Sharing service to facilitate deployment of Streamlit projects. Using the service requires a few quick steps.
You can create this using the following command while in your project’s environment:
pip freeze > requirements.txt
Create a public repository for your project and be sure to commit the requirements.txt in addition to any project files.
Here’s a primer on creating a repository if you have not used Github.
While the service is still in its early stages, you can request access here. I received access from the Streamlit team in less than 24 hours.
Once you receive the access email, sign in to share.streamlit.io with your current GitHub account.
Once you are signed in hit “New App” and enter the repository information.
Note: If your python dependencies require OS-level packages you may need to add a packages.txt file to your repository. For example, using the OpenCV Python library with Streamlit requires the host server to install ffmpeg.
In this lesson, we quickly deployed a Python project for free using Streamlit Sharing. You can view the final, deployed app here as well as all of the source code on Github.
To learn more about the algorithm behind the maze solver, or how to use Streamlit to create a friendly web interface using very few lines of Python code, check out Parts I and II of this series.
towardsdatascience.com
towardsdatascience.com
Registering for Medium membership supports my work.
Python Program for Fibonacci numbers

24 May, 2022
The Fibonacci numbers are the numbers in the following integer sequence.0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation 
    Fn = Fn-1 + Fn-2
with seed values  
   F0 = 0 and F1 = 1.
Method 1 ( Use recursion ) :  
Python3
# Function for nth Fibonacci numberdef Fibonacci(n):       # Check if input is 0 then it will    # print incorrect input    if n < 0:        print("Incorrect input")     # Check if n is 0    # then it will return 0    elif n == 0:        return 0     # Check if n is 1,2    # it will return 1    elif n == 1 or n == 2:        return 1     else:        return Fibonacci(n-1) + Fibonacci(n-2) # Driver Programprint(Fibonacci(9)) # This code is contributed by Saket Modi# then corrected and improved by Himanshu Kanojiya
34

Method 2 ( Use Dynamic Programming ) :  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Python3
# Function for nth fibonacci# number - Dynamic Programming# Taking 1st two fibonacci numbers as 0 and 1FibArray = [0, 1] def fibonacci(n):       # Check is n is less    # than 0    if n < 0:        print("Incorrect input")             # Check is n is less    # than len(FibArray)    elif n < len(FibArray):        return FibArray[n]    else:               FibArray.append(fibonacci(n - 1) + fibonacci(n - 2))        return FibArray[n] # Driver Programprint(fibonacci(9)) # This code is contributed by Saket Modi
34

Method 3 ( Space Optimized):  
Python
# Function for nth fibonacci# number - Space Optimisation# Taking 1st two fibonacci numbers as 0 and 1 def fibonacci(n):    a = 0    b = 1         # Check is n is less    # than 0    if n < 0:        print("Incorrect input")             # Check is n is equal    # to 0    elif n == 0:        return 0           # Check if n is equal to 1    elif n == 1:        return b    else:        for i in range(1, n):            c = a + b            a = b            b = c        return b # Driver Programprint(fibonacci(9)) # This code is contributed by Saket Modi# Then corrected and improved by Himanshu Kanojiya
34

Please refer complete article on Program for Fibonacci numbers for more details! 
grohith70
himanshukanojiya
adnanirshad158
akshaysingh98088
simranarora5sos
amartyaghoshgfg
andreyneyvanov
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to add two numbers
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Python program to find sum of elements in list
Python Program for Bubble Sort
Add a key:value pair to dictionary in Python
Publish Jupiter Notebook File as Web App

08 Jan, 2021
In Jupyter Notebook we always build some models, do some plotting on given Dataset, and many more. But we can also publish our Jupyter file as a web-app. It will show only the output of each code rather than showing the source code. 
In this article, we will look into the process of publishing a Jupyter Notebook file on Github as a Web-app.
To convert Jupyter Notebook file into an HTML file follow the below steps:
Step 1: Open Jupyter Notebook and Click the three-dot menu in the top left corner and select Python.
Step 2: Write some useful code. It may be Markdown or Code shell. For example, here we have written some markdown cells, one arithmetic code, and a CSV file’s data read code.
Markdown Cell
Code Cell
Step 3: Make a copy of the notebook.
Step 4: Remove all Markdown cells that are not necessary.
Step 5: Run only those cells whose output you want to display as a web-app. Because only display output will be shown in our web-app.
Step 6: To prevent other outputs from being displayed, just add a semicolon at the end of the code and rerun the kernel. For example, here, to prevent the display of the output of data.head(), we have added a “;” at the line of code.
Step 7: Save your notebook. Note that it is in the same directory as your Jupyter lab installation.
Step 8: Open the terminal and run the below command:
jupyter nbconvert Your-File-Name.ipynb --no-input --no-prompt
 You will now have a file named ‘Your-File-Name.html’
After the HTML file is generated, publish it on Github using the below steps:
Step 1: Create a GitHub repository (index.html) and ensure that you initialize it with a read.me file.
Login to your GitHub account
Go to Home Page
Click on the + Nav option
Create a new repository.
Step 2: Once the repository is ready, rename our GeeksForGeeks.html (Which we have created in step 1) file to ‘index.html’. Make sure your file and dashboard name is the same else it will not show up.
Step 3: Once all files are successfully uploaded, remove all content from the read.me file. (Do not delete the file, it just needs to be empty).To upload your file: 
Go to your repository.
Click on Add file.
Upload the files.
Step 4: Go to the settings of your repository and enable GitHub pages. To do so follow the below steps:
Go to setting.
Select Branch option as main.
Click on save.
This will publish our website.
Step 5: Visit the link of the newly created GitHub page and your dashboard should appear.
Note: It is mandatory to publish your HTML file as index.html.
      Otherwise, you may receive erroneous output.
Output:
Technical Scripter 2020
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dispatch Decorator in Python

08 May, 2020
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.
Example:
# defining a decorator def hello_decorator(func):         # inner1 is a Wrapper function in      # which the argument is called             # inner function can access the outer local     # functions like in this case "func"     def inner1():         print("Hello, this is before function execution")             # calling the actual function now         # inside the wrapper function.         func()             print("This is after function execution")                 return inner1         # defining a function, to be called inside wrapper def function_to_be_used():     print("This is inside the function !!")         # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used)         # calling the function function_to_be_used() 
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution

A Dispatch decorator is used to select between different implementations of the same abstract method based on the signature, or list of types.
Example:
# Python program to demonstrate# dispatch decorator  from multipledispatch import dispatch    @dispatch(int)def func(x):    return x * 2  @dispatch(float)def func(x):    return x / 2  # Driver codeprint(func(2))print(func(2.0))
Output:
4
1.0
In the above example, the @dispatch(int) statement suggests that the Dispatcher ‘func’ is created and then allocates the ‘int’ type as the key and dispatcher ‘func’ as the value and allocates it to the ith index in the namespace (dictionary).
Now you all must be wondering what is a namespace? Don’t worry let’s have a look at the namespace.
A namespace is nothing but a dictionary that is used by the dispatch decorator. The dispatch decorator creates a dispatcher object with the name of the function and stores this object as a key-value pair. This dictionary is used to map a functions like func in the above example to a dispatcher object like Disptacher('func').
By default, the namespace used is the global namespace in multipledispatch.core.global_namespace. For additional security, one can establish their own namespaces using a dictionary.
Example:
from multipledispatch import dispatch    nsp = {}  @dispatch(int, namespace = nsp)def func(x):    return x * 2  @dispatch(float, namespace = nsp)def func(x):    return x / 2  # Driver codeprint(func(2))print(func(2.0))print(nsp)
Output:
4
1.0
{'func': <dispatched func>}
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Automate Google Search using Selenium

11 May, 2020
Google search can be automated using Python script in just 2 minutes. This can be done using selenium (a browser automation tool). Selenium is a portable framework for testing web applications. It can automatically perform the same interactions that any you need to perform manually and this is a small example of it. Mastering Selenium will help you automate your day to day tasks like controlling your tweets, Whatsapp texting and even just googling without actually opening a browser in just 15-30 lines of python code. The limits of automation is endless with selenium.
Seleniumpip install selenium  
Chrome browserChromedriverDownload the chrome browser from here (choose the version for your system)After downloading, extract it and then copy the file in the folder of the script.
Seleniumpip install selenium  

pip install selenium  

Chrome browser
ChromedriverDownload the chrome browser from here (choose the version for your system)After downloading, extract it and then copy the file in the folder of the script.
This can be done in two ways, by taking input from the user and by giving input in the command line itself.
# Method 1Asking the user for input.
from selenium import webdriver  # Taking input from usersearch_string = input("Input the URL or string you want to search for:")  # This is done to structure the string # into search url.(This can be ignored)search_string = search_string.replace(' ', '+')   # Assigning the browser variable with chromedriver of Chrome.# Any other browser and its respective webdriver # like geckodriver for Mozilla Firefox can be usedbrowser = webdriver.Chrome('chromedriver')  for i in range(1):    matched_elements = browser.get("https://www.google.com/search?q=" +                                     search_string + "&start=" + str(i))
After saving the above script in script.py, run it in the command prompt as:
python script.py

# Method 2
Taking search string in the command line itself.
from selenium import webdriverimport sys  # function to convert a list into stringdef convert(s):     str1 = ""     return(str1.join(s))         # Assign the arguments passed to a variable search_stringsearch_string = sys.argv[1:]   # The argument passed to the program is accepted# as list, it is needed to convert that into stringsearch_string = convert(search_string)  # This is done to structure the string # into search url.(This can be ignored)search_string = search_string.replace(' ', '+')     # Assigning the browser variable with chromedriver of Chrome.# Any other browser and its respective webdriver # like geckodriver for Mozilla Firefox can be usedbrowser = webdriver.Chrome('chromedriver')    for i in range(1):    matched_elements = browser.get("https://www.google.com/search?q=" +                                    search_string + "&start=" + str(i))
After saving the above script in script.py, run it in the command prompt as:
python script.py "geeksforgeeks"
alpeshkaushal
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – popup menu in wxPython

15 May, 2020
In this article we are going to know how can we create a popupmenu in wxPython. We will write a code when we click right on screen a popup menu will show up with menu items names as ‘one’ and ‘two’.
Syntax :
wx.Window.PopupMenu(self, menu, pos)

Parameters :
Code Example :
import wx  class PopMenu(wx.Menu):      def __init__(self, parent):        super(PopMenu, self).__init__()          self.parent = parent          # menu item 1        popmenu = wx.MenuItem(self, wx.NewId(), 'one ')        self.Append(popmenu)        # menu item 2        popmenu2 = wx.MenuItem(self, wx.NewId(), 'two')        self.Append(popmenu2)  class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)          self.InitUI()      def InitUI(self):          self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)          self.SetSize((600, 400))        self.SetTitle('Popup Menu')        self.Centre()      def OnRightDown(self, e):        # sow popu menu        self.PopupMenu(PopMenu(self), e.GetPosition())    def main():      app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output :
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Calculate n + nn + nnn + ... + n(m times) in Python - GeeksforGeeks

05 Nov, 2019
The program is to find a mathematical series, where we need to accept the value of n and m. n is the base number and m is the number of times till which the series run.
Examples:
Input : 2 + 22 + 222 + 2222 + 22222 
Output : 24690

Input : 12 + 1212 + 121212
Output : 122436

We first convert the numbers into string format and concatenate them regularly. Later, we convert them back to integer and add them upto mth term. as shown in the following program.
# Python program to sum the given series  # Returns sum of n + nn + nnn + .... (m times)def Series(n, m):      # Converting the number to string    str_n = str(n)      # Initializing result as number and string    sums = n    sum_str = str(n)      # Adding remaining terms    for i in range(1, m):                 # Concatenating the string making n, nn, nnn...        sum_str = sum_str + str_n                  # Before adding converting back to integer        sums = sums + int(sum_str)      return sums  # Driver Coden = 2m = 5total = Series(n, m)print(total)
Output:
24690

nidhi_biet
large-numbers
series
Python
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1