code-rag-bench/online-tutorials huggingface dataset:
Adding and Removing Elements in Perl Array

Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used the print function to print various values. Similarly, there are various other functions or sometimes called subroutines, which can be used for various other functionalities.
 Live Demo
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";

# add one element at the end of the array
push(@coins, "Penny");
print "2. \@coins = @coins\n";

# add one element at the beginning of the array
unshift(@coins, "Dollar");
print "3. \@coins = @coins\n";

# remove one element from the last of the array.
pop(@coins);
print "4. \@coins = @coins\n";

# remove one element from the beginning of the array.
shift(@coins);
print "5. \@coins = @coins\n";
This will produce the following result −
1. @coins = Quarter Dime Nickel
2. @coins = Quarter Dime Nickel Penny
3. @coins = Dollar Quarter Dime Nickel Penny
4. @coins = Dollar Quarter Dime Nickel
5. @coins = Quarter Dime Nickel
How to Install Tkinter in Windows? - GeeksforGeeks

09 Sep, 2021
In this article, we will look into the various methods of installing Tkinter on a Windows machine.
Note: Python already comes bundled with Tkinter. But if you still face any error with Tkinter, follow along with the article for manual installation.
Python 
PIP or conda (Depending upon your preference)
Open up the command prompt and use the below command to install Tkinter:
pip install tk
The following message will be displayed once the installation is completed:
To verify the installation use the tk._test() function. Use the below screenshots for reference:
Python3
import tkintertkinter._test()
Output:
Conda users can open up the Anaconda Power Shell and use the below command to install Tkinter:
conda install -c anaconda tk
You will get the following message once the installation is completed:
To verify the installation run the below code:
Python3
import tkintertkinter._test()
Output:
Blogathon-2021
how-to-install
Picked
Python-tkinter
Blogathon
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to parse JSON Data into React Table Component ?
How to Connect Python with SQL Database?
Changing CSS styling with React onClick() Event
Python - Gaussian fit
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
Range Sum Queries Without Updates using C++

In this article, we will give an array of size n, which will be an integer. Then, we will compute the sum of elements from index L to index R and execute the queries multiple times, or we need to calculate the sum of the given range from [L, R]. For example −
Input : arr[] = {1, 2, 3, 4, 5}
   L = 1, R = 3
   L = 2, R = 4
Output : 9
   12

Input : arr[] = {1, 2, 3, 4, 5}
   L = 0, R = 4
   L = 1, R = 2
Output : 15
   5
There are two solutions to this question. The first one is by the Brute Force approach and by the Prefix sum(Efficient) approach.
In this approach, we will traverse through the given range and print the sum.
#include<bits/stdc++.h>

using namespace std;

int main() {
   int arr[] = {1, 2, 3, 4, 5};
   int n = sizeof(arr)/sizeof(int); // size of given array.
   int L1 = 1, R1 = 3;
   int L2 = 2, R2 = 4;
   int sum = 0;
   for(int i = L1; i <= R1; i++) // traversing through the first range.
      sum += arr[i];
   cout << sum << "\n";
   sum = 0;
   for(int i = L2; i <= R2; i++) // traversing through the second range.
      sum += arr[i];
   cout << sum << "\n";
}
9
12
In this approach, we are simply traversing through the given ranges; in this case, this program is good as it has searching time complexity O(N), where N is the size of the given array. Still, this changes when we are given several queries Q then our complexity turns to O(N*Q), where Q is the number of queries and N is the size of the given array. Unfortunately, this time complexity can’t handle higher constraints, so now we will look into an efficient approach that will work for higher constraints.
In this approach, we will make a new array named prefix which will be our prefix sum array, and then we answer the sum of ranges given.
#include<bits/stdc++.h>
using namespace std;

int main() {
   int arr[] = {1, 2, 3, 4, 5};
   int n = sizeof(arr)/sizeof(int); // size of given array.
   int L1 = 1, R1 = 3;
   int L2 = 2, R2 = 4;
   int sum = 0;
   int prefix[n];
   for(int i = 0; i < n; i++){
      sum += arr[i];
      prefix[i] = sum;
   }

   if(L1) // to avoid segmentation fault
      cout << prefix[R1] - prefix[L1 - 1] << "\n";
   else
      cout << prefix[R1] << "\n";

   if(L2) // avoiding segmentation fault.
      cout << prefix[R2] - prefix[L2 - 1] << "\n";
   else
      cout << prefix[R2] << "\n";
}
9
12
In this approach, we store the prefix sum values in an array called prefix. Now, this array makes our program very efficient as this gives us searching time complexity of O(1), which is the best complexity you can get, and therefore when we are given Q amount of queries, then our searching time complexity becomes O(Q) where Q is the number of queries.
In this article, we solve a problem to find the Range sum queries without updates using the Prefix sum array. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.
How to display a list of plots with the help of grid.arrange in R?

In data analysis, we deal with many variables at a time and we want to visualize the histogram of these variables at a time. This helps us to understand the distribution of each variable in the data set, therefore we can apply the appropriate technique to deal with those variables. To create a list of plots we can use grid.arrange function in gridExtra package that can arrange plots based on our need.
Consider the below data frame −
> set.seed(10)
> df<-data.frame(x1=rnorm(10),x2=rnorm(20,0.2),x3=rnorm(20,0.5),x4=rnorm(10,0.5))
> head(df,20)
            x1     x2           x3         x4
1  0.01874617 1.301779503 -1.3537405 0.09936245
2 -0.18425254 0.955781508 0.4220539 0.16544343
3 -1.37133055 -0.038233556 1.4685663 1.86795395
4 -0.59916772   1.187444703  0.6849260   2.63776710
5  0.29454513   0.941390128 -0.8799436   1.00581926
6  0.38979430   0.289347266 -0.9355144   1.28634238
7  -1.20807618 -0.754943856  0.8620872  -0.40221194
8  -0.36367602 0.004849615  -1.2590868   1.03289699
9  -1.62667268 1.125521262  0.1754560   -0.14589425
10 -0.25647839 0.682978525  -0.1515630   0.79098749
11  0.01874617 -0.396310637  1.5865514   0.09936245
12 -0.18425254 -1.985286838 -0.2625449   0.16544343
13 -1.37133055 -0.474865938 -0.3286625   1.86795395
14 -0.59916772 -1.919061192  1.3344739   2.63776710
15 0.29454513  -1.065198022 -0.4676520   1.00581926
16 0.38979430  -0.173661555  0.4711847   1.28634238
17 -1.20807618 -0.487555430  0.7325252  -0.40221194
18 -0.36367602 -0.672158827  0.1987913   1.03289699
19 -1.62667268  0.098238994 -0.1776146  -0.14589425
20 -0.25647839 -0.053780530  1.1552276   0.79098749
Loading ggplot2 package −
> library(ggplot2)
Loading gridExtra package −
> library(gridExtra)
Creating the histograms of x1, x2, x3, and x4 −
> p1 <- ggplot(df, aes(x1)) + geom_histogram()
> p2 <- ggplot(df, aes(x2)) + geom_histogram()
> p3 <- ggplot(df, aes(x3)) + geom_histogram()
> p4 <- ggplot(df, aes(x4)) + geom_histogram()
> PlotsList<- list(p1,p2,p3,p4)
Arranging the plots in one graph −
> grid.arrange(grobs = PlotsList, ncol = 2)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Here R is showing “`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.” with the output but it is not an error, it is just telling us to change the binwidth and we can change it in geom_histogram() as geom_histogram(binwidth=1).
Write a function that generates one of 3 numbers according to given probabilities in C++

In this problem, we have to create a function that will generate three numbers based on the given probability.
For this, we will use the built-in random number generator function which is rand(a, b) which generates random numbers within the range [a, b] with equal probability.
Our task is to return only three numbers A, B, C which have the probability of occurrence as P(A), P(B), P(C) respectively and according to definition of probability P(A) + P(B) + P(C) = 1.
To create our function using rand(a,b). we will use its feature that the probability of occurrence of any number from a to b is the same. But we have to get A with probability P(A) and so on. So, for this, we will use percentage probabilities of the numbers i.e. if P(A) = 1/5, we will treat it as 20%.
So, the maximum probability percentage will be 100%, so we will generate a random number from 0 to 100 and based on the number generated we will return numbers between A, B, C based on the following conditions.
Case 1 − If the number generated is between 0 and P(A), return A.
Case 2 − If the number generated is between P(A) and P(A)+P(B), return B.
Case 3 − If the number generated is between P(A)+P(B) and 1{P(A)+P(B)+P(C)}, return C.
Let’s see an example that will make the concept clear,
A = 3 , P(A) = 35%
B = 43, P(B) = 50%
C = 90, P(C) = 15%
The program will return,
3 if the rand function generates number between 0 and 35.
43 if the rand function generates number between 35 and 85.
90 if the rand function generates number between 85 and 100.
Program to show the implementation of our logic,
 Live Demo
#include<iostream>
using namespace std;
int randomABC(int A, int B, int C, int PA, int PB, int PC){
   int randNumber = rand()%100+1;
   if (randNumber <= PA)
   return A;
   if (randNumber <= (PA+PB))
   return B;
   else
   return C;
}
int main(){
   cout<<"Random number between 3, 45, 90 with given probabilities is : "<<randomABC(3, 43, 90, 35, 40, 25);
   return 0;
}
Random number between 3, 45, 90 with given probabilities is : 3
C/C++ Program for Finding the vertex, focus and directrix of a parabola - GeeksforGeeks

05 Dec, 2018
A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from the focus is a parabola.Vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight line used to generate the curve.
The standard form of a parabola equation is . Given the values of a, b and c; our task is to find the coordinates of vertex, focus and the equation of the directrix.
Example –
Input : 5 3 2
Output : Vertex:(-0.3, 1.55)
         Focus: (-0.3, 1.6)
         Directrix: y=-198
Consult the formula below for explanation.

#include <bits/stdc++.h>using namespace std;  // Function to calculate Vertex, Focus and Directrixvoid parabola(float a, float b, float c){    cout << "Vertex: (" << (-b / (2 * a)) << ", "         << (((4 * a * c) - (b * b)) / (4 * a))         << ")" << endl;    cout << "Focus: (" << (-b / (2 * a)) << ", "         << (((4 * a * c) - (b * b) + 1) / (4 * a))         << ")" << endl;    cout << "Directrix: y="         << c - ((b * b) + 1) * 4 * a << endl;}  // Driver Functionint main(){    float a = 5, b = 3, c = 2;    parabola(a, b, c);    return 0;}
Vertex: (-0.3, 1.55)
Focus: (-0.3, 1.6)
Directrix: y=-198

Please refer complete article on Finding the vertex, focus and directrix of a parabola for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Regular expressions in C
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Exit codes in C/C++ with Examples
Hamming code Implementation in C/C++
Conditional wait and signal in multi-threading
C Hello World Program
Absolute difference of Number arrays in JavaScript

Suppose, we have two arrays like these −
const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
We are required to write a JavaScript function that takes in such two arrays and returns an array of absolute difference between the corresponding elements of the array.
So, for these arrays, the output should look like −
const output = [8,6,4,1,3,3];
We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array.
Therefore, let’s write the code for this function −
The code for this will be −
const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
const absDifference = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0));
      res[i] = el;
   };
   return res;
};
console.log(absDifference(arr1, arr2));
The output in the console will be −
[ 8, 6, 4, 1, 3, 3 ]
XPath - Comparison Operators

XPath defines following comparison operators to be used with the XPath expressions.
=
is equals to
!=
is not equals to
<
is less than
>
is greater than
<=
is less than or equals to
>=
is greater than or equals to
This example creates a table of <student> element with its attribute roll no and its child <firstname>,<lastname><nickname> and <marks> by iterating over each student. It checks marks to be greater than 90 and then prints the student(s) details.
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">  

   <xsl:template match = "/">
      <html>
         <body>
            <h2>Students</h2>
					
            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>
						
               <xsl:for-each select = "class/student">
                  <xsl:if test = "marks > 90">
                     <tr>
                        <td><xsl:value-of select = "@rollno"/></td>
                        <td><xsl:value-of select = "firstname"/></td>
                        <td><xsl:value-of select = "lastname"/></td>
                        <td><xsl:value-of select = "nickname"/></td>
                        <td><xsl:value-of select = "marks"/></td>
                     </tr>
                  </xsl:if>
               </xsl:for-each>
            </table>
         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

    90 Lectures 
     20 hours 

 Arun Motoori

    23 Lectures 
     8 hours 

 Sanjay Kumar

    13 Lectures 
     1.5 hours 

 Sanjay Kumar

    24 Lectures 
     1.5 hours 

 Sanjay Kumar

    47 Lectures 
     3 hours 

 Krishna Sakinala
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2014-(Set-1) | Question 34 - GeeksforGeeks

28 Jun, 2021
Which of the following are used to generate a message digest by the network security protocols?
(P) RSA 
(Q) SHA-1 
(R) DES 
(S) MD5
(A) P and R only(B) Q and R only(C) Q and S only(D) R and S onlyAnswer: (C)Explanation:
RSA – It is an algorithm used to encrypt and decrypt messages.
SHA 1 – Secure Hash Algorithm 1, or SHA 1 is a cryptographic hash function. It produces a 160 bit (20 byte) hash value (message digest).
DES – Data Encryption Standard, or DES is a symmetric key algorithm for encryption of electronic data.
MD5 – Message Digest 5, or MD5 is a widely used cryptographic hash function that produces a 128 bit hash value (message digest).
Q and S i.e SHA 1 and MD5 are used to generate a message digest by the network security protocols.
So, C is the correct choice.Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
Updating a record in MySQL using NodeJS

In this article, we will see how we can update a record in MySQL using NodeJS. We will dynamically update MySQL table values from Node.js server. You can use the select statement after updating to check if the MySql record is updated.
Before proceeding, please check the following steps are already executed −
mkdir mysql-test
mkdir mysql-test
cd mysql-test
cd mysql-test
npm init -y
npm init -y
npm install mysql
npm install mysql
The above steps are for installing the Node - mysql dependecy in the project folder.
For updating an existing record into the MySQL table, firstly create an app.js file
For updating an existing record into the MySQL table, firstly create an app.js file
Now copy-paste the below snippet in the file
Now copy-paste the below snippet in the file
Run the code using the following command
Run the code using the following command
>> node app.js
// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   var sql = "UPDATE student SET address = 'Bangalore' WHERE name = 'John';"
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log(result.affectedRows + " Record(s) updated.");
      console.log(result);
   });
});
1 Record(s) updated.
OkPacket {
   fieldCount: 0,
   affectedRows: 1, // This will return the number of rows updated.
   insertId: 0,
   serverStatus: 34,
   warningCount: 0,
   message: '(Rows matched: 1 Changed: 1 Warnings: 0', // This will return the
   number of rows matched.
   protocol41: true,
   changedRows: 1 }
// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   // Updating the fields with address while checking the address
   var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';"
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log(result.affectedRows + " Record(s) updated.");
      console.log(result);
   });
});
3 Record(s) updated.
OkPacket {
   fieldCount: 0,
   affectedRows: 3, // This will return the number of rows updated.
   insertId: 0,
   serverStatus: 34,
   warningCount: 0,
   message: '(Rows matched: 3 Changed: 3 Warnings: 0', // This will return the number of rows matched.
   protocol41: true,
   changedRows: 3 }
Amazon RDS - Oracle DBA Tasks 

As an industry leading database technology, oracle has many in-built features which makes it easy to manage the DBA activities, even in the cloud. The Amazon RDS oracle DB provides access to many stored procedures and functions which can be accessed using the SQL developer client tool. This procedure can be executed using the user ID and password created during the Amazon RDS instance creation. Below are the examples of some of the most frequently used DBA activities.
Sometimes a long running query or any other DB activity needs to be killed by killing the session. We use the Amazon RDS procedure rdsadmin.rdsadmin_util.kill to kill a session. The following code does that.
# First get the session identifier and the session serial number,
select SID, SERIAL#, STATUS from V$SESSION where USERNAME = 'AWSUSER';

# Next use the procedure 
begin
    rdsadmin.rdsadmin_util.kill(
        sid    => sid, 
        serial => serial_number);
end;
/

The Amazon RDS procedure rdsadmin.rdsadmin_util.alter_default_tablespace can be used to set to the default tablespace for a DB using the following command.
exec rdsadmin.rdsadmin_util.alter_default_tablespace(tablespace_name => 'AWSuser');

We can use the Amazon RDS procedure rdsadmin.rdsadmin_util.alter_db_time_zone to changes the time zone for the DB.
# Change the time zone of the DB to UTC + 5.30 
exec rdsadmin.rdsadmin_util.alter_db_time_zone(p_new_tz => '+5:30');
# Change the time zone to a specific region
exec rdsadmin.rdsadmin_util.alter_db_time_zone(p_new_tz => 'Asia/Kolkata');
We can use the Amazon RDS procedure rdsadmin.rdsadmin_util.add_logfile to add additional redo logs. The following command adds a log file of size 128MB.
exec rdsadmin.rdsadmin_util.add_logfile(p_size => '128M');
 Print
 Add Notes
 Bookmark this page
How to find the Number of CPU Cores in C#?

There are several different pieces of information relating to processors that we can get
Number of physical processors
Number of cores
Number of logical processors
These can all be different; in the case of a machine with 2 dual-core hyper-threadingenabled
processors, there are 2 physical processors, 4 cores, and 8 logical processors.
The number of logical processors is available through the Environment class, but the
other information is only available through WMI (and you may have to install some
hotfixes or service packs to get it on some systems) −
Add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.
class Program{
   public static void Main(){
      foreach (var item in new
      System.Management.ManagementObjectSearcher("Select * from
      Win32_ComputerSystem").Get()){
         Console.WriteLine("Number Of Physical Processors: {0} ",
         item["NumberOfProcessors"]);
      }
      Console.ReadLine();
   }
}
Number Of Physical Processors: 1
class Program{
   public static void Main(){
      int coreCount = 0;
      foreach (var item in new
      System.Management.ManagementObjectSearcher("Select * from
      Win32_Processor").Get()){
         coreCount += int.Parse(item["NumberOfCores"].ToString());
      }
      Console.WriteLine("Number Of Cores: {0}", coreCount);
      Console.ReadLine();
   }
}
Number Of Cores: 2
class Program{
   public static void Main(){
      Console.WriteLine("Number Of Logical Processors: {0}",
      Environment.ProcessorCount);
      Console.ReadLine();
   }
}
Number Of Logical Processors: 4
Explain about initial, incremental and terminal cash flows in finance management.

Initial cash flows
Initial cash flow is the cash required to start a project or business. This cash is estimated mainly at planning stages of a business or a project. Fixed capital, working capital, salvage value, tax rate, and book value are considered, while calculating the initial cash flows.
Sometimes, the decision for estimation of initial cash flow depends on profitability of a project or strategic purpose. Generally, initial cash flows are negative number because at a start of project or a business, there will be no returns.
Initial cash flows = FC+WC-S + (S-B) * T
Here, FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate.
Incremental cash flow is the additional cash flow for an organization. A positive cash flow indicates that there will be an increase in organization cash flows and chances for approving the project are high.
Sunk cost, opportunity cost, cannibalization and allocated cost makes calculation of incremental cash flow difficult. Market conditions, policies and legal constraints will also sometimes affect
incremental cash flows. These cash flows act as deciding tool to accept or invest on a project. Initial investment, operating cash flow and terminal cash flows are components of an incremental cash flow.
Incremental cash flow = CI – ICO - E
Here CI = Cash Inflow, E = Expenses and ICO = initial cash outflow
Terminal cash flows
Terminal cash flows are cash flows at the end of the project, after all taxes are deducted. In other words, terminal cash flows are the net amount made by company after disposing the asset and necessary amounts are paid.
These are calculated after disposal of asset and all other amounts are paid (expenses, taxes etc.). With the help of these cash flows, company can get more information on financials of a project. Based on the financials, they can accept or reject.
Sometimes forecasting errors may lead to making wrong decisions, estimation of equipment may differ.
Terminal cash flow = Ta + ΔWC
Terminal cash flow = Sp – T + ΔWC
Terminal cash flow = (Sp – B) * (1-T) + ΔWC
Here, Ta = disposal (after tax), Sp = sales (pre tax) , T = Tax rate, ΔWC= change in working capital , B = Book value of asset.
DAX Text - TRIM function

Removes all the spaces from the text except for single spaces between words.
TRIM (<text>) 

text
The text from which you want spaces removed, or a column that contains text.
A text string.
You can use DAX TRIM function on the text that you have received from another application that may have irregular spacing.
When you use DAX TRIM function on a column of text with trailing spaces, the results of the TRIM function may not be apparent in the calculated column. However, you can compare the length of the input text and the resulting text to find the difference.
= TRIM ("Product used for Fabric Care")  
returns Product used for Fabric Care. If you use TRIM function on a column of text values, the results might not be visible. You can use LEN function on both, the parameter column and the resulting column, to compare the lengths of the strings.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
C - strncmp function

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <stdio.h>

int strncmp(char *string1, char *string2, int n); 

The strncmp function compares first n characters of string1 and string2 and returns a value indicating their relationship.
 if Return value if < 0 then it indicates string1 is less than string2
 if Return value if < 0 then it indicates string1 is less than string2
 if Return value if > 0 then it indicates string2 is less than string1
 if Return value if > 0 then it indicates string2 is less than string1
 if Return value if = 0 then it indicates string1 is equal to string2
 if Return value if = 0 then it indicates string1 is equal to string2
#include <stdio.h>

int main() {
  char string1[20];
  char string2[20];

  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 4));

  strcpy(string1, "Helloooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 10));

  strcpy(string1, "Hellooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 20));

  return 0;
}

It will proiduce following result:
Return Value is : 0
Return Value is : 111
Return Value is : 0


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
C library function - perror()

The C library function void perror(const char *str) prints a descriptive error message to stderr. First the string str is printed, followed by a colon then a space.
Following is the declaration for perror() function.
void perror(const char *str)
str − This is the C string containing a custom message to be printed before the error message itself.
str − This is the C string containing a custom message to be printed before the error message itself.
This function does not return any value.
The following example shows the usage of perror() function.
#include <stdio.h>

int main () {
   FILE *fp;

   /* first rename if there is any file */
   rename("file.txt", "newfile.txt");

   /* now let's try to open same file */
   fp = fopen("file.txt", "r");
   if( fp == NULL ) {
      perror("Error: ");
      return(-1);
   }
   fclose(fp);
      
   return(0);
}
Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist −
Error: : No such file or directory


    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
Convert BGR and RGB with Python - OpenCV - GeeksforGeeks

24 Feb, 2021
Prerequisites: OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will convert a BGR image to RGB with python and OpenCV.
OpenCV uses BGR image format. So, when we read an image using cv2.imread() it interprets in BGR format by default.
We can use cvtColor() method to convert a BGR image to RGB and vice-versa.
Syntax: cv2.cvtColor(code) 
Parameter:
 cv2.COLOR_BGR2RGB –  BGR image is converted to RGB.
cv2.COLOR_RGB2BGR –  RGB image is converted to BGR.
Converting a BGR image to RGB and vice versa can have several reasons, one of them being that several image processing libraries have different pixel orderings. 
Import module
Read image
Convert it using cvtColor()
Add wait key
Add destroy window mechanism
Image used: Apple
First, we will display the image as it is imported which means in BGR format.
Example:
Python3
import cv2  image = cv2.imread("/content/gfg.jpeg")cv2.imshow('image',image)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Now to convert BGR to RGB implementation is given below.
Example:
Python3
import cv2  image = cv2.imread("/content/gfg.jpeg")  # converting BGR to RGBimage_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  cv2.imshow('image', image_rgb)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Introduction to Kivy; A Cross-platform Python Framework

In this article, we will learn about Kivy framework and its installation. Kivy is a GUI based application interface, open-source that helps in cross-platform applications for Windows, Linux and Mac.
Firstly we need to install python on pc.
After that we need to install the dependencies −
Windows −
>>> python -m pip install docutils pygments pypiwin32kivy.deps.sdl2 kivy.deps.glew
>>> python -m pip install kivy.deps.gstreamer
>>> python -m pip install kivy.deps.angle
Linux −
$ sudo add-apt-repository ppa:kivy-team/kivy
Windows −
>>> python -m pip install kivy
Linux −
>>> sudo apt-get install python3-kivy
Now let’s see how we can make a graphical user interface using Kivy −
import kivy
kivy.require('1.10.0')
from kivy.app import App # gui interface creator
from kivy.uix.button import Label # button label import statement
class Sample(App):
   # display content on screen
   def build(self):
   # Return a label widget with Sample
   return Label(text ="Tutorialpoint")
sample = Sample()
sample.run()
A new window popup will be displayed with the title of Sample containing text “Tutorialspoint” in it .
A window popup will be observed on the screen
In this manner we can use Kivy to create a GUI badsed application in Python
In this article, we learnt about the use of kivy framework for the creation of GUI based application.
Tryit Editor v3.7

Tryit: Let an image float to the right in a paragraph
C++ Program to Represent Graph Using Linked List

The incidence matrix of a graph is another representation of a graph to store into the memory. This matrix is not a square matrix. The order of the incidence matrix is V x E. Where V is the number of vertices and E is the number of edges in the graph.
In each row of this matrix we are placing the vertices, and in each column the edges are placed. In this representation for an edge e {u, v}, it will be marked by 1 for the place u and v of column e.
The incidence matrix representation takes O(V x E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory.
The incidence matrix representation takes O(V x E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory.
Input:
Output:
Input − The u and v of an edge {u,v}, and the adjacency list
Output − Adjacency List of the graph G
Begin
   Append v into the list at index u
   Append u into the list at index v
End
 Live Demo
#include<iostream>
#include<list>
#include<iterator>
using namespace std;
void displayAdjList(list<int> adj_list[], int v) {
   for(int i = 0; i<v; i++) {
      cout << i << "--->";
      list<int> :: iterator it;
      for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {
         cout << *it << " ";
      }
      cout << endl;
   }
}
void add_edge(list<int> adj_list[], int u, int v) {    //add v into the list u, and u into list v
   adj_list[u].push_back(v);
   adj_list[v].push_back(u);
}
main(int argc, char* argv[]) {
   int v = 6; //there are 6 vertices in the graph
   //create an array of lists whose size is 6
   list<int> adj_list[v];
   add_edge(adj_list, 0, 4);
   add_edge(adj_list, 0, 3);
   add_edge(adj_list, 1, 2);
   add_edge(adj_list, 1, 4);
   add_edge(adj_list, 1, 5);
   add_edge(adj_list, 2, 3);
   add_edge(adj_list, 2, 5);
   add_edge(adj_list, 5, 3);
   add_edge(adj_list, 5, 4);
   displayAdjList(adj_list, v);
}
0--->4 3
1--->2 4 5
2--->1 3 5
3--->0 2 5
4--->0 1 5
5--->1 2 3 4
Group month and year in MySQL?

You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used.
The syntax is as follows −
SELECT DATE_FORMAT(yourColumnName, '%m-%Y') from yourTableName
GROUP BY MONTH(yourColumnName), YEAR(yourColumnName)DESC;
To understand the above concept, let us create a table. The following is the query to create a table −
mysql> create table GroupMonthAndYearDemo
   −> (
   −> DueDate datetime
   −> );
Query OK, 0 rows affected (1.49 sec)
Insert records in the table using the following query −
mysql> insert into GroupMonthAndYearDemo values(now());
Query OK, 1 row affected (0.11 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 2 year));
Query OK, 1 row affected (0.12 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -2 year));
Query OK, 1 row affected (0.10 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 1 year));
Query OK, 1 row affected (0.16 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -1 year));
Query OK, 1 row affected (0.14 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from GroupMonthAndYearDemo;
The following is the output −
+---------------------+
| DueDate             |
+---------------------+
| 2018-12-06 13:12:34 |
| 2020-12-06 13:12:59 |
| 2016-12-06 13:13:08 |
| 2019-12-06 13:13:14 |
| 2017-12-06 13:13:19 |
+---------------------+
5 rows in set (0.00 sec)
The query to group by month and year is as follows −
mysql> select DATE_FORMAT(DueDate, '%m-%Y') from GroupMonthAndYearDemo 
   −> GROUP BY MONTH(DueDate) , YEAR(DueDate)DESC;
The following is the output displaying month and year grouped by using GROUP BY −
+-------------------------------+
| DATE_FORMAT(DueDate, '%m-%Y') |
+-------------------------------+
| 12-2020                       |
| 12-2019                       |
| 12-2018                       |
| 12-2017                       |
| 12-2016                       |
+-------------------------------+
5 rows in set, 2 warnings (0.00 sec)
Reverse words in a given String in Python - GeeksforGeeks

23 Nov, 2020
We are given a string and we need to reverse words of a given string?
Examples:
Input : str = geeks quiz practice code
Output : str = code practice quiz geeks

This problem has existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem.
Separate each word in given string using split() method of string data type in python.
Reverse the word separated list.
Print words of list, in string form after joining each word with space using ” “.join() method in python.
# Function to reverse words of string   def rev_sentence(sentence):       # first split the string into words     words = sentence.split(' ')       # then reverse the split string list and join using space     reverse_sentence = ' '.join(reversed(words))       # finally return the joined string     return reverse_sentence   if __name__ == "__main__":     input = 'geeks quiz practice code'    print (rev_sentence(input))
Output:
code practice quiz geeks

This article is contributed by Shashank Mishra (Gullu). 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.
TanmayThaakur
Python string-programs
Python
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
How to remove the frame from a Matplotlib figure in Python?

11 Dec, 2020
A frame in the Matplotlib figure is an object inside which given data is represented using independent Axes. These axes represent left, bottom, right and top which can be visualized by Spines(lines) and ticks.
To remove the frame (box around the figure) in Matplotlib we follow the steps. Here firstly we will plot a 2D figure in Matplotlib by importing the Matplotlib library. 
Syntax: plt.tick_params(axis=’x’, which=’both’, bottom=False, top=False, labelbottom=False)
Approach:
Select the axis to be applied. And select the tick by which the parameter are applied generally it can be ‘major’ , ‘minor’ or ‘both’.
Get the current Axex and select the spines’ visibility as False.
Python3
# Importing the Library  import matplotlib.pyplot as plt# Defining X-axis and Y-axis data Pointsx = [0, 1, 2, 3, 4, 5, 6, 8]y = [1, 5, 2, 8, 3, 5, 2, 7]  # Defining the Width and height of the Figureplt.figure(figsize=(8, 7))plt.plot(x, y)plt.show()
Output:  
The given output contains the frame with the spines and ticks. By means of removing the frame we are actually removing the box around the figure containing axes( left, bottom, right, Top).To remove the spines denoted by Black Lines we can follow the steps,
Python3
plt.figure(figsize=(4, 3))  plt.plot(x, y)  # Selecting the axis-X making the bottom and top axes False.plt.tick_params(axis='x', which='both', bottom=False,                top=False, labelbottom=False)  # Selecting the axis-Y making the right and left axes Falseplt.tick_params(axis='y', which='both', right=False,                left=False, labelleft=False)  # Iterating over all the axes in the figure# and make the Spines Visibility as Falsefor pos in ['right', 'top', 'bottom', 'left']:    plt.gca().spines[pos].set_visible(False)plt.show()
Output:
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | datetime.timedelta() function
Using return value of cin to take unknown number of inputs in C++

23 Jun, 2022
Consider a problem where we need to take an unknown number of integer inputs. 
A typical solution is to run a loop and stop when a user enters a particular value. How to do it if we are not allowed to use if-else, switch-case, and conditional statements?
The idea is to use the fact that ‘cin >> input’ is false if the non-numeric value is given. Note that the above approach holds true only when the input value’s data type is int (integer). 
Important Point: cin is an object of std::istream. In C++11 and later, std::istream has a conversion function explicit bool() const;, meaning that there is a valid conversion from std::istream to bool, but only where explicitly requested. An if or while counts as explicitly requesting conversion to bool. [Source StackOVerflow] 
Before C++ 11, std::istream had a conversion to operator void*() const;
C++
// C++ program to take unknown number// of integers from user.#include <iostream>using namespace std;int main(){    int input;    int count = 0;    cout << "To stop enter anything except integer";    cout << "\nEnter Your Input::";     // cin returns false when anything    // is entered except integer    while (cin >> input)        count++;         cout << "\nTotal number of inputs entered: "         << count;    return 0;} //This code is updated by Susobhan Akhuli
Output: 
To stop enter any character
Enter Your Input 1 2 3 s
Total number of inputs entered: 3
Time Complexity: O(count)Auxiliary Space: O(1)
This article is contributed by Aditya Rakhecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
workwitharpitjain
susobhanakhuli
cpp-input-output
cpp-puzzle
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NLP | Custom corpus

20 Feb, 2019
What is a corpus?A corpus can be defined as a collection of text documents. It can be thought as just a bunch of text files in a directory, often alongside many other directories of text files.
How it is done ?NLTK already defines a list of data paths or directories in nltk.data.path. Our custom corpora must be present within any of these given paths so it can be found by NLTK.We can also create a custom nltk_data directory in our home directory and verify that it is in the list of known paths specified by nltk.data.path.
Code #1 : Creating a custom directory and verify.
# importing librariesimport os, os.path  # using the given pathpath = os.path.expanduser('~/nltk_data')  # checkingif not os.path.exists(path):    os.mkdir(path)      print ("Does path exists : ", os.path.exists(path))    import nltk.dataprint ("\nDoes path exists in nltk : ",        path in nltk.data.path)
Output :
Does path exists : True
Does path exists in nltk : True
Code #2 : Creating a wordlist file.
# loading librariesimport nltk.data  nltk.data.load('corpora/cookbook/word_file.txt', format ='raw')
Output :
b'nltk\n'
How all this works ?
nltk.data.load() recognizes the formats – ‘raw’, ‘pickle’ and ‘yaml’.
It guess the format based on the file’s extension, if format is not given.
As in the code above, ‘raw’ format is needed to be specified.
As in the code above, ‘raw’ format is needed to be specified.
If file ends in ‘.yaml’, then no need to specify the format.
Code #3 : How to load a YAML file
import nltk.data  # loading file using the pathnltk.data.load('corpora/cookbook/synonyms.yaml')
Output :
{'bday': 'birthday'}
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.