code-rag-bench/online-tutorials huggingface dataset:
Difference between COMP and COMP3

27 Sep, 2021
Internally the computer stores the data in more than one form. The Cobol language facilitates the programmer to specify the  internal representation of the data according to the need. There are two internal forms available in the Cobol:
DISPLAY –It is the default internal representation of the data. Any type of data can be specified with the DISPLAY internal representation.COMPUTATIONAL –Only the numeric data’s can be specified with COMPUTATIONAL internal representation. There are many types of COMPUTATIONAL representation, like COMP, COMP-1 , COMP-2, COMP-3 etc.
DISPLAY –It is the default internal representation of the data. Any type of data can be specified with the DISPLAY internal representation.
COMPUTATIONAL –Only the numeric data’s can be specified with COMPUTATIONAL internal representation. There are many types of COMPUTATIONAL representation, like COMP, COMP-1 , COMP-2, COMP-3 etc.
USAGE clause is used to specify the type of internal representation. You can use any level-number for USAGE clause except 66 or 88.
Syntax:
        USAGE IS {COMPUTATIONAL/COMP/DISPLAY}.
1. COMP :Usage clause is applicable only on numerical data items. It represents the data purely in binary form. and can store the data either in half word or in full word depending on the size of the data. We can use only 9 and S during the data declaration:
9 is used to store declare integer variables.
S is used to store the sign.
2. COMP3 :Usage clause is applicable only on numerical data items. It stores the data in packed decimal form. It uses one rightmost bit to store the sign irrespective of weather we have used S in PIC clause or not. The hexadecimal number C and F stores the positive sign at rightmost bit and D stores the negative sign at rightmost bit. We can use 9, S and V in PIC clause during data declaration.
V is used to store decimal point at a particular location in data item.
Difference between COMP and COMP3 :
COMP
COMP3
The memory to be occupied by the data according to the length is predefined i.e. :
9(01) – 9(04) : 16 bits (2 bytes)
9(05) – 9(09) :  32 bits (4 bytes)
S9(10) – S9(18) :  64 bits (8 bytes)
The memory to be occupied by the data is defined by the following formula:
(length of variable + 1)/2 bytes.
Example : The memory occupied by S9(3) is:
(3+1)/2 i.e. 2 bytes.
Example:
        02 CompVariable PIC 9 USAGE IS COMP.
        02 CompVariable1 PIC S9(5) USAGE IS COMP.
Example:
        02 Variable PIC 9 USAGE IS COMP3.
        02 Variable1 PIC S9(10) USAGE IS COMP3.
        02 Variable2 PIC S9V99 USAGE IS COMP3.
Picked
COBOL
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
50 Common Ports You Should Know
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
Layers of OSI Model
TCP/IP Model
Basics of Computer Networking
Differences between TCP and UDP
Types of Network Topology
numpy.mask_indices() function | Python

22 Apr, 2020
numpy.mask_indices() function return the indices to access (n, n) arrays, given a masking function.
Syntax : numpy.mask_indices(n, mask_func, k = 0)Parameters :n : [int] The returned indices will be valid to access arrays of shape (n, n).mask_func : [callable] A function whose call signature is similar to that of triu, tril.k : [scalar] An optional argument which is passed through to mask_func.Return : [tuple of arrays] The n arrays of indices corresponding to the locations where mask_func(np.ones((n, n)), k) is True.
Code #1 :
# Python program explaining# numpy.mask_indices() function  # importing numpy as geek import numpy as geek  gfg = geek.mask_indices(3, geek.triu)  print (gfg)
Output :
(array([0, 0, 0, 1, 1, 2]), array([0, 1, 2, 1, 2, 2]))

 Code #2 :
# Python program explaining# numpy.mask_indices() function  # importing numpy as geek import numpy as geek  gfg = geek.mask_indices(3, geek.triu, 1)  print (gfg)
Output :
(array([0, 0, 1]), array([1, 2, 2]))

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Consecutive Pairs comma removal

28 Jun, 2022
Sometimes, while working amongst lists, we can have a problem in which we need to pair up elements from two lists. In this, we can have pairs in which we find that there is comma that is printed in tuple and we wish to avoid it usually. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + list comprehension + replace() The combination of above functionalities can be used to perform this task. In this, we join lists using zip() and task of removal of comma and joining is performed using replace(). 
Python3
# Python3 code to demonstrate# Consecutive Pairs Duplication Removal# using list comprehension + zip() + replace() # Initializing liststest_list1 = [1, 2, 3, 4, 5]test_list2 = [2, 3, 4, 5, 6] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Consecutive Pairs Duplication Removal# using list comprehension + zip() + replace()res = str(list(zip(test_list1, test_list2))).replace('), (', ') (')         # printing resultprint ("The combined list after consecutive comma removal : " + str(res))
The original list 1 is : [1, 2, 3, 4, 5]
The original list 2 is : [2, 3, 4, 5, 6]
The combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]
  Method #2 : Using map() + list comprehension + zip() This is yet another way in which this task can be performed. In this we perform the task performed using replace() with map(). 
Python3
# Python3 code to demonstrate# Consecutive Pairs Duplication Removal# using list comprehension + zip() + map() # Initializing liststest_list1 = [1, 2, 3, 4, 5]test_list2 = [2, 3, 4, 5, 6] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Consecutive Pairs Duplication Removal# using list comprehension + zip() + map()res = "[" + " ".join(map(str, zip(test_list1, test_list2))) + "]"         # printing resultprint ("The combined list after consecutive comma removal : " + str(res))
The original list 1 is : [1, 2, 3, 4, 5]
The original list 2 is : [2, 3, 4, 5, 6]
The combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]
vinayedula
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Safe access nested dictionary keys

14 May, 2020
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let’s discuss certain ways to safely get the nested available key in dictionary.
Method #1 : Using nested get()
This method is used to solve this particular problem, we just take advantage of the functionality of get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present.
# Python3 code to demonstrate working of# Safe access nested dictionary key# Using nested get()  # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # using nested get()# Safe access nested dictionary keyres = test_dict.get('Gfg', {}).get('is')  # printing resultprint("The nested safely accessed value is :  " + str(res))
The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is :  best

 
Method #2 : Using reduce() + lambda
The combination of above functions can be used to perform this particular task. It just checks using lambda function for the available keys. The plus of this method is that more than 1 key can be queried at once i.e more nested level keys, but the negative is that it does only work with Python2.
# Python code to demonstrate working of# Safe access nested dictionary key# Using reduce() + lambda  # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # using reduce() + lambda# Safe access nested dictionary keykeys = ['Gfg', 'is']res = reduce(lambda val, key: val.get(key) if val else None, keys, test_dict)  # printing resultprint("The nested safely accessed value is :  " + str(res))
The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is :  best

Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
SQL query to check SAP HANA system version

Other option to check the version of SAP HANA database-
Select * from "SYS"."M_DATABASE";
Go to SQL editor and run the above command.
Go to Result tab and you can see the version of your SAP HANA system.
How to create a lagged variable in R for groups?

Lagged variable is the type of variable that contains the previous value of the variable for which we want to create the lagged variable and the first value is neglected. Therefore, we will always have one missing value in each of the groups, if we are creating a lagged variable that depends on a grouping variable or factor variable.
Consider the below data frame:
> set.seed(2)
> Factor<-rep(c("F1","F2","F3","F4"),each=5)
> Rate<-c(12,54,18,26,14,25,81,47,15,12,96,25,14,34,68,78,42,56,81,75)
> df<-data.frame(Factor,Rate)
> df
Factor Rate
1 F1 12
2 F1 54
3 F1 18
4 F1 26
5 F1 14
6 F2 25
7 F2 81
8 F2 47
9 F2 15
10 F2 12
11 F3 96
12 F3 25
13 F3 14
14 F3 34
15 F3 68
16 F4 78
17 F4 42
18 F4 56
19 F4 81
20 F4 75
Creating a lagged variable for Rate treating Factor variable as group variable −
> df$Lagged_Variable <- c(NA, df$Rate[-nrow(df)])
> df$Lagged_Variable[which(!duplicated(df$Factor))] <- NA
> df
Factor Rate Lagged_Variable
1 F1 12 NA
2 F1 54 12
3 F1 18 54
4 F1 26 18
5 F1 14 26
6 F2 25 NA
7 F2 81 25
8 F2 47 81
9 F2 15 47
10 F2 12 15
11 F3 96 NA
12 F3 25 96
13 F3 14 25
14 F3 34 14
15 F3 68 34
16 F4 78 NA
17 F4 42 78
18 F4 56 42
19 F4 81 56
20 F4 75 81
Python program to right rotate a list by n - GeeksforGeeks

28 Mar, 2022
Given a list and an integer n, write a Python program to right rotate the list by n position.
Examples : 
Input : n = 2, List_1 = [1, 2, 3, 4, 5, 6]Output : List_1 = [5, 6, 1, 2, 3, 4]Explanation: We get output list after right rotating (clockwise) given list by 2.
Input :  n = 3, List_1 = [3, 0, 1, 4, 2, 3]Output : List_1 = [4, 2, 3, 3, 0, 1]
Approach #1 : Traverse the first list one by one and then put the elements at required places in a second list. 
Python3
# Python program to right rotate a list by n # Returns the rotated list def rightRotate(lists, num):    output_list = []     # Will add values from n to the new list    for item in range(len(lists) - num, len(lists)):        output_list.append(lists[item])     # Will add the values before    # n to the end of new list    for item in range(0, len(lists) - num):        output_list.append(lists[item])     return output_list  # Driver Coderotate_num = 3list_1 = [1, 2, 3, 4, 5, 6] print(rightRotate(list_1, rotate_num))
[4, 5, 6, 1, 2, 3]

Time complexity : O(n)
Approach #2 : Another approach to solve this problem by using slicing technique. One way of slicing list is by using len() method. 
Python3
# Python program to right rotate# a list by n using list slicingn = 3 list_1 = [1, 2, 3, 4, 5, 6]list_1 = (list_1[len(list_1) - n:len(list_1)]                 + list_1[0:len(list_1) - n])print(list_1)
[4, 5, 6, 1, 2, 3]

Approach #3 : In the above method, last n elements of list_1 was taken and then remaining elements of list_1. Another way is without using len() method.  
Python
# Right Rotating a list to n positionsn = 3 list_1 = [1, 2, 3, 4, 5, 6]if n>len(list_1):    n = int(n%len(list_1))list_1 = (list_1[-n:] + list_1[:-n]) print(list_1)
[4, 5, 6, 1, 2, 3]

Time complexity : O(n)
Note : list_1[:] will return the whole list as the blank space on left of slicing operator refers to start of list i.e 0 and blank space on right refers to ending position of list. 
akash mc
nitinnathoms
Namrata_Tiwari
Python list-programs
python-list
Python
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
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
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Tryit Editor v3.7

Tryit: HTML paragraphs with hr
GATE | GATE-CS-2006 | Question 85 - GeeksforGeeks

15 Oct, 2019
Consider the following log sequence of two transactions on a bank account, with initial balance 12000, that transfer 2000 to a mortgage payment and then apply a 5% interest.
  1. T1 start
  2. T1 B old=12000 new=10000
  3. T1 M old=0 new=2000
  4. T1 commit
  5. T2 start
  6. T2 B old=10000 new=10500
  7. T2 commit 
Suppose the database system crashes just before log record 7 is written. When the system is restarted, which one statement is true of the recovery procedure?(A) We must redo log record 6 to set B to 10500(B) We must undo log record 6 to set B to 10000 and then redo log records 2 and 3.(C) We need not redo log records 2 and 3 because transaction T1 has committed.(D) We can apply redo and undo operations in arbitrary order because they are idempotentAnswer: (B)Explanation: We must undo log record 6 to set B to 10000 and then redo log records 2 and 3 bcoz system fail before commit operation. So we need to undone active transactions(T2) and redo committed transactions (T1)
Note: Here we are not using checkpoints.
Checkpoint : Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed.
Recovery:When a system with concurrent transactions crashes and recovers, it behaves in the following manner −
=>The recovery system reads the logs backwards from the end to the last checkpoint.
=>It maintains two lists, an undo-list and a redo-list.
=>If the recovery system sees a log with and or just , it puts the transaction in the redo-list.
=>If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list.
All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs.
So Answer is B redo log records 2 and 3 and undo log record 6Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
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-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
How can we check the current MySQL transaction isolation level?

By executing SELECT @@TX_ISOLATION command we can check the current MySQL transaction isolation level.
mysql> SELECT @@TX_ISOLATION;
+-----------------+
| @@TX_ISOLATION  |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set (0.00 sec)
Python NLTK | nltk.tokenize.SpaceTokenizer()

07 Jun, 2019
With the help of nltk.tokenize.SpaceTokenizer() method, we are able to extract the tokens from string of words on the basis of space between them by using tokenize.SpaceTokenizer() method.
Syntax : tokenize.SpaceTokenizer()Return : Return the tokens of words.
Example #1 :In this example we can see that by using tokenize.SpaceTokenizer() method, we are able to extract the tokens from stream to words having space between them.
# import SpaceTokenizer() method from nltkfrom nltk.tokenize import SpaceTokenizer     # Create a reference variable for Class SpaceTokenizertk = SpaceTokenizer()     # Create a string inputgfg = "Geeksfor Geeks.. .$$&* \nis\t for geeks"     # Use tokenize methodgeek = tk.tokenize(gfg)     print(geek)
Output :
[‘Geeksfor’, ‘Geeks..’, ‘.$$&*’, ‘\nis\t’, ‘for’, ‘geeks’]
Example #2 :
# import SpaceTokenizer() method from nltkfrom nltk.tokenize import SpaceTokenizer     # Create a reference variable for Class SpaceTokenizertk = SpaceTokenizer()     # Create a string inputgfg = "The price\t of burger \nin BurgerKing is Rs.36.\n"     # Use tokenize methodgeek = tk.tokenize(gfg)     print(geek)
Output :
[‘The’, ‘price\t’, ‘of’, ‘burger’, ‘\nin’, ‘BurgerKing’, ‘is’, ‘Rs.36.\n’]
Python-nltk
Python
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 | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
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
Python – Multiple Column Sort in Tuples

06 Jul, 2021
Sometimes, while working with records, we can have a problem in which we need to perform sort operation on one of the columns, and on other column, if equal elements, opposite sort. This kind of problem can occur as application in many domains such as web development. Lets discuss certain ways in which this problem can be solved.
Input : test_list = [(6, 7), (6, 5), (6, 4), (7, 10)] Output : [(7, 10), (6, 4), (6, 5), (6, 7)]
Input : test_list = [(10, 7), (8, 5)] Output : [(10, 7), (8, 5)]  
Method #1 : Using sorted() + lambda The combination of above functions can offer one of the ways to solve this problem. In this, we perform sort using sorted() and order and column manipulation is handled by lambda function.
Python3
# Python3 code to demonstrate working of# Multiple Column Sort in Tuples# Using sorted() + lambda # initializing listtest_list = [(6, 7), (6, 5), (1, 4), (8, 10)] # printing original listprint("The original list is : " + str(test_list)) # Multiple Column Sort in Tuples# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[0], sub[1])) # printing resultprint("The sorted records : " + str(res))
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]
 
 Method #2 : Using itemgetter() + sorted() This is yet another way in which this task can be performed. In this, we perform the task required for lambda function using itemgetter().
Python3
# Python3 code to demonstrate working of# Multiple Column Sort in Tuples# Using itemgetter() + sorted()from operator import itemgetter # initializing listtest_list = [(6, 7), (6, 5), (1, 4), (8, 10)] # printing original listprint("The original list is : " + str(test_list)) # Multiple Column Sort in Tuples# Using itemgetter() + sorted()res = sorted(test_list, key = itemgetter(1))res = sorted(res, key = itemgetter(0), reverse = True) # printing resultprint("The sorted records : " + str(res))
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]
 
arorakashish0911
Python List-of-Tuples
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Math sin( ) Method

09 Feb, 2022
Below is the example of the Math sin() Method.
Example:<script type="text/javascript">      document.write("When zero is  passed as a parameter: "                      + Math.sin(0));</script>
<script type="text/javascript">      document.write("When zero is  passed as a parameter: "                      + Math.sin(0));</script>
Output:When zero is  passed as a parameter: 0
When zero is  passed as a parameter: 0
The Math.sin() method in Javascript is used to return the sine of a number. The Math.sin() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians.
The sin() is a static method of Math, therefore, it is always used as Math.sin(), rather than as a method of a Math object created.
Syntax:
Math.sin(value)
Parameters: This method accepts a single parameter as mentioned above and described below:value which is a number given in radians.
Return Value: The Math.sin() method returns the sine of the given numbers.
Below examples illustrates the Math sin() method in JavaScript:
Example 1:Input : Math.sin(0)
Output : 0
Input : Math.sin(0)
Output : 0
Example 1:Input : Math.sin(1)
Output : 0.8414709848078965
Input : Math.sin(1)
Output : 0.8414709848078965
Example 1:Input : Math.sin(Math.PI / 2)
Output : 1
Input : Math.sin(Math.PI / 2)
Output : 1
More codes for the above method are as follows:Program 1: When 1 is passed as a parameter.
<script type="text/javascript">         document.write("Result : " + Math.sin(1));</script>
Output:
Result : 0.8414709848078965
Program 2: When PI is passed as a parameter.
<script type="text/javascript">         document.write("Result : " + Math.sin(Math.PI / 2));</script>
Output:
Result : 1
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
ysachin2314
javascript-math
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python

07 Jul, 2022
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. 
It’s pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file. 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below. 
 
json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you. 
Syntax:
json.load(file object)
Example: Suppose the JSON file looks like this:
We want to read the content of this file. Below is the implementation.
Python3
# Python program to read# json file    import json  # Opening JSON filef = open('data.json')  # returns JSON object as # a dictionarydata = json.load(f)  # Iterating through the json# listfor i in data['emp_details']:    print(i)  # Closing filef.close()
Output:
json.loads(): If you have a JSON string, you can parse it by using the json.loads() method.json.loads() does not take the file path, but the file contents as a string, using fileobject.read() with json.loads() we can return the content of the file. 
Syntax:
json.loads(jsonstring) #for Json string

json.loads(fileobject.read()) #for fileobject
Example: This example shows reading from both string and JSON file. The file shown above is used.
Python3
# Python program to read# json file    import json    # JSON stringa = '{"name": "Bob", "languages": "English"}'  # deserializes into dict # and returns dict.y = json.loads(a)  print("JSON string = ", y)print()      # JSON filef = open ('data.json', "r")  # Reading from filedata = json.loads(f.read())  # Iterating through the json# listfor i in data['emp_details']:    print(i)  # Closing filef.close()
Output:
kapoorsagar226
nachiket_18
Python-json
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – String till Substring

25 Jun, 2022
Sometimes, more than finding a substring, we might need to get the string that is occurring before the substring has been found. Let’s discuss certain ways in which this task can be performed.
The partition function can be used to perform this task in which we just return the part of the partition occurring before the partition word.
Python3
# Python3 code to demonstrate# String till Substring# using partition() # initializing stringtest_string = "GeeksforGeeks is best for geeks" # initializing split wordspl_word = 'best' # printing original stringprint("The original string : " + str(test_string)) # printing split stringprint("The split string : " + str(spl_word)) # using partition()# String till Substringres = test_string.partition(spl_word)[0] # print resultprint("String before the substring occurrence : " + res)
The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is
 
The split function can also be applied to perform this particular task, in this function, we use the power of limiting the split and then print the former string. 
Python3
# Python3 code to demonstrate# String till Substring# using split() # initializing stringtest_string = "GeeksforGeeks is best for geeks" # initializing split wordspl_word = 'best' # printing original stringprint("The original string : " + str(test_string)) # printing split stringprint("The split string : " + str(spl_word)) # using split()# String till Substringres = test_string.split(spl_word)[0] # print resultprint("String before the substring occurrence : " + res)
The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is
 
Python3
# Python3 code to demonstrate# String till Substring# using find()# you can also use index(0 instead of find() # initializing stringtest_string = "GeeksforGeeks is best for geeks" # initializing substringspl_word = 'best' # printing original stringprint("The original string : " + str(test_string))  # String till Substringx=test_string.find(spl_word)res=test_string[0:x]  # print resultprint("String before the substring occurrence : " + res)
The original string : GeeksforGeeks is best for geeks
String before the substring occurrence : GeeksforGeeks is 
astro24
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
setsid command in Linux with Examples

08 Apr, 2019
setsid command in Linux system is used to run a program in a new session. The command will call the fork(2) if already a process group leader. Else, it will execute a program in the current process.
Syntax:
setsid [options] program [arguments]

Example: It will execute our shell script in a new session.
Options:
setsid -c: This option will set the controlling terminal to the current one.Example:sudo setsid -c ./add.shIn this example, we have our current terminal set to controlling terminal.
Example:
sudo setsid -c ./add.sh
In this example, we have our current terminal set to controlling terminal.
setsid -w: This option will wait for the execution of the program to end and return the exit value of this program as the return value of setsid.Example:setsid -w ./add.shIn this example, if there’s any process which is supposed to take some time to be fully executed then, in that case, it will return the exit value.
Example:
setsid -w ./add.sh
In this example, if there’s any process which is supposed to take some time to be fully executed then, in that case, it will return the exit value.
setsid -V : This option will show the version information and exit.Example:setsid -V
Example:
setsid -V
setsid -h : This option will show the help text and exit.setsid -h
setsid -h
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Class and Object | Question 1

28 Jun, 2021
Predict the output of following Java program?
class Test {  int i;} class Main {   public static void main(String args[]) {      Test t;      System.out.println(t.i); }  
(A) 0(B) garbage value(C) compiler error(D) runtime errorAnswer: (C)Explanation: t is just a reference, the object referred by t is not allocated any memory. Unlike C++, in Java all non-primitive objects must be explicitly allocated and these objects are allocated on heap. The following is corrected program.
class Test {  int i;} class Main {   public static void main(String args[]) {      Test t = new Test();      System.out.println(t.i); }  
Quiz of this Question
Class and Object
Java-Class and Object
Java Quiz
Java-Class and Object
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print “Hello World” with empty or blank main in C++

14 Jun, 2022
Write a program in C++ that prints “Hello World”, it has a main function and body of main function is empty.
Following are three different solutions.
We can create a global variable and assign it return value of printf() that prints “Hello World” 
CPP
// C++ program to print something with empty main()#include <bits/stdc++.h> int x = printf("Hello World"); int main(){    // Blank}
We can use Constructor in C++. In the below program, we create an object of class ‘A’ outer of the main Function so object declaration time it will be call to constructor so that it will be print “Hello World”. 
CPP
// C++ program to print something with empty main()#include <iostream>using namespace std; class A {public:    A() // Constructor    {        cout << "Hello World";    }}; A obj; // Create Object of class A int main(){    // Blank}
We can initialize a global variable with return type of function that prints “Hello World”.
C++
// C++ program to print something with empty main()#include <iostream>  int fun(){    std::cout << "Hello World";    return 1;}  int x = fun(); // global variable  int main() {}
Related article: How to print “GeeksforGeeks” with empty main() in C, C++ and Java? This article is contributed by Devanshu Agarwal. 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.
isha307
cpp-puzzle
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
Getting maximum elements in Julia - maximum() and maximum!() Methods - GeeksforGeeks

19 Aug, 2021
The maximum() is an inbuilt function in julia which is used to return maximum elements in different scenario.
Syntax: maximum(f, itr) or maximum(itr) or maximum(A::AbstractArray; dims)
Parameters: 
f: Specified function.
itr: Specified list of elements.
A::AbstractArray: Specified array of different dimensions.
dims: Specified dimensions.
Returns: It returns the maximum elements in different scenario.  
Example:  
Julia
# Julia program to illustrate# the use of maximum() method # Getting maximum elements in different scenarios # In the below scenario, length function# and a list of elements are used as# parameter. Here the length of string with# maximum alphabets will be returnedprintln(maximum(length, ["GFG", "Geeks", "GeeksforGeeks"])) # In the below scenario, a list of# elements are shown and maximum elements are# returned as outputprintln(maximum([5, 10, 15, 20])) # Getting the maximum value of an array# over the given dimensionsA = [5 10; 15 20];println(maximum(A, dims = 1))println(maximum(A, dims = 2))
Output: 
The maximum!() is an inbuilt function in julia which is used to calculate the maximum value of the specified array over the specified singleton dimensions. 
Syntax: maximum!(r, A)Parameters: 
r: Specified singleton dimensions.
A: Specified array.
Returns: It returns the maximum value of the specified array over the specified singleton dimensions.  
Example: 
Julia
# Julia program to illustrate# the use of maximum !() method # Getting the maximum value of the# specified array over the specified# singleton dimensions.A = [5 10; 15 20];println(maximum !([1; 1], A))println(maximum !([1 1], A))
Output: 
[10, 20]
[15 20]
 
sumitgumber28
anikakapoor
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Tuples in Julia
while loop in Julia
Manipulating matrices in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Storing Output on a File in Julia
Taking Input from Users in Julia
How to Run a Python Program

There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
Here is the list of all the available command line options −
Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your application, as in the following −
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C: >python script.py # Windows/DOS
Note − Be sure the file permission mode allows execution.
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.
Unix − IDLE is the very first Unix IDE for Python.
Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.
If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine.
How to add space around table border in HTML?

To set border spacing for an HTML table, use the CSS border-spacing property. It sets the distance between cells in a table,
You can try to run the following code to add space around table border in HTML
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, td, th {
            border: 1px solid black;
            border-spacing: 20px;
            width: 300px;
         }
      </style>
   </head>
   <body>
      <h1>Our Technologies</h1>
      <table>
         <tr>
            <th>IDE</th>
            <th>Database</th>
         </tr>
         <tr>
            <td style="text-align:center">NetBeans</td>
            <td style="text-align:center">MySQL</td>
        </tr>
     </table>
  </body>
</html>
p5.js | Keyboard | keyIsDown()

16 Apr, 2019
The keyIsDown() function in p5.js checks the key’s current status that key is down, i.e. pressed. It can be used if you have a movable object, and you want several keys to be able to affect its behavior simultaneously, such as moving a sprite diagonally.
Syntax:
keyIsDown()

Below program illustrates the keyIsDown() function in p5.js:Example-1:
let x = 100;let y = 100;  function setup() {        // create canvas of size 600*600    createCanvas(600, 600);}  function draw() {        // fill color    fill(x, y, x - y);      if (keyIsDown(LEFT_ARROW)) {        x -= 5;    }      if (keyIsDown(RIGHT_ARROW)) {        x += 5;    }      if (keyIsDown(UP_ARROW)) {        y -= 5;    }      if (keyIsDown(DOWN_ARROW)) {        y += 5;    }      clear();    ellipse(x, y, 50, 50);}
Output:
Example-2:
let diameter = 30;  function setup() {        // Create canvas of size 600*600    createCanvas(600, 600);}  function draw() {        // 107 and 187 are keyCodes for "+"    if (keyIsDown(107) || keyIsDown(187)) {        diameter += 1;    }      // 109 and 189 are keyCodes for "-"    if (keyIsDown(109) || keyIsDown(189)) {        diameter -= 1;    }      clear();    fill(255, 0, 0);    ellipse(width / 2, height / 2, diameter, diameter);}
Output:Reference: https://p5js.org/reference/#/p5/keyIsDown
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python – math.prod() method

23 Jan, 2020
Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.prod() method in Python is used to calculate the product of all the elements present in the given iterable. Most of the built-in containers in Python like list, tuple are iterables. The iterable must contain numeric value else non-numeric types may be rejected.This method is new in Python version 3.8.
Syntax: math.prod(iterable, *, start = 1)
Parameters:iterable: an iterable containing numeric valuesstart: an integer representing the start value. start is a named (keyword-only) parameter and its default value is 1.
Returns: the calculated product of all elements present in the given iterable.
Code #1: Use of math.prod() method
# Python Program to explain math.prod() method  # Importing math moduleimport math  # listarr = [1, 2, 3, 4, 5]  # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr)print(product)    # tupletup = (0.5, 0.6, 0.7)  # Calculate the product # of all elements present# in the given tupleproduct = math.prod(tup)print(product)    # rangeseq = range(1, 11)  # Calculate the product # of all elements present# in the given rangeproduct = math.prod(seq)print(product)  # As the start value is not specified # it will default to 1
120
0.21
3628800

Code #2: if start parameter is explicitly specified
# Python Program to explain math.prod() method  # Importing math moduleimport math    # By default start value is 1# but can be explicitly provided# as a named (keyword-only) parameter  # listarr = [1, 2, 3, 4, 5]  # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr, start = 2)print(product)
240

Code #3: When the given iterable is empty
# Python Program to explain math.prod() method  # Importing math moduleimport math  # If the given input iterable# is empty, then this method# returns the start value   # listarr = []  # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr)print(product)    # Tupletup = ()  # Calculate the product of# of all elements present# in the given tupleproduct = math.prod(tup, start = 5)print(product)
1
5

Reference: Python math library
Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Powershell - ForEach-Object Cmdlet

ForEach-Object cmdlet can be used to perform operations on each object of a collection of objects.
In these examples, we're see the ForEach-Object cmdlet in action.
In this example, we'll divide integer in an array. We'll refer to each object using $_.
1000,2000,3000 | ForEach-Object -Process {$_/1000}
You can see following output in PowerShell console.
1
2
3        

Get the names of the items in current directory.
In this example, we'll split powershell module names.
"Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")}
You can see following output in PowerShell console.
p5.js | Mouse | pmouseX

16 Apr, 2019
The pmouseX variable in p5.js is used to store the horizontal position of the mouse cursor in the frame previous to the currently active frame, relative to the origin of the canvas.
Syntax:
mouseX
Below programs illustrate the pmouseX variable in p5.js:
Example 1: This example uses pmouseX variable to draw mouse pointer as circle.
function setup() {      // Create canvas    createCanvas(1000, 400);}   function draw() {          // Set the background color    background(244, 248, 252);          // Fill color relative pmouseX,    // pmouseY and mouseY    fill(pmouseX%255, pmouseY%255, mouseY%255);          // Draw circle     circle(pmouseX, mouseX, pmouseX%100);}
Output:
Example 2: This example uses pmouseX variable to display the position of mouse pointer.
function setup() {      // Create canvas    createCanvas(1000, 400);          // Set font size    textSize(20);}   function draw() {          // Set background color    background(200);          // Display result    text("Position of pmouseX is "        + pmouseX, 30, 40);}
Output:
Reference: https://p5js.org/reference/#/p5/pmouseX
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Condition of schedules to View-equivalent

28 Jun, 2021
Two schedules S1 and S2 are said to be view-equivalent if below conditions are satisfied : 
1) Initial Read If a transaction T1 reading data item A from database in S1 then in S2 also T1 should read A from database. 
 
  T1     T2     T3
-------------------
        R(A)
 W(A)          
               R(A)
        R(B)
Transaction T2 is reading A from database. 
2)Updated Read If Ti is reading A which is updated by Tj in S1 then in S2 also Ti should read A which is updated by Tj. 
 
  T1     T2     T3         T1    T2    T3                   
-------------------       ----------------
 W(A)                    W(A)       
         W(A)                               R(A)
                 R(A)               W(A)
Above two schedule are not view-equivalent as in S1 :T3 is reading A updated by T2, in S2 T3 is reading A updated by T1. 
3)Final Write operation If a transaction T1 updated A at last in S1, then in S2 also T1 should perform final write operations. 
 
 T1       T2        T1     T2            
------------    ---------------
 R(A)              R(A)
         W(A)     W(A)
 W(A)                    W(A)
Above two schedules are not view-equivalent as Final write operation in S1 is done by T1 while in S2 done by T2. 
View Serializability: A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). 
Below are the previous Year Gate Question asked on this topic https://www.geeksforgeeks.org/dbms-gq/transactions-and-concurrency-control-gq/ 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
AmolBarge
madhav_mohan
nunemunthalashiva
DBMS-Transactions and Concurrency Control
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Data Preprocessing in Data Mining
Difference between DELETE, DROP and TRUNCATE
Node.js fsPromises.open() Method

08 Oct, 2021
The fsPromises.open() method is used to asynchronously open a file that returns a Promise that, when resolved, yields a FileHandle object.
Syntax:
fsPromises.open( filename, flags, mode)
Parameter: This method accept three parameters as mentioned above and described below:
filename: It is a String, Buffer or an URL that holds the name of the file to read or the entire path if stored at other location.
flags: It is a String or a Number, which gives operation in which file has to be opened. Default ‘r’.
mode:  It is a String or an Integer. Sets the mode of file i.e. r:read, w:write, r+:readwrite. It sets to default as readwrite.
Return Value: It returns the Promise.
Below example illustrates the fsPromises.open() method in Node.js:
Example:
// Node.js program to demonstrate the     // fsPromises.open() Method      // Include the fs module var fs = require('fs'); var fsPromises = fs.promises;    // Open file Demo.txt in read mode fsPromises.open('Demo.txt', 'r').then((result)=>{    console.log(result);}).catch((error)=>{    console.log(error);});
Output:
FileHandle { [Symbol(handle)]: FileHandle { fd: 3 } }
Explanation: The file is opened and the flag is set to read mode. After opening of file function is called to read the contents of file and store in memory.
Note: mode sets the file mode (permission and sticky bits), but only if the file was created.
Some characters (< > : ” / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces.
Akanksha_Rai
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React