code-rag-bench/online-tutorials huggingface dataset:
Count Number of Characters in String in R - GeeksforGeeks

16 May, 2021
In this article, we will discuss how to find the number of characters in a string using R Programming Language. The number of characters in a string means the length of the string. 
Examples:
Input: Geeksforgeeks
Output: 13
Explanation: Total 13 characters in the given string.
Input: Hello world
Output: 11
This can be calculated using the below-mentioned functions:
Using nchar() method
Using str_length() method
Using stri_length() method
Method 1: Using nchar() method.
nchar() method in R programming is used to get the length of a string.
Syntax: nchar(string)
Parameter: string
Return: Returns the length of a string
Code:
R
# R program to calculate length # of string  # Given Stringgfg <- "Geeks For Geeks"  # Using nchar() methodanswer <- nchar(gfg)  print(answer)
Output:
[1] 15
This method can be used to return the length of multiple strings passed as a parameter.
Code:
R
nchar(c("Hello World!","Akshit"));
Output:
[1] 12  6
Method 2. Using str_length () method.
The function str_length() belonging to the ‘stringr’ package can be used to determine the length of strings in R.
Syntax: str_length (str)
Parameter: string as str
Return value: Length of string
Code:
R
# R program for finding length# of string  # Importing packagelibrary(stringr)  # Calculating length of string    str_length("hello")
Output:
[1] 5
This method can be used to return the length of multiple strings passed as a parameter.
Code:
R
# Codelibrary(stringr);  str_length(c("Hello World!","Akshit"));
Output:
[1] 12  6
Method 3. Using stri_length() method.
This function returns the number of code points in each string.
Syntax: stri_length(str)
Parameter: str as character vector
Return Value: Returns an integer vector of the same length as str.
Note that the number of code points is not the same as the `width` of the string when printed on the console.
Code:
R
library(stringi);  stri_length(c("Akshit"));
Output:
[1] 6
This method can be used to return the length of multiple strings passed as a parameter.
R
library(stringi);  stri_length(c("Hello World","Akshit"));
Output:
[1] 11  6
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
PHP 7 - Environment Setup

In order to develop and run PHP Web pages, three vital components need to be installed on your computer system.
Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.
PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.
Before you proceed, it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Store the following php file in Apache's htdocs folder.
<?php
   phpinfo();
?>
Type the following address into your browser's address box.
http://127.0.0.1/phpinfo.php

If this displays a page showing your PHP installation related information, then it means you have PHP and Webserver installed properly. Otherwise, you have to follow the given procedure to install PHP on your computer.
This section will guide you to install and configure PHP over the following four platforms −
PHP Installation on Linux or Unix with Apache
PHP Installation on Linux or Unix with Apache
PHP Installation on Mac OS X with Apache
PHP Installation on Mac OS X with Apache
PHP Installation on Windows NT/2000/XP with  IIS
PHP Installation on Windows NT/2000/XP with  IIS
PHP Installation on Windows NT/2000/XP with  Apache
PHP Installation on Windows NT/2000/XP with  Apache
If you are using Apache as a Web Server, then this section will guide you to edit Apache Configuration Files.
Check here − PHP  Configuration in Apache Server
The PHP configuration file, php.ini, is the final and immediate way to affect PHP's functionality.
Check here − PHP.INI File Configuration
To configure IIS on your Windows machine, you can refer your IIS Reference Manual shipped along with IIS.

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to convert a 2D array into 1D array in C#?

Set a two-dimensional array and a one-dimensional array −
int[,] a = new int[2, 2] {{1,2}, {3,4} };
int[] b = new int[4];
To convert 2D to 1D array, set the two dimensional into one-dimensional we declared before −
for (i = 0; i < 2; i++) {
   for (j = 0; j < 2; j++) {
      b[k++] = a[i, j];
   }
}
The following is the complete code to convert a two-dimensional array to one-dimensional array in C# −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Program {
   class twodmatrix {

      static void Main(string[] args) {
      int[, ] a = new int[2, 2] {
         {
            1,
            2
         },{
            3,
            4
            }
         };

         int i, j;
         int[] b = new int[4];
         int k = 0;

         Console.WriteLine("Two-Dimensional Array...");
         for (i = 0; i < 2; i++) {

            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]);
            }
         }

         Console.WriteLine("One-Dimensional Array...");
         for (i = 0; i < 2; i++) {
            for (j = 0; j < 2; j++) {
               b[k++] = a[i, j];
            }
         }  

         for (i = 0; i < 2 * 2; i++) {
            Console.WriteLine("{0}\t", b[i]);
         }
         Console.ReadKey();
      }
   }
}
PHP Expressions

Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a typical assignment statement ($x=100), a literal value, a function or operands processed by operators is an expression, anything that appears to the right of assignment operator (=)
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
These operators are called increment and decrement operators respectively. They are unary operators, needing just one operand and can be used in prefix or postfix manner, although with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator decrements by 1). However, when used in assignment expression, prefix makesincremnt/decrement first and then followed by assignment. In case of postfix, assignment is done before increment/decrement
Uses postfix ++ operator
 Live Demo
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
This produces following result
x = 11 y = 10
Whereas following example uses prefix increment operator in assignment
 Live Demo
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
This produces following result
x = 11 y = 11
Ternary operator has three operands. First one is a logical expression. If it is TRU, second operand expression is evaluated otherwise third one is evaluated
 Live Demo
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
Following result will be displayed
pass
MATLAB - if...elseif...elseif...else...end Statements

An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions.
When using if... elseif...else statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any elseif's.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
if <expression 1>
   % Executes when the expression 1 is true 
   <statement(s)>

elseif <expression 2>
   % Executes when the boolean expression 2 is true
   <statement(s)>

Elseif <expression 3>
   % Executes when the boolean expression 3 is true 
   <statement(s)>

else 
   %  executes when the none of the above condition is true 
   <statement(s)>
end

Create a script file and type the following code in it −
a = 100;
%check the boolean condition 
   if a == 10 
      % if condition is true then print the following 
      fprintf('Value of a is 10\n' );
   elseif( a == 20 )
      % if else if condition is true 
      fprintf('Value of a is 20\n' );
   elseif a == 30 
      % if else if condition is true  
      fprintf('Value of a is 30\n' );
   else
      % if none of the conditions is true '
      fprintf('None of the values are matching\n');
   fprintf('Exact value of a is: %d\n', a );
   end
When the above code is compiled and executed, it produces the following result −
None of the values are matching
Exact value of a is: 100


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
How to Filter and save the data as new files in Excel with Python Pandas?

03 Jul, 2020
Prerequisistes: Python Pandas
Pandas is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users.
In this article, we are trying to filter the data of an excel sheet and save the filtered data as a new Excel file.
Note: You can click on this filename to download this sheet datasets.xlsx
Excel Sheet used:
In this excel sheet we are having three categories in Species column-
SetosaVersicolorVirginica
Setosa
Versicolor
Virginica
Now our aim is to filter these data by species category and to save this filtered data in different sheets with filename =species.subcategory name i.e. after the execution of the code we will going to get three files of following names-
Setosa.xlsxVersicolor.xlsxVirginica.xlsx
Setosa.xlsx
Versicolor.xlsx
Virginica.xlsx
Below is the implementation.
# Python code to filter and save the # data with different file namesimport pandas    data = pandas.read_excel("datasets.xlsx")  speciesdata = data["Species"].unique()  for i in speciesdata:    a = data[data["Species"].str.contains(i)]    a.to_excel(i+".xlsx")
Output:
Explanation:
First, we have imported the Pandas library.
Then we have loaded the data.xlsx excel file in the data object.
To fetch the unique values from that species column we have used unique() function. To check the unique values in the Species column we have called the unique() in speciesdata object.
Then we will going to iterate the speciesdata object as we will going to store the Species column unique values(i.e. Setosa, Versicolor, Virginica) one by one.
In object “a” we are filtering out the data that matches the Species.speciesdata i.e. in each iteration object a will going to store three different types of data i.e. data of Setosa type then data of Versicolor type and at last the data of Virginica type.
Now to save the filtered data one by one in excel file we have used to_excel function, where, the file will going to be saved by the speciesdata name.
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java program to calculate the power of a Given number using recursion

You can calculate the power where the base and exponent are given, using recursion as shown in the following program.
import java.util.Scanner;
public class PowerUsingRecursion {
   public static int power(int base, int exp){
      if (exp !=0){
         return (base * power(base, exp-1));
      }else {
         return 1;
      }
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the base number ::");
      int base = sc.nextInt();
      System.out.println("Enter the exponent number ::");
      int exp = sc.nextInt();
      System.out.println(power(base, exp));
   }
}
Enter the base number ::
5
Enter the exponent number ::
5
PyQt5 – Set icon size of item icon in ComboBox

22 Apr, 2020
In this article we will see how we can set the icon size to the item of combo box. By default there is no icon set to the icon in the combo box although we can set icon to each item with the help of setItemIcon method, sometimes there is a need for adjusting the icon size.
In order to change the icon size of items icon we will use setIconSize method.
Syntax : combobox.setIconSize(size)
Argument : It takes QSize object as argument
Action It will set icon size to the item
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # creating editable combo box        self.combo_box.setEditable(True)          # index        index = 0          # icon        icon = QIcon('logo.png')          # adding icon to the given index        self.combo_box.setItemIcon(index, icon)          # size        size = QSize(10, 10)          # setting icon size        self.combo_box.setIconSize(size)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
StringBuilder reverse() in Java with Examples

19 Aug, 2019
The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. The method helps to this character sequence to be replaced by the reverse of the sequence.
Syntax:
public java.lang.AbstractStringBuilder reverse()
Returns:This method returns StringBuilder object after reversing the characters.
Below programs illustrate the java.lang.StringBuilder.replace() method:Example 1:
// Java program to demonstrate// the reverse() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuilder object        // with a String pass as parameter        StringBuilder str            = new StringBuilder("WelcomeGeeks");          // print string        System.out.println("String = "                           + str.toString());          // reverse the string        StringBuilder reverseStr = str.reverse();          // print string        System.out.println("Reverse String = "                           + reverseStr.toString());    }}
Output:
String = WelcomeGeeks
Reverse String = skeeGemocleW

Example 2:
// Java program to demonstrate// the reverse() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuilder object        // with a String pass as parameter        StringBuilder str            = new StringBuilder("AAAABBBCCCC");          // print string        System.out.println("String = "                           + str.toString());          // reverse the string        StringBuilder reverseStr = str.reverse();          // print string        System.out.println("Reverse String = "                           + reverseStr.toString());    }}
Output:
String = AAAABBBCCCC
Reverse String = CCCCBBBAAAA

References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#reverse()
Akanksha_Rai
Java-Functions
Java-StringBuilder
Reverse
Java
Java
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python | Check if string repeats itself - GeeksforGeeks

25 Jun, 2019
While working with strings, many times, we can come across a use case in which we need to find if a string has in it the repeating substring, which repeats all over the string and thus making a multiple of the root substring. Let’s discuss certain ways in which we can get the root substring of string.
Method #1 : Using List comprehension + Brute ForceWe can perform this task using selective slicing and brute force manner. This is the naive method to find the string in which we try to get the root string by repetitive division of string.
# Python3 code to demonstrate working of# Check if string repeats itself# Using List comprehension + Brute Force  # initializing string test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks"  # printing original string print("The original string is : " + test_str)  # using List comprehension + Brute Force# Check if string repeats itselfres = Nonefor i in range(1, len(test_str)//2 + 1):    if (not len(test_str) % len(test_str[0:i]) and test_str[0:i] *           (len(test_str)//len(test_str[0:i])) == test_str):        res = test_str[0:i]  # printing result print("The root substring of string : " + res)
The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks
The root substring of string : GeeksforGeeks

 
Method #2 : Using list slicing + find()
This problem can also be solved using the fact that we can search for root string after adding a string and checking the root string in this string except last and first character, represents the string is repeating itself.Doesn’t work for string length < 2.
# Python3 code to demonstrate working of# Check if string repeats itself# Using list slicing + find()  # initializing string test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks"  # printing original string print("The original string is : " + test_str)  # using list slicing + find()# Check if string repeats itselfres = Nonetemp = (test_str + test_str).find(test_str, 1, -1)if temp != -1:    res = test_str[:temp]  # printing result print("The root substring of string : " + res)
The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks
The root substring of string : GeeksforGeeks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
Python | Convert a list into a tuple
Calculate Trace of a Matrix in R Programming – tr() Function

19 Jun, 2020
tr() function in R Language is used to calculate the trace of a matrix. Trace of a matrix is the sum of the values on the main diagonal(upper left to lower right) of the matrix.
Syntax: tr(x)
Parameters:x: Matrix
Example 1:
# R program to calculate# trace of a matrix  # Loading librarylibrary(psych)  # Creating a matrixA = matrix(   c(6, 1, 1, 4, -2, 5, 2, 8, 7),    nrow = 3,                ncol = 3,                byrow = TRUE           )   A  # Calling tr() functioncat("Trace of A:\n") tr(A)
Output:
     [, 1] [, 2] [, 3]
[1, ]    6    1    1
[2, ]    4   -2    5
[3, ]    2    8    7
Trace of A:
[1] 11

Example 2:
# R program to calculate# trace of a matrix  # Loading librarylibrary(psych)  # Creating a matrixA = matrix(c(1:9), 3, 3)   A  # Calling tr() functioncat("Trace of A:\n") tr(A)
Output:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
Trace of A:
[1] 15

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python unittest – assertIn() function

29 Aug, 2020
assertIn() in Python is a unittest library function that is used in unit testing to check whether a string is contained in other or not. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is contained in container string it will return true else it returns false.
Syntax: assertIn(key, container, message)
Parameters: assertIn() accept three parameters which are listed below with explanation:
key:  a string whose presence is checked in the given container
container: a string in which key string is searched
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):    # test function to test whether key is present in container    def test_negative(self):        key = "gfg"        container = "geeksforgeeks"        # error message in case if test case got failed        message = "key is not in container."        # assertIn() to check if key is in container        self.assertIn(key, container, message)  if __name__ == '__main__':    unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/e920f2cd9195a3fd72bd531f7f101754.py", line 12, in test_negative
    self.assertIn(key, container, message)
AssertionError: 'gfg' not found in 'geeksforgeeks' : key is not in container.

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

Example 2: Positive Test case
Python3
# test suiteimport unittest    class TestStringMethods(unittest.TestCase):    # test function to test whether key is present in container    def test_positive(self):        key = "geeks"        container = "geeksforgeeks"        # error message in case if test case got failed        message = "key is not in container."        # assertIn() to check if key is in container        self.assertIn(key, container, message)    if __name__ == '__main__':    unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Traversing directory in Java using BFS

24 Mar, 2018
Given a directory, print all files and folders present in directory tree rooted with given directory.
We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from queue. If the popped item is a directory, get list of all files and directories present in it, add each directory to the queue. If the popped item is a file, we print its name.
// Java program to print all files/directories// present in a directory.import java.io.File;import java.util.LinkedList;import java.util.Queue;  class FileUtils {      public static void printDirsFiles(String inputDir)    {        /* make a queue to store files and directories */        Queue<File> queue = new LinkedList<>();          queue.add(new File(inputDir));          /* loop until queue is empty -*/        while (!queue.isEmpty()) {              /* get next file/directory from the queue */            File current = queue.poll();              File[] fileDirList = current.listFiles();              if (fileDirList != null) {                  /* Enqueue all directories and print                    all files. */                for (File fd : fileDirList) {                    if (fd.isDirectory())                         queue.add(fd);                    else                         System.out.println(fd);                                    }            }        }    }      /* Iterative function to traverse given        directory in Java using BFS*/    public static void main(String[] args)    {        String inputDir = "C:\\Programs";        printDirsFiles(inputDir);    }}
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or 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.
BFS
java-file-handling
java-LinkedList
Java
Java
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matching strings for similar characters - JavaScript

We are required to write a JavaScript function that accepts two string and a number n.
The function matches the two strings i.e., it checks if the two strings contains the same characters.
The function returns true if both the strings contain the same character irrespective of their order or if they contain at most n different characters, else the function should return false.
Following is the code −
const str = 'some random text';
const str2 = 'some r@ndom text';
const deviationMatching = (first, second, num) => {
   let count = 0;
   for(let i = 0; i < first.length; i++){
      if(!second.includes(first[i])){
         count++;
      };
      if(count > num){
         return false;
      };
   };
   return true;
};
console.log(deviationMatching(str, str2, 1));
This will produce the following output in console −
true
C# Program For Reading Data From Stream and Cast Data to Chars - GeeksforGeeks

01 Nov, 2021
Given data, now our task is to read data from the stream and cast data to chars in C#. So to do this task we use the following class and methods:
FileStream: It is a class that is used to read and write files. So, to manipulate files using FileStream, you need to create an object of FileStream class. 
Syntax:
Stream object = new FileStream(path, FileMode.Open)
Where path is the location of your file – @”c:\A\data.txt” and FileMode is the mode of the file like reading and writing.
ReadByte(): This method is used to read the data from the file Byte by Byte. This method will throw NotSupportException when the current stream did not support reading. If the current stream is closed then this method will throw ObjectDisposedException.
Syntax:
FileStream_object.ReadByte()
Example:
Let us consider a file named “file.txt” is present in the A folder of C drive like as shown in the below image:
Now we read data from stream and cast data to chars. So to this follow the following approach.
Approach
Read the file named “file.txt” using FileStream with the help of specified path.
Read the data in file byte by byte using ReadByte() method until it reaches end of file.
while ((obj = s.ReadByte()) != -1)
{

    // Convert the data into chars and display
    Console.Write("{0} ", (char)obj);
}
Display file data into chars using Casting to char.
(char)obj
C#
// C# program to read the data from stream// and cast data to chars using System;using System.IO;  public sealed class GFG{      public static void Main(){          // Read the file from the specified path    using (Stream s = new FileStream(@"c:\A\file.txt", FileMode.Open))    {        int obj;                  // Read the data in file byte by byte        // Using ReadByte() method        while ((obj = s.ReadByte()) != -1)        {                          // Convert the data into chars and display            Console.Write("{0} ", (char)obj);        }        Console.ReadLine();    }}}
Output:
T H I S  I S  F I L E  D E M O
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
How to create a plot in R with a different plot window size using plot function?

We can create plots in R with having different plot window sizes. This will be helpful when we want to express X-axis or Y-axis differently. Also, the change in the size of the plot window will help us to paste the plot in places that are short or large. For example, if we want to present the plot in a business meeting then we can increase its size and if we want to publish it in a paper then its size can be decreased.
Consider the below vectors x and y −
> x<-1:20
> y<-20:1
Plotting with default −
> plot(x,y)
Plotting with 10-inch-wide and 5 inch in height −
> dev.new(width=10, height=5, unit="in")
> plot(x,y)
Plotting with 10-cm-wide and 5-cm in height −
> dev.new(width=5, height=5, unit="cm")
> plot(x,y)
Plotting with 100x50 pixel −
> dev.new(width=100, height=50, unit="px")
> plot(x,y)
C++ Program to Implement Network_Flow Problem

This is a C++ Program to implement Network_Flow problem using Ford Fulkerson algorithm.
Begin
   function bfs() returns true if there is path from source s to sink t in
   the residual graph which indicates additional possible flow in the graph.
End
Begin
   function fordfulkarson() return maximum flow in given graph:
   A) initiate flow as 0.
   B) If there is an augmenting path from source to sink, add the path to flow.
   C) Return flow.
End
#include <iostream>
#include <climits>
#include <cstring>
#include <queue>
#define n 7
using namespace std;
bool bfs(int g[n][n], int s, int t, int par[])
{
   bool visit[n];
   memset(visit, 0, sizeof(visit));
   queue <int> q;
   q.push(s);
   visit[s] = true;
   par[s] = -1;
   while (!q.empty())
   {
      int u = q.front();
      q.pop();
      for (int v=0; v<n; v++)
      {
         if (visit[v]==false && g[u][v] > 0)
         {
            q.push(v);
            par[v] = u;
            visit[v] = true;
         }
      }
   }
   return (visit[t] == true);
}
int fordFulkerson(int G[n][n], int s, int t)
{
   int u, v;
   int g[n][n];
   for (u = 0; u < n; u++)
   {
      for (v = 0; v < n; v++)
      g[u][v] = G[u][v];
   }
   int par[n];
   int max_flow = 0;
   while (bfs(g, s, t,par))
   {
      int path_flow = INT_MAX;
      for (v=t; v!=s; v=par[v])
      {
         u = par[v];
         path_flow = min(path_flow, g[u][v]);
      }
      for (v = t; v != s; v = par[v])
      {
         u = par[v];      
         g[u][v] -= path_flow;
         g[v][u] += path_flow;
      }
      max_flow += path_flow;
   }
   return max_flow;
}
int main()
{
   int g[n][n] = {{0, 6, 7, 1},
      {0, 0, 4, 2},
      {0, 5, 0, 0},
      {0, 0, 19, 12},
      {0, 0, 0, 17},
      {0, 0, 0, 0}};
   cout << "The maximum possible flow is " << fordFulkerson(g, 0, 3);
   return 0;
}
The maximum possible flow is 3
How to Plot Complex Numbers in Python?

You can plot complex numbers on a polar plot. If you have an array of complex numbers, you can plot it using:
import matplotlib.pyplot as plt
import numpy as np

cnums = np.arange(5) + 1j * np.arange(6,11)
X = [x.real for x in cnums]
Y = [x.imag for x in cnums]
plt.scatter(X,Y, color='red')
plt.show()
This will plot a graph of the numbers in a complex plane.
How to insert a document into a MongoDB collection using Java?

You can insert a document into an existing collection in MongoDB using the insert() method.
db.coll.insert(doc)
Where,
db is the database.
db is the database.
coll is the collection (name) in which you want to insert the document
coll is the collection (name) in which you want to insert the document
doc is the document you want to insert.
doc is the document you want to insert.
> use myDatabase()
switched to db myDatabase()
> db.createCollection(sample)
{ "ok" : 1 }
> db.sample.insert({name:"Ram", age:26, city:"Hyderabad"})
WriteResult({ "nInserted" : 1 })
In Java, you can insert a document into a collection using the insertOne() method of the com.mongodb.client.MongoCollection interface. This method accepts a document (object) representing the document you want to insert as a parameter.
Therefore to create a collection in MongoDB using Java program −
Make sure you have installed MongoDB in your system
Make sure you have installed MongoDB in your system
Add the following dependency to its pom.xml file of your Java project.
Add the following dependency to its pom.xml file of your Java project.
<dependency>
   <groupId>org.mongodb</groupId>
   <artifactId>mongo-java-driver</artifactId>
   <version>3.12.2</version>
</dependency>
Create a MongoDB client by instantiating the MongoClient class.
Create a MongoDB client by instantiating the MongoClient class.
Connect to a database using the getDatabase() method.
Connect to a database using the getDatabase() method.
Prepare the document to be inserted.
Prepare the document to be inserted.
Get the object of the collection into which you want to insert the document, using the getCollection() method.
Get the object of the collection into which you want to insert the document, using the getCollection() method.
Invoke the insertOne() method by passing the document (created above) as a parameter.
Invoke the insertOne() method by passing the document (created above) as a parameter.
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Connecting to the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection
      database.createCollection("students");
      //Preparing a document
      Document document = new Document();
      document.append("name", "Ram");
      document.append("age", 26);
      document.append("city", "Hyderabad");
      //Inserting the document into the collection
      database.getCollection("students").insertOne(document);
      System.out.println("Document inserted successfully");
   }
}
Document inserted successfully
How do I use Window Manager (wm) attributes in Tkinter?

The Window Manager is a toolkit available in Tcl/Tk that can be accessed with the command 'wm'. The 'wm' command allows you to set the appearance and geometry of the Tkinter window. We can control the title, color, size, and other attributes with this command. The 'wm' command has numerous keywords that can be used to modify its property.
# Import the required library
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

# Create an instance of tkinter frame
win=Tk()

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

Label(win, text="This window is disabled.",
   font=("Calibri, 24")).pack()

# Makes the window topmost
win.wm_attributes('-topmost', True)

# Makes the window transparent
win.wm_attributes('-alpha', 0.9)

# Disable the window
win.wm_attributes('-disabled', True)

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

win.mainloop()
If you run the above code, it will display a topmost transparent window that you cannot interact with, as the window is disabled using the wm attribute "-disabled".
env command in Linux with Examples - GeeksforGeeks

15 May, 2019
env is used to either print environment variables. It is also used to run a utility or command in a custom environment. In practice, env has another common use. It is often used by shell scripts to launch the correct interpreter. In this usage, the environment is typically not changed.
Syntax :
env [OPTION]... [-][NAME=VALUE]... [COMMAND [ARG]...]

Options of env command
1. Without any argument : print out a list of all environment variables.
EXAMPLE :
2. -i or –ignore-environment or only – : runs a command with an empty environment
SYNTAX :
$ env -i your_command

Note: This completely clear out the environment, but it does not prevent your_command setting new variables.
EXAMPLE : To clear the environment (creating a new environment without any existing environment variables) for a new shell
In this, it clears all the environment variable and then new shell sets the environment variable PWD. Thus in this new shell when we execute env, we only see one environment variable PWD.
3. -u or –unset: remove variable from the environment
SYNTAX :
$ env -u variable_name

EXAMPLE : Removing XDG_VTNR environment variable which you can see in the image above in the output of just env.
4. -0 or –null: End each output line with NULL, not newline
SYNTAX :
$ env -0

EXAMPLE :
5. –version: Display version information and exit.
SYNTAX :
$ env --version

EXAMPLE :
6. –help: Display a help message and exit.
SYNTAX :
$ env --help

EXAMPLE :
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Plot a Line Graph for Pandas Dataframe with Matplotlib?

We will plot a line grapg for Pandas DataFrame using the plot(). At first, import the required libraries −
import pandas as pd
import matplotlib.pyplot as plt
Create a DataFrame −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Reg_Price": [2000, 2500, 2800, 3000, 3200, 3500],"Units": [100, 120, 150, 170, 180, 200]
   }
)
Plot a line graph with both the columns −
plt.plot(dataFrame["Reg_Price"], dataFrame["Units"])
Following is the code −
import pandas as pd
import matplotlib.pyplot as plt

# creating a DataFrame with 2 columns
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Reg_Price": [2000, 2500, 2800, 3000, 3200, 3500],"Units": [100, 120, 150, 170, 180, 200]
   }
)

# plot a line graph
plt.plot(dataFrame["Reg_Price"], dataFrame["Units"])
plt.show()
This will produce the following output −
How to bind multiple versions of a DB2 program into a package?

Packages are DB2 database objects which hold the executable forms of SQLs which are used in COBOL-DB2 programs. The packages are stored in a catalog table and contain the strategy/tables/columns/predicate associated with the SQL statements.
If there is a DB2 table ORDERS_TEST in test environment and ORDERS_PROD in production environment, then we need two versions of COBOL-DB2 program (which will access these tables) — one for test and the other for production.
Although both programs will be carbon copy of each other, the only difference lies in the SQL statements. The test version of the program will use table ORDERS_TEST in SQL statements and the production version of program will use ORDERS_PROD table in SQL statement. In order to achieve this versioning, we need to bifurcate the packages of the program.
To keep the multiple versions of the package, we have to use the VERSION option in the pre-compilation step. Therefore, we can give the VERSION(TEST) for the test version of the package and VERSION(PROD) for the production version of the package.
Following is an example:
//BIND EXEC PGM=IKJEFT01
//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(TB3)
BIND PLAN(PLANA) -
PKLIST(PACKA) -
VERSION(PROD) -
ACQUIRE(ALLOCATE) -
ISOLATION (RS)
/*
Pattern pattern() method in Java with examples

The java.util.regex package of java provides various classes to find particular patterns in character sequences. The pattern class of this package is a compiled representation of a regular expression.
The pattern() method of the Pattern class fetches and returns the regular expression in the string format, using which the current pattern was compiled.
import java.util.regex.Pattern;
public class PatternExample {
   public static void main(String[] args) {
      String date = "12/09/2019";
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      if(pattern.matcher(date).matches()) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");
      }
      //Retrieving the regular expression of the current pattern
      String regularExpression = pattern.pattern();
      System.out.println("Regular expression: "+regularExpression);
   }
}
Date is valid
Regular expression: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
public class PatternExample {
   public static void main(String[] args) {
      String input = "Hi my id is 056E1563";
      //Regular expression using groups
      String regex = "(.*)?(\\d+)";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      if(pattern.matcher(input).matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      //Retrieving the regular expression of the current pattern
      String regularExpression = pattern.pattern();
      System.out.println("Regular expression: "+regularExpression);
   }
}
Match found
Regular expression: (.*)?(\d+)
wxPython - Change font of Radio Button - GeeksforGeeks

06 Jan, 2022
In this article we are going to learn that how can we change the font of the label text present on the radio button present in the frame. We need to follow some steps as follows: 
Step 1: Create a wx.Font object. Step 2: Add different attributes of font in parameters like: family, style etc. Step 3: Create a Radio Button. Step 3: Set font by using SetFont() function. 
 
Syntax: wx.RadioButton.SetFont(self, font)Parameters: 
 
 
Code Example:  
Python3
import wx APP_EXIT = 1  class Example(wx.Frame):     def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)         self.InitUI()     def InitUI(self):                 # create parent panel for radio buttons        self.pnl = wx.Panel(self)         # create radio buttons        self.rb1 = wx.RadioButton(self.pnl, label ='Btn1', pos =(30, 10), size =(100, 20))        self.rb2 = wx.RadioButton(self.pnl, label ='Btn2', pos =(30, 30), size =(100, 20))        self.rb3 = wx.RadioButton(self.pnl, label ='Btn3', pos =(30, 50), size =(100, 20))         # declare font for radio buttons        font = wx.Font(12, wx.FONTFAMILY_MODERN, 0, 90, underline = False,                       faceName ="")         # set font for all radio buttons        self.rb1.SetFont(font)        self.rb2.SetFont(font)        self.rb3.SetFont(font)  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()  if __name__ == '__main__':    main()
Output Window:  
 
gulshankumarar231
Python wxPython-Button
Python-gui
Python-wxPython
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 ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to install DSC resources using PowerShell?

To install the DSC resource using PowerShell, we can use the same command to install modules in PowerShell (Install-Module).
The Find-DscResource command would get all the available DSC resources. To search the specific DSC resource, you can provide the -Name parameter in the Find-DscReource command. For example, we need to search for the FilesAndFolder DSC resource
Find-DSCResource -Name filesandfolders
Name             Version ModuleName Repository
----             ------- ---------- ----------
FilesAndFolders 0.3.212 CommonTasks PSGallery
To install this module, we can pipeline the Install-Module command.
Find-DSCResource -Name filesandfolders | Install-Module -Force -Verbose
Once the module is installed, we can use the Get-DSCResource command to check if the module is installed properly.
Get-DscResource -Name FilesAndFolders
To check the properties of the installed module, we can use the below command.
Get-DscResource -Name FilesAndFolders | Select -ExpandProperty Properties
Name                 PropertyType IsMandatory Values
----                 ------------ ----------- ------
DependsOn             [String[]]     False       {}
PsDscRunAsCredential  [PSCredential] False       {}
Items                 [Hashtable[]]  True        {}
Exp() and Count() Function in MS Access

01 Sep, 2020
1. Exp() function :In MS Access, the Exp() function returns e( 2.718281) power raised to a number. In this function, a number will be pass as a parameter and it will return e raised to the power of a specified number.e is a constant which value is equal to 2.718281. It is the base of natural logarithms.
Syntax :
Exp(number)

Example-1 :
SELECT Exp(6) AS ExpNum;

Output –
Example-2 :
SELECT Exp(1) AS ExpNum;

Output –
2. Count() function :In MS Access, The Count() function returns the total number of eligible records of a query. When a query expression is performed with the help of count function then it will count total records and return that total count number.
Note –Null values will not be included in the count.
Syntax :
Count(expression)

Consider an example for Demo Database given below.
Table name : Stu_Details.
Example-1 :
SELECT Count(*) AS TOTAL FROM Stu_Details;

Output –
Example-2 :
SELECT Count(*) AS TOTAL FROM Stu_Details
Where MARKS>50;

Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
SQL | GROUP BY
Difference between DELETE and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
SQL Correlated Subqueries