code-rag-bench/online-tutorials huggingface dataset:
Difference between input() and sys.stdin.readline()

29 Oct, 2021
Python is a widely used general-purpose language that can be used for many purposes. Taking input in any language is as important as breathing for humans. Python provides various methods for taking input. However, we all may get confused about how each method is different from one another. In this article, we will discuss about two such methods i.e input() and sys.stdin.readline().
Note: For more information, refer to Python Tutorial
This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether the user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by Python.
How the input function works in Python :
When input() function executes program flow will be stopped until the user has given input.
The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional.
Whatever you enter as input, input function converts it into a string. if you enter an integer value still input() function converts it into a string. You need to explicitly convert it into an integer in your code using typecasting.
Example:
# Program to check input  # type in Python     num = input ("Enter number :") print(num) name1 = input("Enter name : ") print(name1)     # Printing type of input value print ("type of number", type(num)) print ("type of name", type(name1))
Output:
Stdin stands for standard input which is a stream from which the program reads its input data. This method is slightly different from the input() method as it also reads the escape character entered by the user. More this method also provides the parameter for the size i.e. how many characters it can read at a time.
Example:
# Python program to demonstrate# sys.stdin.readline()    import sys  name = sys.stdin.readline()print(name)  num = sys.stdin.readline(2)print(num)
Output:
abdullahvadhariya
python-input-output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
QUOTENAME() Function in SQL Server

30 Dec, 2020
QUOTENAME() function :This function in SQL Server is used to return a Unicode string with delimiters added in order to make the string a valid SQL Server delimited identifier.
Features :
This function is used to find a Unicode string with delimiters added.
This function accepts only strings and delimiters.
This function add delimiters by default if not specified.
This function always returns string along with delimiters.
Here, the string is limited to 128.
Syntax :
QUOTENAME(string, quote_char)
Parameter :This method accepts two parameter as given below :
string: Specified string of Unicode character data which is limited to 128 characters.
quote_char : It is optional. It is a one-character string which is to be used as the delimiter. For example, it can be a single quotation mark i.e, ( ‘ ), or a left or right bracket i.e, ( [] ), or a double quotation mark i.e, ( ” ), or a left or right parenthesis i.e, ( () ), or a greater than or less than sign i.e, ( >< ), or a left or right brace i.e, ( {} ) or a backtick i.e, ( ` ). Moreover, if this parameter is not specified, the brackets are used by default.
Returns :It returns a Unicode string with delimiters added in order to make the string a valid SQL Server delimited identifier.
Example-1 :Getting the Unicode string of the string “xyz”.
SELECT QUOTENAME('xyz');
Output :
[xyz]
Here, the quote_char parameter is not defined but brackets are added to the output by default.
Example-2 :Getting the Unicode string with parenthesis delimiters.
SELECT QUOTENAME('abc', '{}');
Output :
{abc}
Here, the delimiters are specified in the parameters so they are returned as output.
Example-3 :Using QUOTENAME() function with a variable and getting the Unicode string of the specified string.
DECLARE @string VARCHAR(3);  
SET @string = '123';  
SELECT QUOTENAME(@string);
Output :
[123]
Example-4 :Using QUOTENAME() function with a variable and getting the Unicode string of the specified string as well as delimiters.
DECLARE @string VARCHAR(4);
DECLARE @delimiter VARCHAR(2);
SET @string = 'jk12';
SET @delimiter = '()';
SELECT QUOTENAME(@string, @delimiter);

Output :
(jk12)
Example-5 :Getting the Unicode string with greater than sign.
SELECT QUOTENAME('23', '>');
Output :
<23>
This delimiter only works with numbers.
Application :This function is used to return the Unicode string with delimiters added to it in order to make the string a valid SQL Server delimited identifier.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to make a system tray application in Tkinter?

A System Tray application is created for the continuous execution of the program. Whenever an application is closed by the user, it will get its state running on the taskbar. To identify a system tray application, we can provide an image or icon to its application.
To create a System Tray icon of a tkinter application, we can use pystray module in Python. It has many inbuilt functions and methods that can be used to configure the system tray icon of the application.
To install pystray in your machine, you can type "pip install pystray" command in your shell or command prompt.
To create a System Tray icon, you can follow these steps,
Import the required libraries - Pystray, Python PIL or Pillow.
Import the required libraries - Pystray, Python PIL or Pillow.
Define a function hide_window() to withdraw window and provide the icon to the system tray.
Define a function hide_window() to withdraw window and provide the icon to the system tray.
Add and define two menu items, "Show" and "Quit".
Add and define two menu items, "Show" and "Quit".
Add a Command in the menu items by defining a function for Show and Quit.
Add a Command in the menu items by defining a function for Show and Quit.
# Import the required libraries
from tkinter import *
from pystray import MenuItem as item
import pystray
from PIL import Image, ImageTk

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

win.title("System Tray Application")
# Set the size of the window
win.geometry("700x350")

# Define a function for quit the window
def quit_window(icon, item):
   icon.stop()
   win.destroy()

# Define a function to show the window again
def show_window(icon, item):
   icon.stop()
   win.after(0,win.deiconify())

# Hide the window and show on the system taskbar
def hide_window():
   win.withdraw()
   image=Image.open("favicon.ico")
   menu=(item('Quit', quit_window), item('Show', show_window))
   icon=pystray.Icon("name", image, "My System Tray Icon", menu)
   icon.run()

win.protocol('WM_DELETE_WINDOW', hide_window)

win.mainloop()
If you run the above code, it will display the application window.
If we close the window, it will still appear in the taskbar as the system tray application.
sympy.integrals.inverse_laplace_transform() in python

15 Jul, 2021
With the help of inverse_laplace_transform() method, we can compute the inverse of laplace transformation of F(s).
Syntax : inverse_laplace_transform(F, s, t) Return : Return the unevaluated transformation function.  
Example #1 : In this example, we can see that by using inverse_laplace_transform() method, we are able to compute the inverse laplace transformation and return the unevaluated function. 
Python3
# import inverse_laplace_transformfrom sympy.integrals.transforms import inverse_laplace_transformfrom sympy import exp, Symbolfrom sympy.abc import s, t a = Symbol('a', positive = True)# Using inverse_laplace_transform() methodgfg = inverse_laplace_transform(exp(-a * s)/s, s, t) print(gfg)
Output :
Heaviside(-a + t)  
Example #2 : 
Python3
# import inverse_laplace_transformfrom sympy.integrals.transforms import inverse_laplace_transformfrom sympy import exp, Symbolfrom sympy.abc import s, t a = Symbol('a', positive = True)# Using inverse_laplace_transform() methodgfg = inverse_laplace_transform(exp(-a * s)/s, s, 5) print(gfg)
Output :
Heaviside(5 – a)  
 
sweetyty
Python SymPy-Stats
SymPy
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
MongoDB – $nin Operator

22 Apr, 2020
MongoDB provides different types of comparison query operators and $nin (not in) operator is one of them. This operator is used to select those documents where the value of the field is not equal to any of the given value in the array and the field that does not exist.If the field contain an array, then this operator selects only those documents whose field contains an array that holds no item that matches a value of the specified array. You can use this operator in methods like find(), update(), etc. according to your requirements.
Syntax:
{field: {$nin: [value1, value2, value3, ...]}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are retrieving only those employee’s documents whose name is not Amit or Suman.
db.contributor.find({name: {$nin: ["Amit", "Suman"]}}).pretty()
In this example, we are retrieving only those employee’s documents who is not working with either C#, Python, or both languages.
db.contributor.find({language: {$nin: ["C#", "Python"]}}).pretty()
In this example, we are retrieving only those employee’s documents whose age is not 25 or 22.
db.contributor.find({"personal.age": { $nin: [25, 22]}}).pretty()
In this example, we are adding a new field-value pair(i.e, salary: 10000) in the documents of those employee’s whose name is not Amit or Priya by using update() method with $in and $set operators.
db.contributor.update({name: {$nin: ["Amit", "Priya"]}},                             {$set: {salary: 1000}})
Note: The update() method by default update only one document at a time. If you want to update multiple documents, then set the value of its multi parameter to true. So, in this example, the update() method updated the first document that matches the given condition as shown in the below image.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Getting Started with System Design
Markov Decision Process
Principal Component Analysis with Python
Fuzzy Logic | Introduction
An introduction to Machine Learning
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
comm - Unix, Linux Command

comm -  compare two sorted files line by line and write to standard output: the lines that are common, plus the lines that are unique.
comm [options]... File1 File2
Before 'comm' can be used, the input files must be sorted using the collating sequence specified by the 'LC_COLLATE' locale, with trailing newlines significant. If an input file ends in a non-newline character, a newline is silently appended. The 'sort' command with no options always outputs a file that is suitable input to 'comm'. With no options, 'comm' produces three column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. Columns are separated by a single TAB character.
The options -1, -2, and -3 suppress printing of the corresponding columns. Unlike some other comparison utilities, 'comm' has an exit status that does not depend on the result of the comparison. Upon normal completion 'comm' produces an exit code of zero. If there is an error it exits with nonzero status.
Show the lines unique to words.txt
$ cat words.txt
Apple
Banana
Orange
India
US
Canada
$ cat countries.txt
India
US
Canada
$ comm -23 < (sort words.txt | uniq) < (sort countries.txt | uniq)
Apple 
Banana
Orange

Show the lines common to words.txt and countries.txt.
$ comm -12 < (sort words.txt | uniq) < (sort countries.txt | uniq)
Python program to reverse the content of a file and store it in another file - GeeksforGeeks

31 Dec, 2020
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types.  
Full reversing: In this type of reversing all the content gets reversed.  
Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last position.  
Example 1: Full Reversing  
Input: Hello Geeks
       for geeks!
        

Output:!skeeg rof
        skeeG olleH
        



Example 2: Word to word reversing 
Input: 
        Hello Geeks
        for geeks!

Output:
         geeks! for
         Geeks Hello



Example 1: Full Reversing Text file: 
 
Python
# Open the file in write modef1 = open("output1.txt", "w")  # Open the input file and get # the content into a variable datawith open("file.txt", "r") as myfile:    data = myfile.read()  # For Full Reversing we will store the # value of data into new variable data_1 # in a reverse order using [start: end: step],# where step when passed -1 will reverse # the stringdata_1 = data[::-1]  # Now we will write the fully reverse # data in the output1 file using # following commandf1.write(data_1)  f1.close()
Output: 
Example 2: Reversing the order of lines. We will use the above text file as input. 
Python3
# Open the file in write modef2 = open("output2.txt", "w")    # Open the input file again and get # the content as list to a variable datawith open("file.txt", "r") as myfile:    data = myfile.readlines()  # We will just reverse the # array using following codedata_2 = data[::-1]  # Now we will write the fully reverse # list in the output2 file using # following commandf2.writelines(data_2)  f2.close()
Output: 
 
rouzbeha
Python DSA-exercises
Python file-handling-programs
python-file-handling
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
C Program to check if a date is valid or not

Given date in format date, month and year in integer. The task is to find whether the date is possible on not.
Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid.
These dates would not only contains range of year but also all the constraints related to a calendar date.
Constraints are −
Date can’t be less than 1 and more than 31
Month can’t be less than 1 and more than 12
Year can’t be less than 1800 and more than 9999
When the months are April, June, September, November the date can’t be more than 30.
When the month is February we have to check whether,If the year is leap year then the number of days can’t be more than 29Else the number of days can’t be more than 28.
If the year is leap year then the number of days can’t be more than 29
Else the number of days can’t be more than 28.
If all the constraints are true then it is a valid date, Else it is not.
Input: y = 2002
   d = 29
   m = 11
Output: Date is valid
Input: y = 2001
   d = 29
   m = 2
Output: Date is not valid
START
In function int isleap(int y)
   Step 1-> If (y % 4 == 0) && (y % 100 != 0) && (y % 400 == 0) then,
      Return 1
   Step 2-> Else
      Return 0
In function int datevalid(int d, int m, int y)
   Step 1-> If y < min_yr || y > max_yr then,
      Return 0
   Step 2-> If m < 1 || m > 12 then,
      Return 0
   Step 3-> If d < 1 || d > 31 then,
      Return 0
   Step 4-> If m == 2 then,
      If isleap(y) then,
         If d <= 29 then,
            Return 1
         Else
            Return 0
         End if
      End if
   Step 5-> If m == 4 || m == 6 || m == 9 || m == 11 then,
      If(d <= 30)
         Return 1
      Else
         Return 0
         Return 1
      End Function
In main(int argc, char const *argv[])
   Step 1->Assign and initialize values as y = 2002, d = 29, m = 11
   Step 2-> If datevalid(d, m, y) then,
      Print "Date is valid"
   Step 3-> Else
      Print "date is not valid”
   End main
STOP
 Live Demo
#include <stdio.h>
#define max_yr 9999
#define min_yr 1800
//to check the year is leap or not
//if the year is a leap year return 1
int isleap(int y) {
   if((y % 4 == 0) && (y % 100 != 0) && (y % 400 == 0))
      return 1;
   else
      return 0;
}
//Function to check the date is valid or not
int datevalid(int d, int m, int y) {
   if(y < min_yr || y > max_yr)
      return 0;
   if(m < 1 || m > 12)
      return 0;
   if(d < 1 || d > 31)
      return 0;
      //Now we will check date according to month
   if( m == 2 ) {
      if(isleap(y)) {
         if(d <= 29)
            return 1;
         else
            return 0;
         }
      }
      //April, June, September and November are with 30 days
      if ( m == 4 || m == 6 || m == 9 || m == 11 )
         if(d <= 30)
            return 1;
         else
            return 0;
            return 1;
   }
int main(int argc, char const *argv[]) {
   int y = 2002;
   int d = 29;
   int m = 11;
      if(datevalid(d, m, y))
         printf("Date is valid\n");
      else
         printf("date is not valid\n");
      return 0;
}
If run the above code it will generate the following output −
Date is valid
C++ program to Check if a Given Binary Tree is an AVL Tree or Not

AVL tree is a self-balancing Binary Search Tree where the difference between heights of left and right subtrees cannot be more than one for all nodes.
This is a C++ program to check if a given Binary Tree is an AVL Tree or not.
Begin
function AVL() returns true if the given tree is AVL otherwise false.
   if(root == NULL)
      return 1
   leftheight = height(root->left)
   rightheight = height(root->right)
   if(abs(leftheight-rightheight) <= 1 && AVL(root->left) && AVL(root->right))
      return 1
   return 0
End
#include <bits/stdc++.h>
using namespace std;
class nod { //node declaration
   public:
   int data;
   nod* l;
   nod* r;
};
nod* newNod(int d) { //creation of new node
   nod* Nod = new nod();
   Nod->data = d;
   Nod->l = NULL;
   Nod->r = NULL;
   return(Nod);
}
int max(int x, int y) { //return maximum between two values
   return (x >= y)? x: y;
}
int height(nod* node) { //get the height means the number of nodes along the longest path from the root
node down to the farthest leaf node of the tree. 
   if(node == NULL)
      return 0;
   return 1 + max(height(node->l), height(node->r));
}
bool AVL(nod *root) {
   int lh;
   int rh;
   if(root == NULL)
      return 1;
   lh = height(root->l); // left height
   rh = height(root->r); // right height
   if(abs(lh-rh) <= 1 && AVL(root->l) && AVL(root->r)) return 1;
   return 0;
}
int main() {
   //take the nodes of the tree as input
   nod *root = newNod(7);
   root->l = newNod(6);
   root->r = newNod(12);
   root->l->l = newNod(4);
   root->l->r = newNod(5);
   root->r->r = newNod(13);
   if(AVL(root))
      cout << "The Tree is AVL Tree"<<endl;
   else
      cout << "The Tree is not AVL Tree "<<endl;
   nod *root1 = newNod(7);
   root1->l = newNod(6);
   root1->r = newNod(12);
   root1->l->l = newNod(4);
   root1->l->r = newNod(5);
   root1->r->r = newNod(13);
   root1->r->r->r = newNod(26);
   if(AVL(root1))
      cout << "The Tree is AVL Tree"<<endl;
   else
      cout << "The Tree is not AVL Tree "<<endl;
   return 0;
}
The Tree is AVL Tree
The Tree is not AVL Tree
Self Destructing Code in C

Here we will see how to create self-destructing code in C. The self-destructing code is basically executing the code, and then remove the executable file after executing it.
This task is very simple. We need to get the executable file name to remove it. We can use the command line arguments. The argv[0] will hold the executable filename. Then using remove() function we can remove it.
In the program we can see that one line is printing after the removing of that file. So now question comes how the next line is executing while current file is not present?
Actually the entire converted code is copied into primary memory before executing it. The executing file content is copied; it is not used itself. So from the primary memory, the next line will be printed.
#include<stdio.h>
int main(int c, char *argv[]) {
   printf("After completing this, the file will be removed\n");
   remove(argv[0]); //remove the argv[0] this is the name of the executable
   printf("Removed\n");
   return 0;
}
After completing this, the file will be removed
Removed
How to find anchor tag in div and add class using jQuery?

To find anchor tag in div, use a selector and the addClass() method adds a class using jQuery.
You can try to run the following code to learn how to find anchor tag in div and add class:
Live Demo
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
           $("#button1").click(function(){
             $('#div1 a').addClass('myclass');
           });
        });
      </script>
     
         <style>
          .myclass {
             font-size: 25px;
           }
         </style>

   </head>
   <body>
      <div id="div1">
         <a href="http://www.google.com">Demo</a>
      </div>
      <div id="div2">
         <p>This is demo text.</p>
      </div>
      <button id="button1">Click</button>
   </body>
</html>
Multiple Inheritance in C++

Multiple inheritance occurs when a class inherits from more than one base class. So the class can inherit features from multiple base classes using multiple inheritance. This is an important feature of object oriented programming languages such as C++.
A diagram that demonstrates multiple inheritance is given below −
A program to implement multiple inheritance in C++ is given as follows −
 Live Demo
#include <iostream>
using namespace std;

class A {
   public:
   int a = 5;
   A() {
      cout << "Constructor for class A" << endl;
   }
};
class B {
   public:
   int b = 10;
   B() {
      cout << "Constructor for class B" << endl;
   }
};
class C: public A, public B {
   public:
   int c = 20;
   C() {
      cout << "Constructor for class C" << endl;
      cout<<"Class C inherits from class A and class B" << endl;
   }
};
int main() {
   C obj;
   cout<<"a = "<< obj.a <<endl;
   cout<<"b = "<< obj.b <<endl;
   cout<<"c = "<< obj.c <<endl;
   return 0;
}
The output of the above program is given as follows −
Constructor for class A
Constructor for class B
Constructor for class C
Class C inherits from class A and class B
a = 5
b = 10
c = 20
In the above program, classes A and B are defined. This is given below −
class A {
   public:
   int a = 5;
   A() {
      cout << "Constructor for class A" << endl;
   }
};
class B {
   public:
   int b = 10;
   B() {
      cout << "Constructor for class B" < endl;
   }
};
Class C inherits from both classes A and B. It is an example of multiple inheritance. Class C definition is shown below −
class C: public A, public B {
   public:
   int c = 20;
   C() {
      cout << "Constructor for class C" << endl;
      cout<<"Class C inherits from class A and class B" << endl;
   }
};
In main() function, an object obj of class C is defined. The constructors of Class A, B and C are automatically called and their contents are displayed. Then the values of a, b and c are printed. These are data members of classes A, B and C respectively. The code snippet for this is as follows −
C obj;
cout<<"a = "<< obj.a <<endl;
cout<<"b = "<< obj.b <<endl;
cout<<"c = "<< obj.c <<endl;
C library function - strtol()

The C library function long int strtol(const char *str, char **endptr, int base) converts the initial part of the string in str to a long int value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.
Following is the declaration for strtol() function.
long int strtol(const char *str, char **endptr, int base)
str − This is the string containing the representation of an integral number.
str − This is the string containing the representation of an integral number.
endptr − This is the reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
endptr − This is the reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
base − This is the base, which must be between 2 and 36 inclusive, or be the special value 0.
base − This is the base, which must be between 2 and 36 inclusive, or be the special value 0.
This function returns the converted integral number as a long int value, else zero value is returned.
The following example shows the usage of strtol() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   char str[30] = "2030300 This is test";
   char *ptr;
   long ret;

   ret = strtol(str, &ptr, 10);
   printf("The number(unsigned long integer) is %ld\n", ret);
   printf("String part is |%s|", ptr);

   return(0);
}
Let us compile and run the above program that will produce the following result −
The number(unsigned long integer) is 2030300
String part is | This is test|


    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
Largest Sum Contiguous Subarray

An array of integers is given. We have to find the sum of all elements which are contiguous, whose sum is largest, that will be sent as output.
Using dynamic programming we will store the maximum sum up to current term. It will help to find the sum for contiguous elements in the array.
Input:
An array of integers. {-2, -3, 4, -1, -2, 1, 5, -3}
Output:
Maximum Sum of the Subarray is: 7
maxSum(array, n)
Input − The main array, the size of the array.
Output − maximum sum.
Begin
   tempMax := array[0]
   currentMax = tempMax
   for i := 1 to n-1, do
      currentMax = maximum of (array[i] and currentMax+array[i])
      tempMax = maximum of (currentMax and tempMax)
   done
   return tempMax
End
#include<iostream>
using namespace std;

int maxSum( int arr[], int n) {
   int tempMax = arr[0];
   int currentMax = tempMax;

   for (int i = 1; i < n; i++ ) { //find the max value
      currentMax = max(arr[i], currentMax+arr[i]);
      tempMax = max(tempMax, currentMax);
   }
   return tempMax;
}

int main() {
   int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
   int n = 8;
   cout << "Maximum Sum of the Sub-array is: "<< maxSum( arr, n );
}
Maximum Sum of the Sub-array is: 7
Difference between Methods and Functions in JavaScript - GeeksforGeeks

11 Apr, 2022
JavaScript Functions: A function is a block of code written to perform some specific set of tasks. We can define a function using the function keyword, followed by Name and optional parameters. Body of function is enclosed in Curly braces.
Syntax: 
function functionName(parameters) {
    // Content
}
Features:
The function is executed when something calls/invokes it.
The name may contain letters, digits, dollar signs, underscore.
Parameters are listed inside round parenthesis after the name of the function.
Arguments are values a function receives when it is invoked.
When the control reaches the return statement, js will stop executing and the value is returned to the caller.
Example: Below is the function to add two numbers.
Javascript
function func(a, b) {var sum = a + b;return sum;}console.log(func(1, 2));
Output:
3
JavaScript Methods: A JavaScript method is a property of an object that contains a function definition. Methods are functions stored as object properties. Object method can be accessed with the following syntax:
Syntax:
object = {
    methodName: function() {
        // Content
    }
};

object.methodName()
Features:
Actions that can be performed on objects are what we term JavaScript methods.
The objects can also be called without using parenthesis.
This refers to the owner object in a method.
Example: The following example shows the method that is invoked with an object called employee.
Javascript
<html>    <head>        <script>            var employee = {                empname: "Rahul",                department : "sales",                details : function() {                    return this.empname +                        " works with Department " +                        this.department;                }            };            console.log(employee.details());        </script>    </head></html>
Output:
Rahul works with Department sales
Difference Between Function and Method:
Function
Method
Syntax of Function is -:
function functionName(parameters) {   // Content}
Syntax of Method is -:
object = {   methodName: function() {       // Content   }};
object.methodName()
We can access object method by following syntax -:
objectName.methodName()
bunnyram19
mayank007rawa
JavaScript-Misc
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between HashMap and HashSet
Difference between Internal and External fragmentation
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
How to Add Cron Jobs to A Specific User in a Linux System

This article we will teach you to schedule a cron job to be executed at a specific time in a day.
MIN    HOUR    Day of month    Month    Day of Week    Command
0-59   0-23       1-31          1-12       0-6       linux command or script
To see the list of cron jobs which exists on the machine, run the below command
# crontab -u test1 -l
no crontab for test1
#crontab -u test1 -e
no crontab for test1 - using an empty one
Select an editor. To change later, run 'select-editor'.
/bin/ed
/bin/nano <---- easiest
/usr/bin/vim.basic
/usr/bin/vim.tiny
Choose 1-4 [2]:2
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (backup_files.sh) on Every day at 9 AM and 6 PM
00 09-18 * * * /home/test1/backup_files.sh
00 – 00th Minute
09-18 – 09 AM & 06:00PM
* --Every day of the Month
* -- Every Month.
* --Every day of the week
At the end of the configuration, you should be able to run a script or command at a specific time every day from a particular user. Like this, we can specify Cron jobs to any user. These type of Crons are generally used to take a backup of the users data such as Desktop, Downloads etc.
Search an element of ArrayList in Java

An element in an ArrayList can be searched using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurance of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      int index1 = aList.indexOf("C");
      int index2 = aList.indexOf("Z");
      if(index1 == -1)
         System.out.println("The element C is not in the ArrayList");
      else
         System.out.println("The element C is in the ArrayList at index " + index1);
      if(index2 == -1)
         System.out.println("The element Z is not in the ArrayList");
      else
         System.out.println("The element Z is in the ArrayList at index " + index2);
   }
}
The element C is in the ArrayList at index 2
The element Z is not in the ArrayList
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows −
List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");
ArrayList.indexOf() returns the index of the first occurrence of “C” and “Z” that is stored in index1 and index2 respectively. Then an if statement is used to check if index1 is -1. If so, then C is not in ArrayList. A similar procedure is done with index2 and the results are printed. A code snippet which demonstrates this is as follows −
int index1 = aList.indexOf("C");
int index2 = aList.indexOf("Z");
if(index1 == -1)
   System.out.println("The element C is not in the ArrayList");
else
   System.out.println("The element C is in the ArrayList at index " + index1);
if(index2 == -1)
   System.out.println("The element Z is not in the ArrayList");
else
   System.out.println("The element Z is in the ArrayList at index " + index2);
How can we update a record in MongoDB?

To update a record, you need to update on the basis of _id. Let us create a collection with documents −
> db.demo458.insertOne( {_id:101,"Name":"David" } );
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo458.insertOne( {_id:102,"Name":"Chris" } );
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo458.insertOne( {_id:103,"Name":"Bob" } );
{ "acknowledged" : true, "insertedId" : 103 }
Display all documents from a collection with the help of find() method −
> db.demo458.find();
This will produce the following output −
{ "_id" : 101, "Name" : "David" }
{ "_id" : 102, "Name" : "Chris" }
{ "_id" : 103, "Name" : "Bob" }
Following is the query to update a record in MongoDB −
> db.demo458.update({_id:102},{$set:{"Name":"David Miller"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo458.find();
This will produce the following output −
{ "_id" : 101, "Name" : "David" }
{ "_id" : 102, "Name" : "David Miller" }
{ "_id" : 103, "Name" : "Bob" }
Perl split Function

This function splits a string expression into fields based on the delimiter specified by PATTERN. If no pattern is specified whitespace is the default. An optional limit restricts the number of elements returned.
A negative limit has the same effect as no limit. This function is often used in conjunction with join() to create small text databases.
Following is the simple syntax for this function −
split /PATTERN/, EXPR, LIMIT

split /PATTERN/, EXPR

split /PATTERN/

split

Return Value in Scalar Context: Not recommended, but it returns the number of fields found and stored the fields in the @_ array.
Return Value in Scalar Context: Not recommended, but it returns the number of fields found and stored the fields in the @_ array.
Return Value in Array Context: A list of fields found in EXPR or $_ if no expression is specified.
Return Value in Array Context: A list of fields found in EXPR or $_ if no expression is specified.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

@fields = split(/:/, "1:2:3:4:5");
print "Field values are: @fields\n";
When above code is executed, it produces the following result −
Field values are: 1 2 3 4 5


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
dirname command in Linux with examples - GeeksforGeeks

15 May, 2019
dirname is a command in Linux which is used to remove the trailing forward slahes “/” from the NAME and prints the remaining portion. If the argument NAME does not contains the forward slash “/” then it simply prints dot “.”.
Syntax:
dirname [OPTION] NAME
Options provided by dirname:
dirname -zero NAME or dirname --z NAME : This option provides a way to end the line by a null command rather then a new line. Using this the next command will execute on the same line rather than on the next line.
dirname --help : It displays help information.
dirname --version : It displays version information.
linux-command
Linux-directory-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
How to find the row sums by excluding a column in R data frame?

Suppose we have a numerical column in an R data frame that we do not want to include
our analysis due to some characteristics such is similarity or distinction with the rest of the data then we might want to exclude that column from the analysis. One such situation would be finding the row sums by excluding a column. For this purpose, we can use the below steps −
First of all, creating a data frame.
Finding the row sums with the help of mutate function of dplyr package and
setdiff function in base R
Let's create a data frame as shown below −
 Live Demo
x1<-round(rnorm(20),2)
x2<-round(rnorm(20),2)
x3<-round(rnorm(20),2)
df<-data.frame(x1,x2,x3)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
   x1    x2    x3
1 0.67  0.63 -0.12
2 -0.41 0.36 -1.14
3 0.73  0.85  0.29
4 -3.14 0.16  0.65
5 -0.07 0.76  0.07
6 -0.05 -0.26 -2.03
7 -1.61 0.36  0.88
8 -1.48 -0.90 1.10
9 - 2.27 -2.92 -0.06
10 -0.78 -1.89 -0.10
11 -0.06 -1.30 -1.43
12 -0.15 -0.57 0.40
13 0.31 -0.46 -0.46
14 -0.40 -0.16 -1.06
15 -0.07 -1.62 -0.23
16 0.29  0.00  0.29
17 -0.61 0.53 1.67
18 0.86 -0.54 -1.40
19 0.85 0.17 -0.37
20 0.61 -1.46 0.27
Using mutate function of dplyr package to find the row sums by excluding the column x3 with setdiff function −
x1<-round(rnorm(20),2)
x2<-round(rnorm(20),2)
x3<-round(rnorm(20),2)
df<-data.frame(x1,x2,x3)
library(dplyr)
df %>% mutate(RowSum=rowSums(.[setdiff(names(.),"x3")]))
   x1    x2    x3  RowSum
1  0.67  0.63 -0.12 1.30
2  -0.41 0.36 -1.14 -0.05
3  0.73  0.85  0.29  1.58
4 -3.14  0.16  0.65 -2.98
5 -0.07  0.76  0.07  0.69
6 -0.05 -0.26 -2.03 -0.31
7 -1.61  0.36  0.88 -1.25
8 -1.48 -0.90  1.10 -2.38
9 -2.27 -2.92 -0.06 -5.19
10 -0.78 -1.89 -0.10 -2.67
11 -0.06 -1.30 -1.43 -1.36
12 -0.15 -0.57 0.40 -0.72
13  0.31  -0.46 -0.46 -0.15
14 -0.40 -0.16 -1.06 -0.56
15 -0.07 -1.62 -0.23 -1.69
16  0.29  0.00  0.29 0.29
17 -0.61  0.53  1.67  -0.08
18  0.86 -0.54 -1.40 0.32
19  0.85 0.17 -0.37 1.02
20  0.61 -1.46 0.27 -0.85
How to sum values of a Python dictionary?

It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict.values(). Then you can call the sum method to get the sum of these values. 
d = {
   'foo': 10,
   'bar': 20,
   'baz': 30
}
print(sum(d.values()))
This will give the output −
60
C++ program to test inheritance through triangle class

Suppose we want to make one Triangle class and another child class called Isosceles. The triangle class has a function that prints that the object is of type triangle, and Isosceles has two functions to show that it is an isosceles triangle and one description. We also need to call the parent class function through Isosceles class object. There is no such proper input, we just call functions in proper way.
So, if the input is like define an object called trg, then call trg.isosceles(), trg.description(), trg.triangle()., then the output will be
This is an isosceles triangle
There are two sides are equal in an isosceles triangle
This is a triangle
To solve this, we will follow these steps −
Define the first Triangle class with public/protected function triangle()
Define the first Triangle class with public/protected function triangle()
Define Isosceles class with public inheritance where two methods are present called isosceles() and description()
Define Isosceles class with public inheritance where two methods are present called isosceles() and description()
Let us see the following implementation to get better understanding −
#include <iostream>
using namespace std;
class Triangle{
    public:
       void triangle(){
           cout<<"This is a triangle" << endl;
       }
};
class Isosceles : public Triangle{
    public:
       void isosceles(){
          cout<<"This is an isosceles triangle" << endl;
       }
       void description(){
          cout<<"There are two sides are equal in an isosceles triangle" << endl;
       }
};
int main(){
    Isosceles trg;
    trg.isosceles();
    trg.description();
    trg.triangle();
}

Isosceles trg;
trg.isosceles();
trg.description();
trg.triangle();
This is an isosceles triangle
There are two sides are equal in an isosceles triangle
This is a triangle
MomentJS - Long Date Formats

This method helps in customizing longdateformat for a locale.
moment.updateLocale('en', {
   longDateFormat : Object
});

Here longDateFormat is an object containing key / value pair for each format.
var localeData = moment.updateLocale('fr', {
   longDateFormat: {
      LT: "h:mm",
      LTS: "h:mm:ss A",
      L: "MM/DD/YYYY",
      l: "M/D/YYYY",
      LL: "MMMM Do YYYY",
      ll: "MMM D YYYY",
      LLL: "MMMM Do YYYY LT",
      lll: "MMM D YYYY LT",
      LLLL: "dddd, MMMM Do YYYY LT",
      llll: "ddd, MMM D YYYY LT"
   }
});
var m = moment().format('LT');
var x = moment().format('LLLL');
 Print
 Add Notes
 Bookmark this page
Getting binomial coefficient of a number in Julia - binomial() Method - GeeksforGeeks

21 Apr, 2020
The binomial() is an inbuilt function in julia which is used to return the binomial coefficient  which is the coefficient of the kth term in the polynomial expansion of .Its formula is –
    
, where  is the factorial of n.If n is negative, then it is defined in terms of the identity
    
.
Syntax: binomial(n::Integer, k::Integer)
Parameters:
n: Specified number
k: Specified number
Returns: It returns the binomial coefficient .
Example 1:
# Julia program to illustrate # the use of binomial() method  # Getting the binomial coefficientprintln(binomial(6, 4))println(factorial(6) ÷ (factorial(6-4) * factorial(4)))
Output:
15
15

Example 2:
# Julia program to illustrate # the use of binomial() method  # Getting the binomial coefficientprintln(binomial(6, 3))println(binomial(-6, 3))println(binomial(-6, -2))println(binomial(5, 2))
Output:
20
-56
0
10

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

Unlike for and while loops, which test the loop condition at the top of the loop, the repeat ... until loop in Pascal checks its condition at the bottom of the loop.
A repeat ... until loop is similar to a while loop, except that a repeat ... until loop is guaranteed to execute at least one time.
repeat
   S1;
   S2;
   ...
   ...
   Sn;
until condition;
For example,
repeat
   sum := sum + number;
   number := number - 2;
until number = 0;
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
If the condition is false, the flow of control jumps back up to repeat, and the statement(s) in the loop execute again. This process repeats until the given condition becomes true.
program repeatUntilLoop;
var
   a: integer;

begin
   a := 10;
   (* repeat until loop execution *)
   repeat
      writeln('value of a: ', a);
      a := a + 1
   until a = 20;
end.
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Tcl - Procedures

Procedures are nothing but code blocks with series of commands that provide a specific reusable functionality. It is used to avoid same code being repeated in multiple locations. Procedures are equivalent to the functions used in many programming languages and are made available in Tcl with the help of proc command.
The syntax of creating a simple procedure is shown below −
proc procedureName {arguments} {
   body
}

A simple example for procedure is given below −
#!/usr/bin/tclsh

proc helloWorld {} {
   puts "Hello, World!"
}
helloWorld
When the above code is executed, it produces the following result −
Hello, World!

An example for procedure with arguments is shown below −
#!/usr/bin/tclsh

proc add {a b} {
   return [expr $a+$b]
}
puts [add 10 30]
When the above code is executed, it produces the following result −
40

An example for procedure with arguments is shown below −
#!/usr/bin/tclsh

proc avg {numbers} {
   set sum 0
   foreach number $numbers {
      set sum  [expr $sum + $number]
   }
   set average [expr $sum/[llength $numbers]]
   return $average
}
puts [avg {70 80 50 60}]
puts [avg {70 80 50 }]
When the above code is executed, it produces the following result −
65
66

Default arguments are used to provide default values that can be used if no value is provided. An example for procedure with default arguments, which is sometimes referred as implicit arguments is shown below −
#!/usr/bin/tclsh

proc add {a {b 100} } {
   return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]
When the above code is executed, it produces the following result −
40
110

An example for recursive procedures is shown below −
#!/usr/bin/tclsh

proc factorial {number} {
   if {$number <= 1} {
      return 1
   } 
   return [expr $number * [factorial [expr $number - 1]]]

}
puts [factorial 3]
puts [factorial 5]
When the above code is executed, it produces the following result −
6
120

 Print
 Add Notes
 Bookmark this page