code-rag-bench/online-tutorials huggingface dataset:
Python Program to print all Possible Combinations from the three Digits

29 Aug, 2020
Given 3 digits a, b, and c. The task is to find all the possible combinations from these digits.
Examples:
Input: [1, 2, 3]
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Input: [0, 9, 5]
Output:
0 9 5
0 5 9
9 0 5
9 5 0
5 0 9
5 9 0

Method 1: Brute force or Naive approach
The naive approach is to run 3 loops from 0 to 3 and print all the numbers from the list if the indexes are not equal to each other.
Example:
Python3
# Python program to print all# the possible combinations  def comb(L):          for i in range(3):        for j in range(3):            for k in range(3):                                  # check if the indexes are not                # same                if (i!=j and j!=k and i!=k):                    print(L[i], L[j], L[k])                      # Driver Codecomb([1, 2, 3])
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Method 2: Using itertools.permutations()
This method takes a list as an input and returns an object list of tuples that contain all permutation in a list form.
Example:
Python3
# Python program to print all# the possible combinations  from itertools import permutations  # Get all combination of [1, 2, 3]# of length 3comb = permutations([1, 2, 3], 3)  for i in comb:    print(i)
Output:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

Python list-programs
Python-itertools
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
Introduction To PYTHON
Python OOPs Concepts
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
GATE | GATE-CS-2016 (Set 2) | Question 61

28 Jun, 2021
Consider the following database schedule with two transactions, T1 and T2.
S = r2(X); r1(X); r2(Y); w1(X); r1(Y); w2(X); a1; a2;
where ri(Z) denotes a read operation by transaction Ti on a variable Z, wi(Z) denotes a write operation by Ti on a variable Z and ai denotes an abort by transaction Ti .Which one of the following statements about the above schedule is TRUE?(A) S is non-recoverable(B) S is recoverable, but has a cascading abort(C) S does not have a cascading abort
(D) S is strictAnswer: (C)Explanation: As we can see in figure,
T2 overwrites a value that T1 writes
T1 aborts: its “remembered” values are restored.
Cascading Abort could have arised if – > Abort of T1 required abort of T2 but as T2 is already aborted , its not a cascade abort. Therefore, Option C
Option A – is not true because the given schedule is recoverable
Option B – is not true as it is recoverable and avoid cascading aborts;
Option D – is not true because T2 is also doing abort operation after T1 does, so NOT strict.Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
statsmodels.jarque_bera() in Python

26 Mar, 2020
With the help of statsmodels.jarque_bera() method, we can get the jarque bera test for normality and it’s a test based on skewness, and the kurtosis, and has an asymptotic distribution.
Syntax : statsmodels.jarque_bera(residual, axis)Return : Return the jarque bera test statistics, pvalue, skewness, and the kurtosis.
Example #1 :In this example we can see that by using statsmodels.jarque_bera() method, we are able to get the jarque bera test statistics, pvalue, skewness and kurtosis by using this method.
# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import jarque_bera  g = np.array([1, 2, 3])# Using statsmodels.jarque_bera() methodgfg = jarque_bera(g)  print(gfg)
Output :
(0.28125, 0.8688150562628432, 0.0, 1.5)
Example #2 :
# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import jarque_bera  g = np.array([1, 2, 3, -1, -2, -3])# Using statsmodels.jarque_bera() methodgfg = jarque_bera(g)  print(gfg)
Output :
(0.5625000000000003, 0.7548396019890072, 0.0, 1.4999999999999996)
Python-statsmodels
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
Introduction To PYTHON
Python OOPs Concepts
Convert integer to string in Python
Xamarin - Android Activity Lifecycle

When a user navigates through an Android App, a series of events occurs. For example, when a user launches an app, e.g., the Facebook App, it starts and becomes visible on the foreground to the user, onCreate() → onStart() → onResume().
If another activity starts, e.g., a phone call comes in, then the Facebook app will go to the background and the call comes to the foreground. We now have two processes running.
onPause()  --- > onStop()

When the phone call ends, the Facebook app returns to the foreground. Three methods are called.
onRestart() --- > onStart() --- > onResume()

There are 7 lifecycle processes in an Android activity. They include −
onCreate − It is called when the activity is first created.
onCreate − It is called when the activity is first created.
onStart − It is called when the activity starts and becomes visible to the user.
onStart − It is called when the activity starts and becomes visible to the user.
onResume − It is called when the activity starts interacting with the user. User input takes place at this stage.
onResume − It is called when the activity starts interacting with the user. User input takes place at this stage.
onPause − It is called when the activity runs in the background but has not yet been killed.
onPause − It is called when the activity runs in the background but has not yet been killed.
onStop − It is called when the activity is no longer visible to the user.
onStop − It is called when the activity is no longer visible to the user.
onRestart − It is called after the activity has stopped, before starting again. It is normally called when a user goes back to a previous activity that had been stopped.
onRestart − It is called after the activity has stopped, before starting again. It is normally called when a user goes back to a previous activity that had been stopped.
onDestroy − This is the final call before the activity is removed from the memory.
onDestroy − This is the final call before the activity is removed from the memory.
The following illustration shows the Android Activity Lifecycle −
How to Apply a function to multiple columns in Pandas?

24 Oct, 2021
Let us see how to apply a function to multiple columns in a Pandas DataFrame. To execute this task will be using the apply() function. 
This function applies a function along an axis of the DataFrame.  
Syntax : DataFrame.apply(parameters)Parameters :  
func : Function to apply to each column or row.
axis : Axis along which the function is applied
raw : Determines if row or column is passed as a Series or ndarray object.
result_type : ‘expand’, ‘reduce’, ‘broadcast’, None; default None
args : Positional arguments to pass to func in addition to the array/series.
**kwds : Additional keyword arguments to pass as keywords arguments to func.
Returns : Series or DataFrame  
Example 1 : Prepending “Geek” before every element in two columns.  
Python3
# import the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame({'String 1' :['Tom', 'Nick', 'Krish', 'Jack'],                   'String 2' :['Jane', 'John', 'Doe', 'Mohan']}) # displaying the DataFramedisplay(df) # function for prepending 'Geek'def prepend_geek(name):    return 'Geek ' + name # executing the functiondf[["String 1", "String 2"]] = df[["String 1", "String 2"]].apply(prepend_geek) # displaying the DataFramedisplay(df)
Output :  
Example 2 : Multiplying the value of each element by 2  
Python3
# import the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame({'Integers' :[1, 2, 3, 4, 5],                   'Float' :[1.1, 2.2, 3.3, 4.4 ,5.5]}) # displaying the DataFramedisplay(df) # function for prepending 'Geek'def multiply_by_2(number):    return 2 * number # executing the functiondf[["Integers", "Float"]] = df[["Integers", "Float"]].apply(multiply_by_2) # displaying the DataFramedisplay(df)
Output :  
 
saurabh1990aror
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
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
BigInteger bitLength() Method in Java

28 Jan, 2022
The java.math.BigInteger.bitLength() method returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. The bitLength method Computes (ceil(log2(this < 0 ? -this : this+1))).Syntax:  
public int bitLength()
Parameters: The method does not return any parameters.Return Value: The method is used to return the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.Examples:  
Input: value = 2300 
Output: 12
Explanation:
Binary signed 2's complement of 2300 = 0000100011111100
first four bits are singed bit so exclude them then remaining 
no of bits = 12. So bitLength in 0000100011111100 = 12.

Input: value = 5482549
Output: 23
Below program illustrates the use of bitLength() method of BigInteger.  
Java
// Program to demonstrate bitLength() method of BigInteger import java.math.*; public class GFG {     public static void main(String[] args)    {         // Create  BigInteger objects        BigInteger biginteger = new BigInteger("2300");         // Call bitLength() method on bigInteger        int count = biginteger.bitLength();         String result = "bitLength of  " + biginteger +        " is " + count;         // Print result        System.out.println(result);    }}
bitLength of  2300 is 12
 
Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#bitLength() 
sumitgumber28
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Join Pandas DataFrames matching by substring - GeeksforGeeks

07 Apr, 2021
Prerequisites: Pandas
In this article, we will learn how to join two Data Frames matching by substring with python. 
join(): joins all the elements in an iteration into a single string
lambda(): an anonymous method which is declared without a name and can accept any number of parameters
find(): gets the initial appearance of any requisite value
merge(): merges two dataframes
Follow the below steps to join two data frames matched by substring.
Create two DataFrames.
Join two dataframes using cartesian product
Join a duplicate column including equal values in all the DataFrames
Join the new column
At last, remove the added column in each DataFrame.
Then we need to add a new column to the Data frame. To do this we will use the “lambda” along with “find” functions where the output is greater than zero.
Now we print the joined data frames matched by substrings .
Below is the implementation.
Python3
import pandas as pd    dataFrame1 = pd.DataFrame([['PQR', 'B1'], ['QRS', 'B2'], ['RDE', 'B3']],                           columns=['work_name', 'tag_name'])  dataFrame2 = pd.DataFrame([['RR', 'T1'], ['QR', 'T2'], ['HG', 'T3'],                            ['PQ', 'T4']],                          columns=['sub_work_name', 'extra_tag_value'])  dataFrame1['join'] = 1dataFrame2['join'] = 1  dataFrameFull = dataFrame1.merge(  dataFrame2, on='join').drop('join', axis=1)  dataFrame2.drop('join', axis=1, inplace=True)  dataFrameFull['match'] = dataFrameFull.apply(    lambda x: x.work_name.find(x.sub_work_name), axis=1).ge(0)  print(dataFrameFull[dataFrameFull['match']])
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Dictionary Values Division - GeeksforGeeks

29 Dec, 2019
Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss division of like key values and ways to solve it in this article.
Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line.
# Python3 code to demonstrate working of# Dictionary Values Division# Using dictionary comprehension + keys()  # Initialize dictionariestest_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}  # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # Using dictionary comprehension + keys()# Dictionary Values Divisionres = {key: test_dict1[key] // test_dict2.get(key, 0)                        for key in test_dict1.keys()}  # printing result print("The divided dictionary is : " + str(res))
The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20}
The original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10}
The divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2}

 
Method #2 : Using Counter() + “//” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the divide operator can perform the task of division.
# Python3 code to demonstrate working of# Dictionary Values Division# Using Counter() + "//" operatorfrom collections import Counter  # Initialize dictionariestest_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}  # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # Using Counter() + "//" operator# Dictionary Values Divisiontemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] // temp2[key] for key in temp1})  # printing result print("The division dictionary is : " + str(dict(res)))
The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20}
The original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10}
The divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2}

Python dictionary-programs
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Update a MySQL column with JSON format?

To display records like JSON format, use MySQL concat(). Let us first create a table −
mysql> create table DemoTable1373
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentDetails text
   -> );
Query OK, 0 rows affected (0.86 sec)
Insert some records in the table using insert command. Here, we haven’t inserted anything −
mysql> insert into DemoTable1373 values();
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable1373 values();
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1373 values();
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1373;
This will produce the following output −
+-----------+----------------+
| StudentId | StudentDetails |
+-----------+----------------+
|         1 | NULL           |
|         2 | NULL           |
|         3 | NULL           |
+-----------+----------------+
3 rows in set (0.00 sec)
Following is the query to update a MySQL field with JSON format −
mysql> update DemoTable1373 set StudentDetails=concat("{" "StudentName:", " John ,"," StudentAge:", 21,","," StudentCountryName: "," US","} ");
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3  Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1373;
This will produce the following output −
+-----------+---------------------------------------------------------------+
| StudentId | StudentDetails                                                |
+-----------+---------------------------------------------------------------+
|         1 | {StudentName: John , StudentAge:21, StudentCountryName:  US}  |
|         2 | {StudentName: John , StudentAge:21, StudentCountryName:  US}  |
|         3 | {StudentName: John , StudentAge:21, StudentCountryName:  US}  |
+-----------+---------------------------------------------------------------+
3 rows in set (0.00 sec)
How to create a link to send email in HTML?

To create a link to send email, use <a> tag, with href attribute. The mailto link is added inside the <a> tag. Just keep in mind to add the email address where you want to receive the email in the mailto link.
You can try to run the following code to create a link to send email in HTML.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML email link</title>
   </head>

   <body>
      <h2>Contact</h2>
      <p>For any queries: <a href="mailto:demo@example.com">Contact us</a></p>
   </body>
</html>
Find the list elements starting with specific letter in Python

In this article we will find all those elements from a list which start with specific letter.
We use the lower function so that the test later can match with the first letter of the the elements in the list irrespective of the case. Then we use the index at 0 so that the first letter of the elements in a list are compared with the test letter.
 Live Demo
listA = ['Mon', 'Tue', 'Wed', 'Thu']
# Test with letter
test = 'T'
# printing original list
print("Given list\n " ,listA)
# using lower and idx
res = [idx for idx in listA if idx[0].lower() == test.lower()]
# print result
print("List elements starting with matching letter:\n " ,res)
Running the above code gives us the following result −
Given list
['Mon', 'Tue', 'Wed', 'Thu']
List elements starting with matching letter:
['Tue', 'Thu']
It is a very straight forward approach in which we use a function startswith. This function Returns true if the element starts with the test letter else it returns false.
 Live Demo
listA = ['Mon', 'Tue', 'Wed', 'Thu']
# Test with letter
test = 'T'
# printing original list
print("Given list\n " ,listA)
# using startswith
res = [idx for idx in listA if idx.lower().startswith(test.lower())]
# print result
print("List elements starting with matching letter:\n " ,res)
Running the above code gives us the following result −
Given list
['Mon', 'Tue', 'Wed', 'Thu']
List elements starting with matching letter:
['Tue', 'Thu']
Postman with Newman & Jenkins

We can integrate Postman with Newman and Jenkins. Newman is used to verify and execute a Collection. To integrate Newman and Jenkins, we have to follow the below steps −
Step1 − We have to complete the installation and configuration of Jenkins. The steps to perform this task is discussed in details in the below link −
https://www.tutorialspoint.com/jenkins/jenkins_installation.htm
Step2 − We have to install npm and Nodejs. For installation of Nodejs can be done from the below link −
https://nodejs.org/en/download/current/
Step3 − The npm is allocated with Nodejs so once we download the Nodejs, the npm gets downloaded automatically.
Step4 − We have to install Newman with the help of the command: npm install -g newman.
Step5 − Open Terminal, navigate to the directory where the Collection is stored. Then run the command: newman run <"file name">. (The file name should always be in inverted quotes).
Step6 − Once Jenkins is up and running, it provides an interface: https://localhost:8080. Then click on New Item in the top left corner of the Postman application.
Step7 − Choose the option Freestyle Project, enter a project name then click on the OK button.
Step8 − Click on the Source Code Management tab and move to the Build section. Select the option Execute shell from the Add build step up dropdown.
Step9 − Add the below command in the Execute Shell edit box under the Build tab.
newman run <file name> --supress-exit-code 1
The exit code means that Newman execution shall get stopped if any errors are encountered. Finally click on Save.
Step10 − Click on Build Now from the left of the Jenkins application.
Step11 − After the Build has completed, click on the Console Output link in the sidebar from the Build details screen to get the details of the Newman output.
turtle.home() function in Python - GeeksforGeeks

21 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to move the turtle to the origin i.e. coordinates (0,0). Whatever, the position of the turtle is, it sets to (0,0) with default direction (facing to east).
Syntax :
turtle.home()

Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle    # check turtle positionprint(turtle.position())  # motionturtle.forward(100)  # check turtle positionprint(turtle.position())  # set turtle to hometurtle.home()  # check turtle positionprint(turtle.position())  # motionturtle.right(90)turtle.forward(100)  # check turtle positionprint(turtle.position())  # set turtle to hometurtle.home()  # check turtle positionprint(turtle.position())
Output :
(0.0, 0.0)
(100.0, 0.0)
(0.0, 0.0)
(0.0, -100.0)
(0.0, 0.0)

Example 2 :
Python3
# import packageimport turtle    # set turtle speed to fastest# for bettrt understandingsturtle.speed(10)  # method to draw a partdef fxn():      # motion  turtle.circle(50,180)  turtle.right(90)  turtle.circle(50,180)  # loop to draw patternfor i in range(12):  fxn()      # set turtle at home  turtle.up()  turtle.home()  turtle.down()      # set position  turtle.left(30*(i+1))
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
What is ResultSet Concurrency in JDBC?

The concurrency of the ResultSet object determines whether its contents can be updated or not.
The Connection interface provides 3 variants of the createStatement() method where one of the method's signature is as follows:
Statement createStatement(int resultSetType, int resultSetConcurrency)
This method accepts two integer type variables where one represents the type of the ResultSet and the other represents the Concurrency of the ResultSet.
The ResultSet interface provides two values to specify the concurrency of the ResultSet.
CONCUR_READ_ONLY: If you set this as a value of the concurrency while creating the ResultSet object you cannot update the contents of the ResultSet you can only read/retrieve them.
CONCUR_READ_ONLY: If you set this as a value of the concurrency while creating the ResultSet object you cannot update the contents of the ResultSet you can only read/retrieve them.
CONCUR_UPDATABLE: If you set this as a value of the concurrency while creating the ResultSet object you can update the contents of the ResultSet.
CONCUR_UPDATABLE: If you set this as a value of the concurrency while creating the ResultSet object you can update the contents of the ResultSet.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Or,
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.
ResultSet.CONCUR_UPDATABLE);
time.Parse() Function in Golang With Examples - GeeksforGeeks

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Parse() function in Go language is used to parse a formatted string and then finds the time value that it forms. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.
Syntax:
func Parse(layout, value string) (Time, error)

Here, layout specifies the format by displaying in what way the reference time, that is defined as Mon Jan 2 15:04:05 -0700 MST 2006 would be explained if it were the value. However, the previously defined layouts like UnixDate, ANSIC, RFC3339 etc, explain standard as well as suitable representations of the reference time. And the value parameter holds string. Where, the elements that are removed from the value are presumed to be zero and when zero is not possible then its assumed to be one.
Return Value: It returns the time value that it represents. And if a time zone indicator is not present then it returns a time in UTC.
Example 1:
// Golang program to illustrate the usage of// time.Parse() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring layout constant    const layout = "Jan 2, 2006 at 3:04pm (MST)"      // Calling Parse() method with its parameters    tm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")      // Returns output    fmt.Println(tm)}
Output:
2014-02-04 18:05:00 +0000 PST

Here, the output returned is in PST as defined above and the layout constant and value used here are long-form of it.
Example 2:
// Golang program to illustrate the usage of// time.Parse() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring layout constant    const layout = "2006-Jan-02"      // Calling Parse() method with its parameters    tm, _ := time.Parse(layout, "2014-Feb-04")      // Returns output    fmt.Println(tm)}
Output:
2014-02-04 00:00:00 +0000 UTC

Here, the output returned is in UTC as there is no time zone indicator and the layout constant and value used here are short form of it.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang?
Python EasyGUI – Integer Box - GeeksforGeeks

05 Sep, 2020
Integer Box : It is used to get the integer input from the user, input should be integer input not sting which happens in enter box. It displays the title, message to be displayed, place to enter a integer input and a pair of “Ok”, “Cancel” button which is used confirm the input. We can set some default integer value to the place where user enter text and we can also set lower and upper bound value which user can enter, below is how the enter box looks like
In order to do this we will use integerbox method
Syntax : integerbox(message, title, default_integer, lower_bound, upper_bound)
Argument : It takes 5 arguments, first string i.e message/information to be displayed, second string i.e title of the window, third is integer which is default integer, forth and fifth are integer representing lower and upper bound respectively
Return : It returns the entered integer and None if cancel is pressed
Example :In this we will create a integer box with default integer and with lower and upper bound value, and will show the specific message on the screen according to the entered integer, below is the implementation
# importing easygui modulefrom easygui import *  # message to be displayedtext = "Enter Something (integer)"  # window titletitle = "Window Title GfG"  # default integerd_int = 10  # lower boundlower = 0  # upper boundupper = 99999  # creating a integer boxoutput = integerbox(text, title, d_int, lower, upper)  # title for the message boxtitle = "Message Box"  # creating a messagemessage = "Enterted Number : " + str(output)  # creating a message boxmsg = msgbox(message, title)
Output :
Another Example :In this we will create a integer box and will show the specific message on the screen according to the entered integer, below is the implementation
# importing easygui modulefrom easygui import *  # message to be displayedtext = "Enter a number !!"  # window titletitle = "Window Title GfG"  # creating a integer boxoutput = integerbox(text, title)  # title for the message boxtitle = "Message Box"  # creating a messagemessage = "Enterted Number : " + str(output)  # creating a message boxmsg = msgbox(message, title)
Output :
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
AngularJS | json Filter - GeeksforGeeks

30 Apr, 2019
The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.JavaScript object that we are using can be of any kind of JavaScript Object.
Syntax:
    {{ object | json : spacing }}

Where json is used to specifies that object should be displayed in JSON format and spacing is an optional parameter with default value 2 that specifies the number of spaces per indentation.
Example 1:This example will display the marks of student in JSON
<!DOCTYPE html><html>    <head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>    </head><body>  <div ng-app="result" ng-controller="resultCtrl">  <h1>Result:</h1>  <pre>{{marks | json}}</pre>  </div>  <script>var app = angular.module('result', []);app.controller('resultCtrl', function($scope) {$scope.marks = {         "Math" : 98,        "Computer" : 93,        "Physics" : 95,        "Chemistry" : 95,        "English" : 74    };});</script>  </body></html>
Output :
Example 2:This example will display fruits name in JSON with 10 spaces per indentation
<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script></head><body>  <div ng-app="fruit" ng-controller="fruitCtrl">  <h1>Fruits:</h1>  <pre>{{fruit | json : 10}}</pre>  </div>  <script>var app = angular.module('fruit', []);app.controller('fruitCtrl', function($scope) {    $scope.fruit = ["Apple", "Banana", "Mango"];});</script>  </body></html>
Output :
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
Angular File Upload
Auth Guards in Angular 9/10/11
Angular | keyup event
What is AOT and JIT Compiler in Angular ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
8085 program to find the factorial of a number - GeeksforGeeks

07 Sep, 2018
Problem – Write an assembly language program for calculating the factorial of a number using 8085 microprocessor.
Example –
Input : 04H
Output : 18H 
as 04*03*02*01 = 24 in decimal => 18H

In 8085 microprocessor, no direct instruction exists to multiply two numbers, so multiplication is done by repeated addition as 4×3 is equivalent to 4+4+4 (i.e., 3 times).Load 04H in D register -> Add 04H 3 times -> D register now contains 0CH -> Add 0CH 2 times -> D register now contains 18H -> Add 18H 1 time -> D register now contains 18H -> Output is 18H
Algorithm –
Load the data into register BTo start multiplication set D to 01HJump to step 7Decrements B to multiply previous numberJump to step 3 till value of B>0Take memory pointer to next location and store resultLoad E with contents of B and clear accumulatorRepeatedly add contents of D to accumulator E timesStore accumulator content to DGo to step 4
Load the data into register B
To start multiplication set D to 01H
Jump to step 7
Decrements B to multiply previous number
Jump to step 3 till value of B>0
Take memory pointer to next location and store result
Load E with contents of B and clear accumulator
Repeatedly add contents of D to accumulator E times
Store accumulator content to D
Go to step 4
Explanation –
First set register B with data.Set register D with data by calling MULTIPLY subroutine one time.Decrement B and add D to itself B times by calling MULTIPLY subroutine as 4*3 is equivalent to 4+4+4 (i.e., 3 times).Repeat the above step till B reaches 0 and then exit the program.The result is obtained in D register which is stored in memory
First set register B with data.
Set register D with data by calling MULTIPLY subroutine one time.
Decrement B and add D to itself B times by calling MULTIPLY subroutine as 4*3 is equivalent to 4+4+4 (i.e., 3 times).
Repeat the above step till B reaches 0 and then exit the program.
The result is obtained in D register which is stored in memory
aastha98
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Architecture of 8085 microprocessor
Computer Organization | RISC and CISC
Memory Hierarchy Design and its Characteristics
Pin diagram of 8086 microprocessor
Architecture of 8086
Computer Organization | Booth's Algorithm
Interrupts
Flag register in 8085 microprocessor
How to grep multiline search patterns in Linux?

In order to be able to grep multiple lines of pattern present in a file, we will make use of the number of grep command that Linux provides us with. But first, we must understand what a grep command is and how to use it on Linux.
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.
Normally, the pattern that we are trying to search in the file is referred to as the regular expression.
grep [options] pattern [files]
While there are plenty of different options available to us, some of the most used are −
-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern
Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1.
grep -rni "word" *
In the above command replace the “word” placeholder with
For that we make use of the command shown below −
grep -rni "func main()" *
The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.
main.go:120:func main() {}

In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −
grep -s "func main()" *
Now suppose we have a text file named sample.txt whose content looks something like this.
$ immukul@192 linux-questions-code % cat sample.txt
blabla
blabla
foofoo
here
is the
text2strike
Just a pattern
bar
blabla
blabla
Now the command to search for multiline pattern is shown below
grep -Pzo "(?s)^(\s*)\N*/foo/,/bar/p.*?{.*?^\1}" .txt
foofoo
here
is the
text2strike
just a pattern
bar
How can I rotate xtick labels through 90 degrees in Matplotlib?

To rotate xtick labels through 90 degrees, we can take the following steps −
Make a list (x) of numbers.
Make a list (x) of numbers.
Add a subplot to the current figure.
Add a subplot to the current figure.
Set ticks on X-axis.
Set ticks on X-axis.
Set xtick labels and use rotate=90 as the arguments in the method.
Set xtick labels and use rotate=90 as the arguments in the method.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [1, 2, 3, 4]
ax1 = plt.subplot()
ax1.set_xticks(x)
ax1.set_xticklabels(["one", "two", "three", "four"], rotation=90)
plt.show()
Perl CGI Environment Variables

All the Perl CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program in Perl.
Here is a small Perl CGI program to list down all the CGI variables supported by your Web server. Click this link to see the result Get Environment
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<font size=+1>Environment</font>\n";
foreach (sort keys %ENV) {
   print "<b>$_</b>: $ENV{$_}<br>\n";
}
1;
JavaScript filter array by multiple strings?

To filter array by multiple strings, use for loop along with indexOf(). Following is the code −
var details = [
   'My first Name is John and last Name is Smith',
   'My first Name is John and last Name is Doe',
   'Student first Name is John and last Name is Taylor'
];
var isPresent;
var records = [];
var matchWords = ['John', 'Doe'];
for (var index = 0; index < details.length; index++){
   isPresent = true;
   for (var outer = 0; outer< matchWords.length; outer++) {
      if (details[index].indexOf(matchWords[outer]) === -1) {
         isPresent = false;
         break;
      }
   }
   if (isPresent){
      records.push(details[index]);
   }
}
console.log(records)
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo151.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo151.js
[ 'My first Name is John and last Name is Doe'
Find length of loop in linked list in C++

In this problem, we are given a linked list that might contain loops. Our task is to find the length of the loop in the linked list. 
Problem Description: we need to count the number of nodes in the loop if it contains a loop otherwise return -1.
Let’s take an example to understand the problem, 
Input: linked-list :
Output: 8
To solve the problem, we first need to check whether the linked list contains a loop. An approach to check this is using Floyd’s Cycle Finding Algorithm. 
In Floyd’s Cycle Finding Algorithm, we will traverse the linked list using two pointers. One slowPointer that increases by 1 and another one is fastPointer that increases by 2. If both numbers meet at some point then there exists a loop otherwise not.
If there exists a loop, we need to count the number of nodes that are present in the loop. For this we will start from the point where slowPointer and fastPointer meet and then count the number of nodes traversed to get to the position back.
Live Demo
#include<bits/stdc++.h>
using namespace std;

struct Node {
   int data;
   struct Node* next;
};

int countLoopNodespoint(struct Node *n) {
   int res = 1;
   struct Node *temp = n;
   while (temp->next != n) {
     
      res++;
      temp = temp->next;
   }
   return res;
}

int countLoopNode(struct Node *list) {
   
   struct Node *slowPtr = list, *fastPtr = list;
   while (slowPtr && fastPtr && fastPtr->next) {
      slowPtr = slowPtr->next;
      fastPtr = fastPtr->next->next;

      if (slowPtr == fastPtr)
         return countLoopNodespoint(slowPtr);
   }
   return 0;
}

struct Node *newNode(int key) {
   struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
   temp->data = key;
   temp->next = NULL;
   return temp;
}

int main() {
   struct Node *head = newNode(1);
   head->next = newNode(2);
   head->next->next = newNode(3);
   head->next->next->next = newNode(4);
   head->next->next->next->next = newNode(5);
   head->next->next->next->next->next = newNode(6);
   head->next->next->next->next->next->next = newNode(7);
   head->next->next->next->next->next->next->next = head->next;

   cout<<"The number of nodes in the loop are "<<countLoopNode(head);

   return 0;
}
The number of nodes in the loop are 6>]
Java Program to display time in 24-hour format

Use the SimpleDateFormat class to display time in 24-hour format.
Set the format
Date dt = new Date();
SimpleDateFormat dateFormat;
dateFormat = new SimpleDateFormat("kk:mm:ss");
Now, the following will display time in 24-hour format
dateFormat.format(dt)
The following is an example
 Live Demo
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Date dt = new Date();
      SimpleDateFormat dateFormat;
      dateFormat = new SimpleDateFormat("kk:mm:ss");
      System.out.println("Time in 24 hr format = "+dateFormat.format(dt));
   }
}
Time in 24 hr format = 11:40:52
Tryit Editor v3.7

Tryit: input type = radio
How will you select a particular value in a dropdown without using the methods of Select class in Selenium?

We can select a particular value in a dropdown using the method of Select class by using findElements() method.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.support.ui.Select;
public class OptionsClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/tutor_connect/index.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // getting the list of elements with the xpath
      List<WebElement> opt = driver.findElements(By.xpath("//select[@name=’selType’]//option"));
      int s = opt.size();
      // Iterating through the list selecting the desired option
      for( int j = 0; j< opt.size();j++){
         // if the option is By Subject click that option
         if( opt.get(j).getText().equals("By Subject")){
            opt.get(j).click();
            break;
         }
      }
      driver.quit();
   }
}
Group Integers in Python

Suppose we have a list of numbers called nums, we have to check whether we can split the list into 1 or more groups such that: 1. Size of each group is greater than or equal to 2. 2. Sizes of all groups are same. 3. All the numbers present in each group are the same.
So, if the input is like [3, 4, 6, 9, 4, 3, 6, 9], then the output will be True.
To solve this, we will follow these steps −
counts := a map where each key are distinct element and values are their frequencies
temp := 0
for each count in counts, doif temp is same as 0, thentemp := counts[count]otherwise,temp := gcd of counts[count] and tempif temp is same as 1, thenreturn False
if temp is same as 0, thentemp := counts[count]
temp := counts[count]
otherwise,temp := gcd of counts[count] and temp
temp := gcd of counts[count] and temp
if temp is same as 1, thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
 Live Demo
from collections import Counter
import math
class Solution:
   def solve(self, nums):
      counts = Counter(nums)
      temp = 0
      for count in counts:
         if temp == 0:
            temp = counts[count]
         else:
            temp = math.gcd(counts[count], temp)
            if temp == 1:
               return False
      return True
ob = Solution()
L = [3, 4, 6, 9, 4, 3, 6, 9]
print(ob.solve(L))
[3, 4, 6, 9, 4, 3, 6, 9]
True
MD5 hash in Java

05 Aug, 2020
To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.
MessageDigest Class provides following cryptographic hash function to find hash value of a text, they are:1. MD52. SHA-13. SHA-256
This Algorithms are initialize in static method called getInstance(). After selecting the algorithm it calculate the digest value and return the results in byte array.
BigInteger class is used, which converts the resultant byte array into its sign-magnitude representation.
This representation converts into hex format to get the MessageDigest
Examples:
Input : hello world
Output : 5eb63bbbe01eeed093cb22bb8f5acdc3

Input : GeeksForGeeks
Output : e39b9c178b2c9be4e99b141d956c6ff6

import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;  // Java program to calculate MD5 hash valuepublic class MD5 {    public static String getMd5(String input)    {        try {              // Static getInstance method is called with hashing MD5            MessageDigest md = MessageDigest.getInstance("MD5");              // digest() method is called to calculate message digest            //  of an input digest() return array of byte            byte[] messageDigest = md.digest(input.getBytes());              // Convert byte array into signum representation            BigInteger no = new BigInteger(1, messageDigest);              // Convert message digest into hex value            String hashtext = no.toString(16);            while (hashtext.length() < 32) {                hashtext = "0" + hashtext;            }            return hashtext;        }           // For specifying wrong message digest algorithms        catch (NoSuchAlgorithmException e) {            throw new RuntimeException(e);        }    }      // Driver code    public static void main(String args[]) throws NoSuchAlgorithmException    {        String s = "GeeksForGeeks";        System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));    }}
Output:
Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6
References: Java Docs for MessageDigest
Computer Networks
Hash
Java Programs
Hash
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Count pairs with given sum