code-rag-bench/online-tutorials huggingface dataset:
Insert Python list into PostgreSQL database

23 Sep, 2021
In this article, we will discuss how to Insert a Python list into PostgreSQL database using pyscopg2 module.
Psycopg2 is the most popular PostgreSQL adapter for the Python programming language. Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-threaded applications and manages its own connection pool. This module can be installed using the given command:
pip install psycopg2
To insert all records the list is traversed and the values are inserted one by one.
Syntax :
list = [(),(),.....,()]
for d in list:
    cursor.execute("INSERT into table_name(
    column1,column2, colum3.....) VALUES (%s, %s, %s,.....)", d)
First import all the required libraries into the working space and establish database connection. Set auto-commit to false and create a cursor object. Now, create a list of data to be inserted into the table. Loop through the list and insert values. Commit and close connection.
Example: Inserting list values to database
Python3
# importing psycopg2 moduleimport psycopg2  # establishing the connectionconn = psycopg2.connect(    database="postgres",    user='postgres',    password='password',    host='localhost',    port='5432')  # creating a cursor objectcursor = conn.cursor()  # creating tablesql = '''CREATE TABLE employee( id  SERIAL NOT NULL, name varchar(20) not null, state varchar(20) not null)'''    # list that contain records to be inserted into tabledata = [('Babita', 'Bihar'), ('Anushka', 'Hyderabad'),         ('Anamika', 'Banglore'), ('Sanaya', 'Pune'),        ('Radha', 'Chandigarh')]  # inserting record into employee tablefor d in data:    cursor.execute("INSERT into employee(name, state) VALUES (%s, %s)", d)    print("List has been inserted to employee table successfully...")  # Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output:
List has been inserted into employee table successfully
Example: Check whether data is being shown in the employee table or not. 
Python3
# importing psycopg2 moduleimport psycopg2  # establishing the connectionconn = psycopg2.connect(    database="postgres",    user='postgres',    password='password',    host='localhost',    port='5432')  # creating cursor objectcursor = conn.cursor()  # query to sort table by namesql2 = 'select * from employee;'# executing querycursor.execute(sql2)  # fetching the resultprint(cursor.fetchall())  # Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output
[(1, ‘Babita’, ‘Bihar’), (2, ‘Anushka’, ‘Hyderabad’), (3, ‘Anamika’, ‘Banglore’), (4, ‘Sanaya’, ‘Pune’), (5, ‘Radha’, ‘Chandigarh’)]
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
time.ParseDuration() Function in Golang With Examples

02 Apr, 2020
Go language provides inbuilt support for measuring and displaying time with the help of the time package. In this package, the calendrical calculations always assume a Gregorian calendar with no leap seconds. This package provides a ParseDuration() function which parses a duration string. Duration string is a signed sequence of decimal numbers with optional fraction and unit suffix, like “100ms”, “2.3h” or “4h35m”. To access ParseDuration() function you need to add a time package in your program with the help of the import keyword.
Note: Valid time units are “ns”, “us” (or “μs”), “ms”, “s”, “m”, “h”.
Syntax:
func ParseDuration(str string) (Duration, error)
Example 1:
// Golang program to illustrate// how to find time durationpackage main  import (    "fmt"    "time")  func main() {      // Using ParseDuration() function    hr, _ := time.ParseDuration("3h")    comp, _ := time.ParseDuration("5h30m40s")      fmt.Println("Time Duration 1: ", hr)    fmt.Println("Time Duration 2: ", comp)  }
Output:
Time Duration 1:  3h0m0s
Time Duration 2:  5h30m40s

Example 2:
// Golang program to illustrate// how to find time durationpackage main  import (    "fmt"    "time")  func main() {      // Using ParseDuration() function    hr, _ := time.ParseDuration("5h")    comp, _ := time.ParseDuration("2h30m40s")    m1, _ := time.ParseDuration("3μs")    m2, _ := time.ParseDuration("3us")      fmt.Println("Time Duration 1: ", hr)    fmt.Println("Time Duration 2: ", comp)    fmt.Printf("There are %.0f seconds in %v.\n",                            comp.Seconds(), comp)          fmt.Printf("There are %d nanoseconds in %v.\n",                              m1.Nanoseconds(), m1)          fmt.Printf("There are %6.2e seconds in %v.\n",                                 m2.Seconds(), m1)}
Output:
Time Duration 1:  5h0m0s
Time Duration 2:  2h30m40s
There are 9040 seconds in 2h30m40s.
There are 3000 nanoseconds in 3μs.
There are 3.00e-06 seconds in 3μs.

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
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to convert a string in lower case in Golang?
How to Parse JSON in Golang?
Chess Library in Python

05 Jul, 2021
The chess module is a pure Python chess library with move generation, move validation and support for common formats. We can play chess with it. It will help us to move the king queen, pawn, bishops and knights. We need to know the basics of chess to play chess with it. This module does every task in python that is possible in the real game.
pip install chess
We just have to import the chess library and with it, we can play chess. When we will import the chess library we have to call the function named board so that we can see the status of the chess board. 
Python3
# import required moduleimport chess # create board objectboard=chess.Board() # display chess boardprint(board)
  
The photo on left is gui representation and picture on left is the ASCII Board
 
Python3
# legal movesboard.legal_moves
Output:
<LegalMoveGenerator at 0x3586100 (Nh3, Nf3, Nc3, Na3, h3, g3, f3, e3, d3, c3, b3, a3, h4, g4, f4, e4, d4, c4, b4, a4)>
If we have to move any piece, we can check with above command that which moves we can do.
Python3
# moving playersboard.push_san("e4")# It means moving the particular piece at# e place to 4th position  # Display chess board print(board)
Output:
Change after the move .
Python3
# Verifying check mateboard.is_checkmate()
Output:
If There is checkmate then it will be TRUE else FALSE.It will be a boolean value.
Stalemate is a situation in the game of chess where the player whose turn it is to move is not in check but has no legal move. The rules of chess provide that when stalemate occurs, the game ends as a draw.
Python3
# Verifying stalemateboard.is_stalemate()
Output:
It will return a boolean value a TRUE or FALSE.
Python3
# codeboard.is_check()
Output:
It will return a boolean value a TRUE or FALSE.
With the new rules from July 2014, a game ends as a draw (even without a claim) once a fivefold repetition occurs or if there are 75 moves without a pawn push or capture. Other ways of ending a game take precedence. So there methods for checking these things also=
Python3
# codeboard.is_fivefold_repetition()board.is_seventyfive_moves()
Output:
Both of it will return a boolean value a TRUE or FALSE.
sweetyty
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Segregate elements by delimiter - GeeksforGeeks

29 Aug, 2020
Given list of Strings, segregate each string by delimiter and output different lists for prefix and suffix.
Input : test_list = [“7$2”, “8$5”, “9$1”], delim = “$”Output : [‘7’, ‘8’, ‘9’], [‘2’, ‘5’, ‘1’]Explanation : Different lists for prefix and suffix of “$”
Input : test_list = [“7*2”, “8*5”, “9*1”], delim = “*”Output : [‘7’, ‘8’, ‘9’], [‘2’, ‘5’, ‘1’]Explanation : Different lists for prefix and suffix of “*”
Method #1 : Using list comprehension + split()
The is one of the way in which this task can be performed. In this, we perform segregation using split(), the first part of split is compiled to one list comprehension and next to other.
Python3
# Python3 code to demonstrate working of # Segregate elements by delimiter# Using list comprehension + split()  # initializing listtest_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]  # printing original listprint("The original list : " + str(test_list))  # using delim delim = "$"  # using split() to split and different list comprehension# assigns results to different lists res1, res2 = [ele.split(delim)[0] for ele in test_list], [ele.split(delim)[1] for ele in test_list]  # printing result print("The filtered list 1 : " + str(res1))print("The filtered list 2 : " + str(res2))
The original list : ['7$2', '8$5', '9$1', '8$10', '32$6']
The filtered list 1 : ['7', '8', '9', '8', '32']
The filtered list 2 : ['2', '5', '1', '10', '6']

Method #2 : Using map() + list + zip() + generator expression
The combination of above functions can be used to solve this problem. In this, we extend the list construction logic using map() and zip() is used to perform split() functionality to each element.
Python3
# Python3 code to demonstrate working of # Segregate elements by delimiter# Using map() + list + zip() + generator expression  # initializing listtest_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]  # printing original listprint("The original list : " + str(test_list))  # using delim delim = "$"  # map() used to cast different sections to different listsres1, res2 = map(list, zip(*(ele.split(delim) for ele in test_list)))  # printing result print("The filtered list 1 : " + str(res1))print("The filtered list 2 : " + str(res2))
The original list : ['7$2', '8$5', '9$1', '8$10', '32$6']
The filtered list 1 : ['7', '8', '9', '8', '32']
The filtered list 2 : ['2', '5', '1', '10', '6']

Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python?
What is Python equivalent of the ! operator?

In C/C++, ! symbol is defined as not operator. Its equivalent in Python is not operator. It returns true if operand is false and vice versa
>>> not(True)
False
>>> not(False)
True
>>> not(20>30)
True
>>> not('abc'=='ABC')
True
How to use month input type in HTML?

The month input type is used in HTML using the <input type="month">. Using this, allow the users to select month and year. A date picker popup is visible whenever you will give a user input to the month input type.
Note − The input type month is not supported on Firefox and Internet Explorer. It works on Google Chrome.
You can try to run the following code to learn how to use month input type in HTML. It will show both month and year.
<!DOCTYPE html>
<html>
   <head>
      <title>HTML input month</title>
   </head>
   <body>
      <form action = "" method = "get">
         Details:<br><br>
         Student Name<br><input type="name" name="sname"><br>
         Month and Year of Birth<br><input type="month" name="bmonth"><br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
How to rename directory using Python?

You can rename a directory in Python by moving it using the shutil module. The shutil.move(src, dst) moves the directory from src to dst. If you just change the name of the directory without specifying the path, you'll basically be renaming it.
>>> import shutil
>>> shutil.move('my_folder', 'new_name')
The above code renames my_folder to new_name. You could also use the os.rename(src, dst) for renaming directories.
>>> import os
>>> os.rename('my_folder', 'new_name')
C++ Program to Rotate bits of a number - GeeksforGeeks

11 Dec, 2021
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put back at left end. 
Example: Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000...11100101) becomes 00..0011100101000. Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000...11100101) by 3 becomes 101000..0011100.  
C++
// C++ code to rotate bits // of number#include<iostream>  using namespace std;#define INT_BITS 32class gfg{      /*Function to left rotate n by d bits*/public:int leftRotate(int n, unsigned int d){          /* In n<<d, last d bits are 0. To     put first 3 bits of n at     last, do bitwise or of n<<d     with n >>(INT_BITS - d) */    return (n << d)|(n >> (INT_BITS - d));}  /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){    /* In n>>d, first d bits are 0.     To put last 3 bits of at     first, do bitwise or of n>>d    with n <<(INT_BITS - d) */    return (n >> d)|(n << (INT_BITS - d));}};  /* Driver code*/int main(){    gfg g;    int n = 16;    int d = 2;    cout << "Left Rotation of " << n <<             " by " << d << " is ";    cout << g.leftRotate(n, d);    cout << "Right Rotation of " << n <<            " by " << d << " is ";    cout << g.rightRotate(n, d);    getchar();}   // This code is contributed by SoM15242
Output : 
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
Please refer complete article on Rotate bits of a number for more details!
rotation
Bit Magic
C++
C++ Programs
Bit Magic
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Check whether K-th bit is set or not
Hamming code Implementation in C/C++
Vector in C++ STL
Arrays in C/C++
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
Binary to decimal and vice-versa in Python

Given Decimal number and Binary number, our task is to convert Decimal to Binary numbers and Binary to Decimal numbers.
Step1: Enter binary number.
Step2: Next take the length of the binary number.
Step3: Using for loop we convert binary to a decimal number.
Just like if the binary number is 1111, then the calculation would be
1*2**3+1*2**2+1*2**1+1*2**0 = 15
Step4: Display the number.
Step1: Enter the decimal number.
Step2: Using while loop
*Divide the number it by 2. Find both remainder and quotient. Take another variable initialized with 1.
Now remainder will be multiplied with this variable and added with the final output number. That variable will be incremented by 1.
*The first remainder is the last digit in the sequence.
Step3: Display the value.
 Live Demo
print("*****************************************************")
print(" DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION")
print("*****************************************************")
print(" For Decimal to Binary...Press 1.")
print(" For Binary to Decimal... Press 2")
print("*****************************************************")
my_choice=int(input("Enter your choice: "))
if my_choice==1:
i=1
s=0
my_dec=int(input("Enter decimal to be converted: "))
while my_dec>0:
   rem=int(my_dec%2)
   s=s+(i*rem)
   my_dec=int(my_dec/2)
   i=i*10
   print ("The binary of the given number is ",s,'.')
else:
   my_bin=input ('Enter binary to be converted: ')
   n=len(my_bin)
   res=0
for i in range(1,n+1):
   res=res+ int(my_bin[i-1])*2**(n-i)
print ("The decimal of the given binary is ",res,'.')
print("******************************************************")
*****************************************************
DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION
*****************************************************
print(" For Decimal to Binary...Press 1.")
print(" For Binary to Decimal... Press 2")
*****************************************************
Enter your choice: 1
Enter decimal to be converted: 15
The binary of the given number is 1111.
******************************************************

*****************************************************
DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION
*****************************************************
For Decimal to Binary...Press 1.
For Binary to Decimal... Press 2
*****************************************************
Enter your choice: 2
Enter binary to be converted: 1111
The decimal of the given binary is 15.
******************************************************
How to insert text at the beginning of the text box in Tkinter?

There are two types of Text editors that Tkinter supports -- the Entry widget and the Text widget. Tkinter text widgets are used to create the text editor where we can edit, add or delete the text whenever we need. We can create a text widget using the Text(parent) constructor. In order to insert a default text for the text widget, we can use the insert(INSERT, "text_to_insert") or insert("1.0", "text_to_insert") method after the text widget declaration.
In this example, we will insert the text at the beginning of the text box.
#Import the required Libraries
from tkinter import *

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

#Set the geometry of tkinter frame
win.geometry("750x250")

#Create a Text Box
text= Text(win, width= 50, height= 30, background=
"gray71",foreground="#fff",font= ('Sans Serif', 13, 'italic bold'))

#Insert the text at the begining
text.insert(INSERT, "Write Something About Yourself")
text.pack(expand= 1, fill= BOTH)

win.mainloop()
Run the above code to display the text box in the window.
In the given output, the default text is initially set to the beginning in the text box.
p5.js | createInput() Function

27 May, 2022
The createInput() function is used to create an input element in the DOM for accepting text input. The optional parameters can be used to set the type of input that can be entered. You can use the set() function to define the length of the box. 
Syntax:
createInput(value, type)
Parameters: This function accepts two parameters as mentioned above and described below:
value: This string parameter used to set the default value of the input.
type: This is a string parameter which sets the type of input. It can have values such as ‘text’, ‘password’, etc for accepting text with that specific format.
Return Value: It returns a pointer to the p5.Element with the created node. 
Below examples illustrate the createInput() function in p5.js: 
Example 1: 
javascript
function setup() {  createCanvas(300, 200);  textSize(18);   text("Enter username:", 20, 20);  usernameInput = createInput('Your username', 'text');  usernameInput.position(30, 40);   text("Enter password:", 20, 80);  passInput = createInput('', 'password');  passInput.position(30, 100);   text("Enter Date of Birth:", 20, 140);  dobInput = createInput('1970-01-01', 'date');  dobInput.position(30, 160);}
Output:
  
Example 2: 
javascript
function setup() {  createCanvas(600, 300);  textSize(28);  text("Write in the input box to display the text", 20, 40);   // Create input element  let inputElem = createInput('');  inputElem.input(onInput);  inputElem.position(30, 60)} function onInput() {  clear();  text("Write in the input box to display the text", 20, 40);   fill("green")  strokeWeight(10)  rect(0, 100, 600, 100)   // Display the text entered  fill("black")  text(this.value(), 20, 140)}
Output:
  
Online editor: https://editor.p5js.org/ 
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ 
Reference: https://p5js.org/reference/#/p5/createInput
vinayedula
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM onclick Event

28 Jun, 2019
The HTML DOM onclick event occurs when the user clicks on an element.
HTML DOM onclick event supports All HTML elements, EXCEPT:
<base>
<bdo>
<br>
<head>
<html>
<iframe>
<meta>
<param>
<script>
<style>
<title>
Syntax:
In HTML:
<element onclick="myScript">
In JavaScript:
object.onclick = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("click", myScript);
Example 1: Using HTML
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onclick Event</h2>        <button onclick="myFunction()">Click me</button>          <p id="demo"></p>          <script>            function myFunction() {                document.getElementById(                  "demo").innerHTML = "GeeksforGeeks";            }        </script>    </center></body>  </html>
Output:
Example 2: Using JavaScript
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onclick Event</h2>        <p id="demo">Click me.</p>          <script>            document.getElementById("demo").onclick = function() {                GFGfun()            };              function GFGfun() {                document.getElementById(                  "demo").innerHTML = "YOU CLICKED ME!";            }        </script>    </center></body>  </html>
Output:Before:
After:
Example 3: In JavaScript, using the addEventListener() method:
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onclick Event</h2>        <p id="demo">Click me.</p>          <script>            document.getElementById(              "demo").addEventListener("click", GFGfun);              function GFGfun() {                document.getElementById(                  "demo").innerHTML = "YOU CLICKED ME!";            }        </script>    </center></body>  </html>
Output:Before:
After:
Supported Browsers: The browsers supported by DOM onclick Event are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NULLIF() Function in SQL Server

21 Jan, 2021
NULLIF() :
This function in SQL Server is used to check if the two specified expressions are equal or not.
Features :
This function is used to check if the two given expressions are equal or not.
This function returns NULL if the given two expressions are equal.
This function returns the first expression if the two given expressions are not equal.
This function comes under Advanced Functions.
This function accepts two parameters i.e, the first expression, and the second expression.
Syntax :
NULLIF(expr1, expr2)
Parameter :
This method accepts two parameters.
expr1, expr2 – Specified expressions that are to be compared.
Returns :
It returns NULL if the given two expressions are equal else it returns the first expression if the two given expressions are not equal.
Example-1 :
Using the NULLIF() function and getting the output.
SELECT NULLIF(11, 11);
Output :
NULL
Here, NULL is returned as both the expressions are equal.
Example-2 :
Using the NULLIF() function and getting the output.
SELECT NULLIF('ab', 'abc');
Output :
ab
Here, ‘ab’ is returned as output as the stated expressions are not equal.
Example-3 :
Using NULLIF() function and getting the output using variables.
DECLARE @exp1 VARCHAR(50);
DECLARE @exp2 VARCHAR(50);
SET @exp1 = '2021/01/08';
SET @exp2 = '2021/01/08';
SELECT NULLIF(@exp1, @exp2);
Output :
NULL
Example-4 :
Using NULLIF() function and getting the output using CAST() function.
SELECT NULLIF(11, CAST(11.65 AS int));
Output :
NULL
Application :
This function is used to test if the two stated expressions are equal or not.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
Python String index() Method

12 Aug, 2021
Finding the string(substring) in a string is an application that has many uses in day-to-day life. Python offers this using a function index(), which returns the position of the first occurrence of a substring in a string. 
Syntax: 
ch.index(ch1, begp, endp)
Parameters: 
ch1 : The string to be searched for.
begp (default : 0) : This function specifies the position from where search has to be started. 
endp (default : string_len) : This function specifies the position from where search has to end.
Return Value: 
Returns the first position of the substring found.
Exception: 
Raises ValueError if argument string is not found. 
Python
# Python code to demonstrate the working of # index()  # initializing target string ch = "geeksforgeeks"  # initializing argument string ch1 = "geeks"  # using index() to find position of "geeks"# starting from 2nd index # prints 8pos = ch.index(ch1,2)  print ("The first position of geeks after 2nd index : ",end="")print (pos)
Output: 
The first position of geeks after 2nd index : 8
Note: The index() method is similar to find(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.
ValueError: This error is raised in the case when the argument string is not found in the target string.
Python
# Python code to demonstrate the exception of # index()  # initializing target string ch = "geeksforgeeks"  # initializing argument string ch1 = "gfg"  # using index() to find position of "gfg"# raises errorpos = ch.index(ch1)  print ("The first position of gfg is : ",end="")print (pos)
Output:
Traceback (most recent call last):
  File "/home/aa5904420c1c3aa072ede56ead7e26ab.py", line 12, in 
    pos = ch.index(ch1)
ValueError: substring not found
Practical Application: This function is used to extract the suffix or prefix length after or before the target word. The example below displays the total bit length of instruction coming from AC voltage given information in a string.
Python
# Python code to demonstrate the application of # index()  # initializing target stringsvoltages = ["001101 AC", "0011100 DC", "0011100 AC", "001 DC"]   # initializing argument string type = "AC"  # initializing bit-length calculatorsum_bits = 0  for i in voltages :           ch = i          if (ch[len(ch)-2]!='D'):       # extracts the length of bits in string        bit_len = ch.index(type)-1                # adds to total       sum_bits = sum_bits + bit_len  print ("The total bit length of AC is : ",end="")print (sum_bits)
Output: 
The total bit length of AC is : 13
AmiyaRanjanRout
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Turn an image into a Bootstrap 4 card background

Use the card-img-overlay class to turn an image into a card background.
You need to first set the <img> element and then use the card-img-overlay class as in the following code snippet −
<div class="card img-fluid" style="width:500px">
  <img class="card-img-top" src="https://www.tutorialspoint.com/avro/images/apache-avro-mini-logo.jpg" alt="Card image" style="width:100%">
  <div class="card-img-overlay">
    <h4 class="card-title">Avro</h4>
    <p class="card-text">Tutorial for Apache Avro</p>
    <a href="#" class="btn btn-info">Learn</a>
  </div>
</div>
Let us see an example to learn how to turn an image into a Bootstrap card background −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

<div class="container">
  <h2>Apach - Tool for Hadoop</h2>
  <div class="card img-fluid" style="width:500px">
    <img class="card-img-top" src="https://www.tutorialspoint.com/avro/images/apache-avro-mini-logo.jpg" alt="Card image" style="width:100%">
    <div class="card-img-overlay">
      <h4 class="card-title">Avro</h4>
      <p class="card-text">Tutorial for Apache Avro</p>
      <a href="#" class="btn btn-info">Learn</a>
    </div>
  </div>
</div>

</body>
</html>
Python | Substring Key match in dictionary

19 Jul, 2019
Sometimes, while working with dictionaries, we might have a use case in which we are not known the exact keys we require but just a specific part of keys that we require to fetch. This kind of problem can arise in many applications. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using items() + list comprehensionThe combination of above method can be used to perform this particular task in which we just access the key value pairs using the items function and list comprehension helps in the iteration and access logic.
# Python3 code to demonstrate working of# Substring Key match in dictionary# Using items() + list comprehension  # initializing dictionarytest_dict = {'All' : 1, 'have' : 2, 'good' : 3, 'food' : 4}  # initializing search key stringsearch_key = 'ood'  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using items() + list comprehension# Substring Key match in dictionaryres = [val for key, val in test_dict.items() if search_key in key]  # printing result print("Values for substring keys : " + str(res))
The original dictionary is : {'All': 1, 'food': 4, 'have': 2, 'good': 3}
Values for substring keys : [4, 3]

 
Method #2 : Using dict() + filter() + lambdaThe combination of above functions can be used to perform this particular task. In this, the dict and filter function is used to convert the result to dictionary and query for the substring in list respectively. The lambda performs the task of accessing all key-value pairs.
# Python3 code to demonstrate working of# Substring Key match in dictionary# Using dict() + filter() + lambda  # initializing dictionarytest_dict = {'All' : 1, 'have' : 2, 'good' : 3, 'food' : 4}  # initializing search key stringsearch_key = 'ood'  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using dict() + filter() + lambda# Substring Key match in dictionaryres = dict(filter(lambda item: search_key in item[0], test_dict.items()))  # printing result print("Key-Value pair for substring keys : " + str(res))
The original dictionary is : {'have': 2, 'good': 3, 'food': 4, 'All': 1}
Key-Value pair for substring keys : {'good': 3, 'food': 4}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List

When it is required to generate random numbers within a given range and append them to a list, a method is defined, that generates random numbers and ‘append’s them to an empty list.
Below is the demonstration of the same −
 Live Demo
import random
def random_gen(beg, end, my_num):
   my_result = []
   for j in range(my_num):
      my_result.append(random.randint(beg, end))
   return my_result
my_num = 19
beg = 1
end = 20
print("The number is :")
print(my_num)
print("The start and end values are :")
print(beg, end)
print("The elements are : ")
print(random_gen(beg, end, my_num))
The number is :
19
The start and end values are :
1 20
The elements are :
[12, 12, 5, 12, 11, 1, 5, 12, 19, 19, 7, 15, 18, 18, 10, 14, 3, 2, 11]
A method named ‘random_gen’ is defined, that takes three parameters- the beginning, end and a number.
A method named ‘random_gen’ is defined, that takes three parameters- the beginning, end and a number.
The method generates random numbers with the range of ‘beginning’ and ‘end’.
The method generates random numbers with the range of ‘beginning’ and ‘end’.
It appends it to a list.
It appends it to a list.
Outside the method, three values are defined.
Outside the method, three values are defined.
They are displayed on the console.
They are displayed on the console.
The method is called by passing this values as parameters.
The method is called by passing this values as parameters.
The output is displayed on the console.
The output is displayed on the console.
How do we add a push button to HTML?

Use the <button> tag in HTML to add a push button. The HTML <button> tag is used for creating a button within HTML form. You can also use <input> tag to create similar buttons.
The following are the attributes of the <button> tag −
You can try to run the following code to implement <button> tag in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Button Tag</title>
   </head>
   <body>
      <form>
         <button name = "button" value = "OK" type = "button">My Button</button>
      </form>
   </body>
</html>
Enumerate() in Python

When using the iterators, we need to keep track of the number of items in the iterator. This is achieved by an in-built method called enumerate(). The enumerate() method adds counter to the iterable. The returned object is a enumerate object. Its syntax and parameters are described below.
enumerate(iterable, start=0)
iterable - a sequence, an iterator, or objects that supports iteration
start – is the position in the iterator from where the counting starts.
Default is 0.
In the below example we take a dictionary and apply enumerate to it. In the result the default start is from 0 and we get the result printed starting with counter value as zero. We can also change the default start value to 5 and see a different result though the count remains same.
days= { 'Mon', 'Tue', 'Wed','Thu'}
enum_days = enumerate(days)
print(type(enum_days))

# converting it to alist
print(list(enum_days))

# changing the default counter to 5
enum_days = enumerate(days, 5)
print(list(enum_days))
Running the above code gives us the following result −
[(0, 'Tue'), (1, 'Thu'), (2, 'Mon'), (3, 'Wed')]
[(5, 'Tue'), (6, 'Thu'), (7, 'Mon'), (8, 'Wed')]
We can also use the code for looping and print the elements of the loop separately as shown in the code below.
 Live Demo
days= { 'Mon', 'Tue', 'Wed','Thu'}
enum_days = enumerate(days)
# enumearte using loop
for enum_days in enumerate(days):
   print(enum_days)

for count,enum_days in enumerate(days,5):
   print(count,enum_days)
Running the above code gives us the following result −
(0, 'Thu')
(1, 'Tue')
(2, 'Wed')
(3, 'Mon')
5 Thu
6 Tue
7 Wed
8 Mon
Count the number of possible triangles in C++

We are given an array which contains the length of sides of triangles. The goal is to find the number of possible triangles that can be made by taking any three sides from that array.
We will do this by checking if the sum of any two is always > third side. If yes these three sides can make a triangle. Increment count of possible triangles that can be made.
Let’s understand with examples.
Input − arr[]= {1,2,4,5}
Output − Count of possible triangles − 1
Explanation − Sides (2,4,5) can only make a triangle as 2+4>5 & 4+5>2 & 2+5>4
Input − arr[]= {4,5,6,3,2}
Output − Count of possible triangles − 7
Explanation − Sides (4,5,6), (4,5,2),(4,5,3),(4,3,2),(5,6,3),(5,6,2) can make triangles.
We take an integer array arr[] initialized with random positive numbers.
We take an integer array arr[] initialized with random positive numbers.
Function countTriangles(int arr[], int n) takes array and its length and return possible triangles that can be made.
Function countTriangles(int arr[], int n) takes array and its length and return possible triangles that can be made.
Take initial count of triangles as 0.
Take initial count of triangles as 0.
Take three for loops for three sides.
Take three for loops for three sides.
Outermost loop 0<=i<n-2, inner i<j<n-1 and innermost j<k<n
Outermost loop 0<=i<n-2, inner i<j<n-1 and innermost j<k<n
For sides arr[i],arr[j],arr[k] check if they form sides of triangle.
For sides arr[i],arr[j],arr[k] check if they form sides of triangle.
Check arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i] if true increment count.
Check arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i] if true increment count.
Return count as result.
Return count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int countTriangles(int arr[], int n){
   // Count of triangles
   int count = 0;
   for (int i = 0; i < n-2; i++){
      for (int j = i + 1; j < n-1; j++){
         for (int k = j + 1; k < n; k++){
            //any two sides have sum > third
            if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i])
               { count++; }
         }
      }
   }
   return count;
}
int main(){
   int Arr[] = { 1,2,5,3,6,8,10 };
   int len = sizeof(Arr) / sizeof(Arr[0]);
   cout << "count of Triangles possible : "<< countTriangles(Arr, len);
   return 0;
}
If we run the above code it will generate the following output −
count of Triangles possible : 8
How to find the column means of a column based on another column values that represent factor in an R data frame?

If we have a column that represent factor then we might want to find the mean of values in other column(s) for the factor levels. This is helpful in comparing the levels of the factor. In R, we can find the mean for such type of data by using aggregate function. Check out the below examples to understand how it can be done.
Consider the below data frame:
Live Demo
> x1<-sample(c(LETTERS[1:4]),20,replace=TRUE)
> y1<-rnorm(20,5,1)
> df1<-data.frame(x1,y1)
> df1
  x1   y1
1 D 5.801197
2 B 3.432060
3 B 6.154168
4 A 5.466655
5 D 5.171689
6 C 5.175170
7 B 5.353469
8 D 4.840470
9 C 4.158980
10 B 4.711343
11 D 4.348326
12 A 5.933382
13 A 3.484782
14 A 2.004760
15 C 4.963307
16 D 4.728794
17 B 3.606417
18 B 6.234446
19 C 4.625489
20 B 6.569928
Finding the mean of y1 based on values in x1:
> aggregate(.~x1,data=df1,mean)
  x1   y1
1 A 4.222395
2 B 5.151690
3 C 4.730736
4 D 4.978095
Live Demo
> x2<-sample(0:1,20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(x2,y2)
> df2
 x2 y2
1 1 6
2 0 5
3 1 3
4 0 3
5 1 4
6 0 7
7 0 5
8 0 3
9 0 5
10 0 4
11 0 4
12 0 7
13 0 4
14 0 6
15 0 2
16 1 7
17 0 9
18 1 2
19 0 6
20 0 5
Finding the mean of y2 based on values in x2:
> aggregate(.~x2,data=df2,mean)
 x2 y2
1 0 5.0
2 1 4.4
Python | Ways to sort list of strings in case-insensitive manner - GeeksforGeeks

16 Aug, 2021
Given a list of strings, A task is to sort the strings in a case insensitive manner. Given below are a few methods to solve the task. Method #1: Using casefold()  
Python3
# Python code to demonstrate# to sort list of# strings in case insensitive manner # Initialising listini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind',            'SIngh', 'manjeet', 'Munich'] # Sorting list in case sensitive mannerres1 = sorted(ini_list)  # Printing case-insensitiveprint("Case-sensitive sorted list", str(res1)) # Sorting list in case-insensitive mannerres2 = sorted(ini_list, key = lambda s: s.casefold()) # Printing resultprint("Case-insensitive sorted list", str(res2))        
Case-sensitive sorted list [‘Alind’, ‘GeeksForGeeks’, ‘Munich’, ‘SIngh’, ‘akshat’, ‘garg’, ‘manjeet’] Case-insensitive sorted list [‘akshat’, ‘Alind’, ‘garg’, ‘GeeksForGeeks’, ‘manjeet’, ‘Munich’, ‘SIngh’] 
 
  Method #2: Using lower()  
Python3
# Python code to demonstrate# to sort list of# strings in case insensitive manner # Initialising listini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind',            'SIngh', 'manjeet', 'Munich'] # Sorting list in case sensitive mannerini_list.sort()  # Printing case-insensitiveprint("Case-sensitive sorted list", str(ini_list)) # Sorting list in case-insensitive mannerini_list.sort(key = lambda x: x.lower()) # Printing resultprint("Case-insensitive sorted list", str(ini_list))    
Case-sensitive sorted list [‘Alind’, ‘GeeksForGeeks’, ‘Munich’, ‘SIngh’, ‘akshat’, ‘garg’, ‘manjeet’] Case-insensitive sorted list [‘akshat’, ‘Alind’, ‘garg’, ‘GeeksForGeeks’, ‘manjeet’, ‘Munich’, ‘SIngh’] 
 
sagartomar9927
Python list-programs
Python string-programs
Python-sort
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Destructors in C++ - GeeksQuiz

24 Nov, 2021
Destructors can be private. See Private Destructor for examples and uses of private destructors in C++.
constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 3
destructor for id 2
destructor for id 1
constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 1
destructor for id 2
destructor for id 3
Compiler Dependent.
constructor for id 1
destructor for id 1
A a;
B b(a);
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Spring - REST Controller
Epam Interview Experience for Junior Software Engineer
EPAM Interview Experience | On-Campus 2022
How to Read Text Files with Pandas?
Construct a DFA that Start With aa or bb
Python Data Structures and Algorithms
Critical Section in Synchronization - GeeksforGeeks

16 Dec, 2019
Critical Section:When more than one processes access a same code segment that segment is known as critical section. Critical section contains shared variables or resources which are needed to be synchronized to maintain consistency of data variable.In simple terms a critical section is group of instructions/statements or region of code that need to be executed atomically (read this post for atomicity), such as accessing a resource (file, input or output port, global data, etc.).
In concurrent programming, if one thread tries to change the value of shared data at the same time as another thread tries to read the value (i.e. data race across threads), the result is unpredictable.
The access to such shared variable (shared memory, shared files, shared port, etc...) to be synchronized. Few programming languages have built-in support for synchronization.
It is critical to understand the importance of race condition while writing kernel mode programming (a device driver, kernel thread, etc.). since the programmer can directly access and modifying kernel data structures.
A simple solution to the critical section can be thought as shown below,
acquireLock();
Process Critical Section
releaseLock();
A thread must acquire a lock prior to executing a critical section. The lock can be acquired by only one thread. There are various ways to implement locks in the above pseudo code. Let us discuss them in future articles.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
VaibhavRai3
ramswarup_kulhary
ravi_42
Process Synchronization
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Normal Forms in DBMS
Differences between TCP and UDP
Cache Memory in Computer Organization
LRU Cache Implementation
Memory Management in Operating System
'crontab' in Linux with Examples
Difference between Internal and External fragmentation
Change the tag's contents and replace with the given string using BeautifulSoup - GeeksforGeeks

26 May, 2021
Prerequisites: Beautifulsoup
Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to change contents within a tag and replace the contents to be changed with the given string. For this, replace_with() function of the module is used.
Syntax:
replace_with(“string”)
Approach:
Import module
Scrap data from webpage
Parse the string scraped to html
Select tag within which replacement has to be performed
Add string in place of the existing one using replace_with() function
Print replaced content
Program:
Python3
# importing BeautifulSoup Modulefrom bs4 import BeautifulSoup markup = '<a href="http://gfg.com/">Geeks for Geeks <i>gfg.com</i></a>' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # tag to be replacedold_tag = soup.a # new tagnew_tag = soup.new_tag("p") # input stringnew_tag.string = "gfg.in" '''replacing tag#page_element.replace_with("string") removes a tag or string from the tree,#and replaces it with the tag or string of your choice.'''old_tag.i.replace_with(new_tag) print(old_tag)
Output:
<a href=”http://gfg.com/”>Geeks for Geeks <p>gfg.in</p></a>
sweetyty
Picked
Python BeautifulSoup
Python bs4-Exercises
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()