code-rag-bench/online-tutorials huggingface dataset:
Python 3 - break statement

The break statement is used for premature termination of the current loop. After abandoning the loop, execution at the next statement is resumed, just like the traditional break statement in C.
The most common use of break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop and starts executing the next line of the code after the block.
The syntax for a break statement in Python is as follows −
break

#!/usr/bin/python3

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print ('Current Letter :', letter)
  
var = 10                    # Second Example
while var > 0:              
   print ('Current variable value :', var)
   var = var -1
   if var == 5:
      break

print ("Good bye!")
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!

The following program demonstrates use of the break in a for loop iterating over a list. User inputs a number, which is searched in the list. If it is found, then the loop terminates with the 'found' message.
#!/usr/bin/python3

no = int(input('any number: '))
numbers = [11,33,55,39,55,75,37,21,23,41,13]

for num in numbers:
   if num == no:
      print ('number found in list')
      break
else:
   print ('number not found in list')
The above program will produce the following output −
any number: 33
number found in list

any number: 5
number not found in list


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Python 3 - List count() Method

The count() method returns count of how many times obj occurs in list.
Following is the syntax for count() method −
list.count(obj)

obj − This is the object to be counted in the list.
This method returns count of how many times obj occurs in list.
The following example shows the usage of count() method.
#!/usr/bin/python3

aList = [123, 'xyz', 'zara', 'abc', 123];

print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))
When we run above program, it produces the following result −
Count for 123 :  2
Count for zara :  1


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to get the length, size, and shape of a series in Pandas?

There are several ways to get the number of elements present in a pandas Series object. And the class pandas series constructor provides you several attributes and methods to determine the features of the Series object.
In the following example, we will learn about the size and shape attributes of the pandas Series object. The size attribute will return an integer value representing the count of the total elements present in a Series object, which works similarly to the python length function.
The shape attribute will return a tuple with two elements in it, those two elements are integer values representing the rows and columns count of a pandas data structure object. Here the pandas Series is a one-Dimensional pandas data structure object with labeled indices, hence the output for the shape attribute will return you a tuple with a single integer element representing the rows count of a pandas Series object.
# importing pandas packages
import pandas as pd

# creating pandas Series object
series = pd.Series(list('ABCDEFGH'))
print(series)

# to get length of the series
print('Length of series:',len(series))

print('Size of the Series:', series.size)

print('The shape of series:',series.shape)
Here we have created a simple series object with string data, and the data is A, B, C, D, E, F, G, H, with the index values 0, 1, 2 to 7.
By using the python length function we can get the length of the Series object, as well as size and shape attributes will return the count of elements and dimension of the series.
0   A
1   B
2   C
3   D
4   E
5   F
6   G
7   H
dtype: object

Length of series: 8
Size of the Series: 8
The shape of series: (8,)
The integer and Alphabet columns are the representation of the series object output and the data type of this series is an object data type. And we can see the output of length function, size attribute, and shape attribute in the above output block.
# importing pandas packages
import pandas as pd

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white', 'R':'red', 'G':'green'})
print(series)

# to get length of the series
print('Length of series:',len(series))

print('Size of the Series:', series.size)

print('The shape of series:',series.shape)
The series object was created by using a dictionary with keys and value pairs, in this example we verified the length, size and shape of the series object by using pandas series attributes.
B   black
W   white
R     red
G   green
dtype: object
Length of series: 4
Size of the Series: 4
The shape of series: (4,)
The length, size and shape of our series object can be seen in the above output block.
Logistic Regression in Python - Testing

We need to test the above created classifier before we put it into production use. If the testing reveals that the model does not meet the desired accuracy, we will have to go back in the above process, select another set of features (data fields), build the model again, and test it. This will be an iterative step until the classifier meets your requirement of desired accuracy. So let us test our classifier.
To test the classifier, we use the test data generated in the earlier stage. We call the predict method on the created object and pass the X array of the test data as shown in the following command −
In [24]: predicted_y = classifier.predict(X_test)

This generates a single dimensional array for the entire training data set giving the prediction for each row in the X array. You can examine this array by using the following command −
In [25]: predicted_y

The following is the output upon the execution the above two commands −
Out[25]: array([0, 0, 0, ..., 0, 0, 0])

The output indicates that the first and last three customers are not the potential candidates for the Term Deposit. You can examine the entire array to sort out the potential customers. To do so, use the following Python code snippet −
In [26]: for x in range(len(predicted_y)):
   if (predicted_y[x] == 1):
      print(x, end="\t")

The output of running the above code is shown below −
The output shows the indexes of all rows who are probable candidates for subscribing to TD. You can now give this output to the bank’s marketing team who would pick up the contact details for each customer in the selected row and proceed with their job.
Before we put this model into production, we need to verify the accuracy of prediction.
To test the accuracy of the model, use the score method on the classifier as shown below −
In [27]: print('Accuracy: {:.2f}'.format(classifier.score(X_test, Y_test)))

The screen output of running this command is shown below −
Accuracy: 0.90

It shows that the accuracy of our model is 90% which is considered very good in most of the applications. Thus, no further tuning is required. Now, our customer is ready to run the next campaign, get the list of potential customers and chase them for opening the TD with a probable high rate of success.

    15 Lectures 
     1 hours 

 Ajay

    53 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
What is unsigned in MySQL?

Unsigned allows us to enter positive value; you cannot give any negative number. Let us create
a table to understand unsigned in MySQL. To create a table, we will use the CREATE command.
Let us create a table −
mysql> CREATE table UnsignedDemo
-> (
-> id int unsigned
-> );
Query OK, 0 rows affected (0.61 sec)
After that I will insert only positive values. Let us insert some records −
mysql> INSERT into UnsignedDemo values(124);
Query OK, 1 row affected (0.09 sec)

mysql> INSERT into UnsignedDemo values(78967);
Query OK, 1 row affected (0.14 sec)
I am displaying all the records with the help of SELECT command −
mysql> SELECT * from UnsignedDemo;

The following is the output
+-------+
| id    |
+-------+
| 124   |
| 78967 |
+-------+
2 rows in set (0.00 sec)
Now, we will try to insert only negative values. But while doing this, we will get the following
error, since the column ‘id’ is unsigned −
mysql> INSERT into UnsignedDemo values(-124);
ERROR 1264 (22003): Out of range value for column 'id' at row 1
Python | Consecutive String Comparison - GeeksforGeeks

29 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it’s next element in a list and return all strings whose next element is similar list. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + loopThis is one way in which this task can be performed. In this, we use zip() to combine the element and it’s next element and then compare for truth and save it in list.
# Python3 code to demonstrate working of# Consecutive String Comparison# using zip() + loop  # initialize list test_list = ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks']  # printing original list print("The original list : " + str(test_list))  # Consecutive String Comparison# using zip() + loopres = []for i, j in zip(test_list, test_list[1: ]):    if i == j:        res.append(i)  # printing resultprint("List of Consecutive similar elements : " + str(res))
The original list : ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks']
List of Consecutive similar elements : ['gfg', 'best', 'geeks']

 
Method #2 : Using list comprehension + zip()This task can also be performed using above functionalities. In this, we use one-liner approach to solve this problem using list comprehension. The method is similar to above one.
# Python3 code to demonstrate working of# Consecutive String Comparison# using zip() + list comprehension  # initialize list test_list = ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks']  # printing original list print("The original list : " + str(test_list))  # Consecutive String Comparison# using zip() + list comprehensionres = [i for (i, j) in zip(test_list, test_list[1:]) if i == j]  # printing resultprint("List of Consecutive similar elements : " + str(res))
The original list : ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks']
List of Consecutive similar elements : ['gfg', 'best', 'geeks']

Python list-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 ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Tryit Editor v3.7

Tryit: HTML external link
LISP - Data Types

In LISP, variables are not typed, but data objects are.
LISP data types can be categorized as.
Scalar types − for example, number types, characters, symbols etc.
Scalar types − for example, number types, characters, symbols etc.
Data structures − for example, lists, vectors, bit-vectors, and strings.
Data structures − for example, lists, vectors, bit-vectors, and strings.
Any variable can take any LISP object as its value, unless you have declared it explicitly.
Although, it is not necessary to specify a data type for a LISP variable, however, it helps in certain loop expansions, in method declarations and some other situations that we will discuss in later chapters.
The data types are arranged into a hierarchy. A data type is a set of LISP objects and many objects may belong to one such set.
The typep predicate is used for finding whether an object belongs to a specific type.
The type-of function returns the data type of a given object.
Type specifiers are system-defined symbols for data types.
Apart from these system-defined types, you can create your own data types. When a structure type is defined using defstruct function, the name of the structure type becomes a valid type symbol.
Create new source code file named main.lisp and type the following code in it.
(setq x 10)
(setq y 34.567)
(setq ch nil)
(setq n 123.78)
(setq bg 11.0e+4)
(setq r 124/2)

(print x)
(print y)
(print n)
(print ch)
(print bg)
(print r)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
10 
34.567 
123.78 
NIL 
110000.0 
62

Next let's check the types of the variables used in the previous example. Create new source code file named main. lisp and type the following code in it.
(defvar x 10)
(defvar y 34.567)
(defvar ch nil)
(defvar n 123.78)
(defvar bg 11.0e+4)
(defvar r 124/2)

(print (type-of x))
(print (type-of y))
(print (type-of n))
(print (type-of ch))
(print (type-of bg))
(print (type-of r))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
(INTEGER 0 281474976710655) 
SINGLE-FLOAT 
SINGLE-FLOAT 
NULL 
SINGLE-FLOAT 
(INTEGER 0 281474976710655)


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Node.js Assert module - GeeksforGeeks

07 Oct, 2021
Assert module in Node.js provides a bunch of facilities that are useful for the assertion of the function. The assert module provides a set of assertion functions for verifying invariants. If the condition is true it will output nothing else an assertion error is given by the console.
Install the assert module using the following command:
npm install assert
Note: Installation is an optional step as it is inbuilt Node.js module.
Importing module:
const assert = require("assert");
Example 1:
console.clear()const assert = require('assert');  let x = 4;let y = 5;  try {      // Checking condition    assert(x == y);}catch {      // Error output    console.log(        `${x} is not equal to ${y}`);}
Output:
Example 2:
console.clear()const assert = require('assert');  let x = 4;let y = 5;  assert(x > y);
Note: In this example, no try-catch is given so an assertion error of the kind given below will be the output.
Output:
Note: Text Highlighted is the assertion error.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
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?
Convert a string to an integer in JavaScript
HTML <textarea> readonly Attribute

The readonly attribute of the <textarea> element is used to set a textarea as readonly. The visitor cannot change the text in the textarea if it is set as readonly.
However, visitor can copy that content.
Following is the syntax −
<textarea readonly>
Let us now see an example to implement the readonly attribute of the <textarea> element −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Interview Questions</h2>
<p>Q1</p>
   <textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)">
   </textarea>
   <p>Q2</p>
   <textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)">
   </textarea>
   <p>Guidelines to appear for interview:</p>
   <textarea rows="6" cols="70" readonly>
      The interviewee should reach at 10AM with the certificates.
   </textarea>
</body>
</html>
In the above example, we have 3 textarea −
<p>Q1</p>
<textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)">
</textarea>
<p>Q2</p>
<textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)">
</textarea>
<p>Guidelines to appear for interview:</p>
<textarea rows="6" cols="70" readonly>
   The interviewee should reach at 10AM with the certificates.
</textarea>
One of this textarea is set as readonly, therefore users won’t be able to add any text in it −
<textarea rows="6" cols="70" readonly>
   The interviewee should reach at 10AM with the certificates.
</textarea>
Java Program to format date in mm-dd-yyyy hh:mm:ss format

Let us format date in mm-dd-yyyy hh:mm:ss format −
// displaying date in mm-dd-yyyy hh:mm:ss format
Format f = new SimpleDateFormat("mm-dd-yyyy hh:mm:ss");
String str = f.format(new Date());
System.out.println("Current Date in MM-dd-yyyy hh:mm:ss format = "+str);
Since we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date −
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
      System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
      // displaying date in mm-dd-yyyy hh:mm:ss format
      Format f = new SimpleDateFormat("mm-dd-yyyy hh:mm:ss");
      String str = f.format(new Date());
      System.out.println("Current Date in MM-dd-yyyy hh:mm:ss format = "+str);
      // displaying date
      f = new SimpleDateFormat("dd/MMMM/yyyy");
      String strDate = f.format(new Date());
      System.out.println("Current Date = "+strDate);
      // current time
      f = new SimpleDateFormat("HH.mm.ss Z");
      String strTime = f.format(new Date());
      System.out.println("Current Time = "+strTime);
   }
}
Today's date and time = Mon, 26 Nov 2018 09:34:11 +0000
Current Date in MM-dd-yyyy hh:mm:ss format = 11-26-2018 09:34:11
Current Date = 26/November/2018
Current Time = 09.34.11 +0000
modal(options) method in Bootstrap

If you want to set content as a Bootstrap modal, then use the .modal(options) method.
For this, use jQuery to set the model on the click of a button as in the following code snippet −
$(document).ready(function(){
  $("#button1").click(function(){
    $("#newModal1").modal({backdrop: true});
  });
});
Let us now implement the modal(“options”) class. Here, we have two buttons that would generate different types of modals on click. One of them would close on clicking outside the modal, but another one will not close.
Here is the complete example −
Live Demo
<!DOCTYPE html>
<html>
<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/3.3.7/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/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
 <div class="container">
   <h2>Sample</h2>
   <button type="button" class="btn btn-default btn-lg" id="button1">Modal One</button>
   <button type="button" class="btn btn-default btn-lg" id="button2">Modal Two</button>

   <div class="modal fade" id="newModal1" role="dialog">
     <div class="modal-dialog">
       <div class="modal-content">
         <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">×</button>
           <h4 class="modal-title">Sample Modal 1</h4>
         </div>
       <div class="modal-body">
         <p>Click outside to close it.</p>
       </div>
       <div class="modal-footer">
         <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
       </div>
     </div>
    </div>
  </div>

  <div class="modal fade" id="newModal2" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Sample Modal 2</h4>
        </div>
      <div class="modal-body">
       <p>It won't close on clicking outside.</p>
      </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
    </div>
   </div>
  </div>
 </div>
</div>

<script>
$(document).ready(function(){
  $("#button1").click(function(){
    $("#newModal1").modal({backdrop: true});
  });
  $("#button2").click(function(){
    $("#newModal2").modal({backdrop: false});
  });
});
</script>

</body>
</html>
Amazon RDS - MySQL DBA Tasks 

As with every other database, Amazon RDS MYSQL also needs DBA tasks to fine tune the database and do periodic health checks etc. But as the AWS platform does not allow the shell access to the DB, there are a limited number of DBA tasks that can be performed as compared to the on-premise installation of MySQL. Below is a list of common DBA tasks that can be performed in AWS RDS MySQL database and their descriptions.
The MySQL error log ( mysql-error.log) file can be viewed by using the Amazon RDS console or by retrieving the log using the Amazon RDS CLI. mysql-error.log is flushed every 5 minutes, and its contents are appended to mysql-error-running.log. The mysql-error-running.log file is then rotated every hour and the hourly files generated during the last 24 hours are retained.
Below there are links to two log files described above.
Using CLI the log files are published to CloudWatch Logs as a JSON Object. 
aws rds modify-db-instance \
    --db-instance-identifier mydbinstance \
    --cloudwatch-logs-export-configuration '{"EnableLogTypes":["audit","error","general","slowquery"]}' \
    --apply-immediately
   
Sometimes the DBA needs to kill a long running session or query which is not giving the result quick enough. This DBA task is done by first finding the process ID of the query and then using a RDS function to kill the query. The below commands are the examples.
# get the ID
Select * from INFORMATION_SCHEMA.PROCESSLIST
#Apply the Kill Function
CALL mysql.rds_kill(processID);
We can improve the recovery time from a crash by setting a DB parameter called innodb_file_per_table. We can find this parameter in the RDS console as shown below.
Next we can Search for the parameter name as shown below.
Amazon RDS sets the default value for innodb_file_per_table parameter to 1, which allows you to drop individual InnoDB tables and reclaim storage used by those tables for the DB instance. This speeds up the recovery time from the crash.
Stopping a DB, Rebooting it or creating snapshots etc can be done easily through RDS console as shown in the below diagram.
 Print
 Add Notes
 Bookmark this page
How to get the current index of an array while using forEach loop in Kotlin?

Sometimes it becomes necessary to access the index of an array. In this article, we will see how we can access the index of an array in Kotlin while using forEach loop.
nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible.
In the following example, we will traverse through the "Subject" array and we will print the index along with the value.
fun main() {
   var subject = listOf("Java", "Kotlin", "JS", "C")

   subject.forEachIndexed {index, element ->
      println("index = $index, item = $element ")
   }
}
It will generate the following output −
index = 0, item = Java
index = 1, item = Kotlin
index = 2, item = JS
index = 3, item = C
withIndex() is a library function of Kotlin using which you can access both the index and the corresponding values of an array. In the following example, we will be using the same array and we will be using withIndex() to print its values and index. This has to be used with a for loop.
fun main() {
   var subject=listOf("Java", "Kotlin", "JS", "C")

   for ((index, value) in subject.withIndex()) {
      println("The subject of $index is $value")
   }
}
It will generate the following output −
The subject of 0 is Java
The subject of 1 is Kotlin
The subject of 2 is JS
The subject of 3 is C
Latitude and longitude of the user's position in JavaScript?

The geolocation property returns a Geolocation object that can be used to locate the user's position. The object provided was navigator.geolocation.This might be annoying to the privacy of the user, therefore, the position is not available unless the user approves it.
navigator.geolocation;
This method returns the latitude and longitude of the user's position without taking any parameter as an argument.
In this example using position.coords, which is a read-only property, along with javascript's geolocation property, the latitude and longitude of the user's location is found out and the result is displayed in the output.
Live Demo
<html>
<body>
<p id = "location"></p>
<script>
   var loc = document.getElementById("location");
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(getPos);
   }
   function getPos(position) {
      loc.innerHTML = "Latitude: " + position.coords.latitude +
      " </br> Longitude: " + position.coords.longitude;
   }
</script>
</body>
</html>
Latitude: 17.4381439
Longitude: 78.3948683
Multiplexer Design using Verilog HDL - GeeksforGeeks

07 Jun, 2021
Prerequisite – Multiplexers in Digital Logic Problem : Design of a 2:1 MUX using Verilog Hardware Description Language along with Testbench. 
Concepts : A multiplexer is a combinational type of digital circuits that are used to transfer one of the available input lines to the single output and, which input has to be transferred to the output it will be decided by the state(logic 0 or logic 1) of the select line signal. 2:1 Multiplexer is having two inputs, one select line (to select one of the two input) and a single output. 
 
Truth Table –  
Verilog HDL code of 2:1 MUX : 
Design –
// define a module for the design
module mux2_1(in1, in2, select, out);

// define input  port
input in1, in2, select;

// define the output port
output out;

// assign one of the inputs to the output based upon select line input
assign out = select ? in2 : in1;
endmodule :mux2_1
Testbench –  
module test;
reg in1, in2, select;
wire out;

// design under test 
mux2_1 mux(.in1(in1), .in2(in2), 
            .select(select), .out(out));

// list the input to the design
initial begin in1=1'b0;in2=1'b0;select=1'b0; 
        #2    in1=1'b1;
        #2    select=1'b1;
        #2    in2=1'b1;
        #2    $stop();
        end

// monitor the output whenever any of the input changes
initial begin $monitor("time=%0d, input1=%b, input2=%b, 
                       select line=%b, output=%b", $time, 
                        in1, in2, select, out);
        end
endmodule :test
Expected Output – 
time=0, input1=0, input2=0, select line=0, out=0
time=2, input1=1, input2=0, select line=0, out=1
time=4, input1=1, input2=0, select line=1, out=0
time=6, input1=1, input2=1, select line=1, out=1 
manishkj116
Code_Mech
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BCD to 7 Segment Decoder
Carry Look-Ahead Adder
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Encoder in Digital Logic
Shift Micro-Operations in Computer Architecture
Half Adder in Digital Logic
Encoders and Decoders in Digital Logic
Difference between Half adder and full adder
Analog to Digital Conversion
Difference between Flip-flop and Latch
C++ program to generate random number

Let us see how to generate random numbers using C++. Here we are generating a random number
in range 0 to some value. (In this program the max value is 100).
To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand.
The declaration of srand() is like below
void srand(unsigned int seed)
It takes a parameter called seed. This is an integer value to be used as seed by the pseudo-random
number generator algorithm. This function returns nothing.
To get the number we need the rand() method. To get the number in range 0 to max, we are using
modulus operator to get the remainder.
For the seed value we are providing the time(0) function result into the srand() function.
#include<iostream>
#include<cstdlib>
#include
using namespace std;
main() {
   int max;
   max = 100; //set the upper bound to generate the random number
   srand(time(0));
   cout << "The random number is: "<<rand()%max;
}
The random number is: 51
The random number is: 29
The random number is: 47
Animating a Lightbox with CSS & JavaScript

We can style lightbox in our webpage using CSS and JavaScript. The following example styles lightbox.
 Live Demo
<!DOCTYPE html>
<html>
<style>
#parent {
   margin: 2%;
   padding: 0;
   box-sizing: border-box;
   background: cornflowerblue;
   text-align: center;
}
html,body {
   height:100%;
   max-height:100%;
   min-height:100%;
}
.smart {
   display: block;
   margin: 0 auto;
   width: 150px;
   height :150px;
}
.animation2 {
   -webkit-transition: .4s ease-in-out;
   -moz-transition: .4s ease-in-out;
   -ms-transition: .4s ease-in-out;
   -o-transition:.4s ease-in-out;
   transition:.4s ease-in-out;
}
.customLightbox img {
   position: absolute;
   margin: auto;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   max-width: 0%;
   max-height: 0%;
}
#lightbox-controls {
   position: fixed;
   height: 70px;
   width: 70px;
   top: -70px;
   right: 0;
   z-index: 2;
   background: rgba(0,0,0,.1);
}
#close-lightbox {
   display: block;
   position: absolute;
   overflow: hidden;
   height: 50px;
   width: 50px;
   text-indent: -5000px;
   right: 10px;
   top: 10px;
   -webkit-transform: rotate(45deg);
   -moz-transform: rotate(45deg);
   -ms-transform: rotate(45deg);
   -o-transform: rotate(45deg);
   transform: rotate(45deg);
}
#close-lightbox:before {
   content: '';
   display: block;
   position: absolute;
   height: 0px;
   width: 3px;
   left: 24px;
   top :0;
   background: white;
}
#close-lightbox:after {
   content: '';
   display: block;
   position: absolute;
   width: 0px;
   height: 3px;
   top: 24px;
   left:0;
   background: white;
}
.customLightbox:target {
   top: 0%;
   bottom: 0%;
   opacity: 1;
}
.customLightbox:target img {
   max-width: 100%;
   max-height: 100%;
}
.customLightbox:target ~ #lightbox-controls {
   top: 0px;
}
.customLightbox:target ~ #lightbox-controls #close-lightbox:after {
   width: 50px;
}
.customLightbox:target ~ #lightbox-controls #close-lightbox:before {
   height: 50px;
}
@-webkit-keyframes smart {
   0% {
      -webkit-transform: rotate(2deg);
   }
   20% {-webkit-transform: rotate(-2deg);}
   40% {-webkit-transform: rotate(2deg);}
   60% {-webkit-transform: rotate(-2deg);}
   80% {-webkit-transform: rotate(2deg);}
   100% {-webkit-transform: rotate(-2deg);}
}
</style>
<body>
<div id="parent">
<h3>Lightbox Example</h3>
<a href="#picture" class="smart"><img src="https://images.unsplash.com/photo1611460116297-
586f43de8ba8?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=130&ixlib=rb1.2.1&q=80&w=130"/>
<div class="customLightbox" id="picture">
<img class="animation2" src="https://images.unsplash.com/photo-1611460116297-
586f43de8ba8?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=630&ixlib=rb1.2.1&q=80&w=630"/>
</div>
<div id="lightbox-controls" >
<a id="close-lightbox" class="animation2" href="#">Close Lightbox</a>
</div>
</div>
</body>
</html>
This will produce the following result −
Changing the Mouse Cursor in Tkinter

Tkinter is a GUI-based Python library which is used to develop various types of functional and GUI-based applications. It provides lots of functions and methods that can be used to provide extensibility and various features while developing an application.
In this article, we will see how we can change the mouse cursor while hovering on a button in the tkinter frame using the cursor property. There are plenty of cursor maps available in tkinter’s button library that provide different visuals for the end-user. Some of the cursor in the library are,
"arrow"
"circle"
"clock"
"cross"
"dotbox"
"exchange"
"fleur"
"heart"
"heart"
"man"
"mouse"
"pirate"
"plus"
"shuttle"
"sizing"
"spider"
"spraycan"
"star"
"target"
"tcross"
"trek"
"watch"
Let us first create some buttons and then we will apply some of these cursors on the mouse pointer.
from tkinter import *
#Create an instance of window or frame
win= Tk()
#Set the geometry
win.geometry("700x600")
win.resizable(0,0)
win.config(cursor= "fleur")
#Let us create a text label
Label(win, text= "Hover on each of these buttons", font=('Poppins', 20)).pack(pady=20)

#Create some buttons with cursor property
b1= Button(win, text= "Star",cursor="star")
b1.pack(pady=20)
b2= Button(win, text= "Arrow",cursor="arrow")
b2.pack(pady=20)
b3= Button(win, text= "Circle",cursor="circle")
b3.pack(pady=20)
b4= Button(win, text= "Clock",cursor="clock")
b4.pack(pady=20)
b5= Button(win, text= "Heart",cursor="heart")
b5.pack(pady=20)
b6= Button(win, text= "Man",cursor="man")
b6.pack(pady=20)
b7= Button(win, text= "Mouse",cursor="mouse")
b7.pack(pady=20)

#Keep Running the window

win.mainloop()
Running the above code will create different buttons with different mouse pointer shapes.
time.Time.UnixNano() Function in Golang with Examples - GeeksforGeeks

24 Aug, 2021
In Go language, time packages supply functionality for determining as well as viewing time. The Time.UnixNano() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn’t rely upon the location connected with t. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. 
Syntax: 
func (t Time) UnixNano() int64
Here, “t” is the stated time.Note: Here, the output returned is not defined if the given Unix time in nanoseconds is not formed by an int64 type(which is a date before the year 1678 or after the year 2262). This implies that the result of calling the UnixNano() method on the zero Time is ambiguous.Return value: It returns “t” as a Unix time which is of type int64. 
Example 1:
Go
// Golang program to illustrate the usage of// Time.UnixNano() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() {     // Defining t in UTC    // for UnixNano method    t := time.Date(2019, 13, 15, 23,               90, 12, 04, time.UTC)     // Calling UnixNano method    unixnano := t.UnixNano()     // Prints output    fmt.Printf("%v\n", unixnano)}
Output: 
1579134612000000004
Example 2:
Go
// Golang program to illustrate the usage of// Time.UnixNano() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() {     // Defining t in UTC    // for UnixNano method    t := time.Date(2001, 13, 15, 2e3,           1e1, 12e2, 04e1, time.UTC)     // Calling UnixNano method    unixnano := t.UnixNano()     // Prints output    fmt.Printf("%v\n", unixnano)}
Output: 
input
1018254600000000040
Here, the time “t” stated in the above code has values which contain constant “e” but they are converted in usual range while conversion.
f20171220
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
How to Split a String in Golang?
Arrays in Go
Golang Maps
Slices in Golang
How to convert a string in lower case in Golang?
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
Python | TextBlob.correct() method

13 Apr, 2022
With the help of TextBlob.correct() method, we can get the corrected words if any sentence have spelling mistakes by using TextBlob.correct() method.
Syntax : TextBlob.correct() Return : Return the correct sentence without spelling mistakes.  
Example #1 : In this example, we can say that by using TextBlob.correct() method, we are able to get the correct sentence without any spelling mistakes.
Python3
# import TextBlobfrom textblob import TextBlob gfg = TextBlob("GFG is a good compny and alays value ttheir employes.") # using TextBlob.correct() methodgfg = gfg.correct() print(gfg)
Output:
GFG is a good company and always value their employed. 
Example #2:
Python3
# import TextBlobfrom textblob import TextBlob gfg = TextBlob("I amm goodd at spelling mstake.") # using TextBlob.correct() methodgfg = gfg.correct() print(gfg)
Output :
I am good at spelling mistake. 
abhishek0719kadiyan
varshagumber28
rkbhola5
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Find positions of Matching Elements between Vectors in R Programming – match() Function

15 Jun, 2020
match() function in R Language is used to return the positions of the first match of the elements of the first vector in the second vector. If the element is not found, it returns NA.
Syntax: match(x1, x2, nomatch)
Parameters:x1: Vector 1x2: Vector 2nomatch: value to be returned in case of no match
Example 1:
# R program to match the vectors  # Creating vectorsx1 <- c("a", "b", "c", "d", "e")x2 <- c("d", "f", "g", "a", "e", "k")  # Calling match functionmatch(x1, x2)
Output:
[1]  4 NA NA  1  5

Example 2:
# R program to match the vectors  # Creating vectorsx1 <- c("a", "b", "c", "d", "e")x2 <- c("d", "f", "g", "a", "e", "k")  # Calling match functionmatch(x1, x2, nomatch = "-1")
Output:
[1]  4 -1 -1  1  5

R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Python | Splitting Text and Number in string

01 Jul, 2019
Sometimes, we have a string, which is composed of text and number (or vice-versa), without any specific distinction between the two. There might be a requirement in which we require to separate the text from the number. Let’s discuss certain ways in which this can be performed.
Method #1 : Using re.compile() + re.match() + re.groups()The combination of all the above regex functions can be used to perform this particular task. In this we compile a regex and match it to group text and numbers separately into a tuple.
# Python3 code to demonstrate working of# Splitting text and number in string # Using re.compile() + re.match() + re.groups()import re  # initializing string test_str = "Geeks4321"  # printing original string print("The original string is : " + str(test_str))  # Using re.compile() + re.match() + re.groups()# Splitting text and number in string temp = re.compile("([a-zA-Z]+)([0-9]+)")res = temp.match(test_str).groups()  # printing result print("The tuple after the split of string and number : " + str(res))
The original string is : Geeks4321
The tuple after the split of string and number : ('Geeks', '4321')

 
Method #2 : Using re.findall()The slight modification of regex can provide the flexibility to reduce the number of regex functions required to perform this particular task. The findall function is alone enough for this task.
# Python3 code to demonstrate working of# Splitting text and number in string # Using re.findall()import re  # initializing string test_str = "Geeks4321"  # printing original string print("The original string is : " + str(test_str))  # Using re.findall()# Splitting text and number in string res = [re.findall(r'(\w+?)(\d+)', test_str)[0] ]  # printing result print("The tuple after the split of string and number : " + str(res))
The original string is : Geeks4321
The tuple after the split of string and number : ('Geeks', '4321')

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program for Binary Search (Recursive and Iterative)

13 Jun, 2022
We basically ignore half of the elements just after one comparison.
Compare x with the middle element.If x matches with middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.Else (x is smaller) recur for the left half.
Compare x with the middle element.
If x matches with middle element, we return the mid index.
Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.
Else (x is smaller) recur for the left half.
Recursive :
C
#include <stdio.h>// A recursive binary search function. It returns location of x in// given array arr[l..r] is present, otherwise -1int binarySearch(int arr[], int l, int r, int x){if (r >= l){int mid = l + (r - l)/2;// If the element is present at the middle itselfif (arr[mid] == x) return mid;// If element is smaller than mid, then it can only be present// in left subarrayif (arr[mid] > x) return binarySearch(arr, l, mid-1, x);// Else the element can only be present in right subarrayreturn binarySearch(arr, mid+1, r, x);}// We reach here when element is not present in arrayreturn -1;}int main(void){int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = binarySearch(arr, 0, n-1, x);(result == -1)? printf("Element is not present in array"): printf("Element is present at index %d", result);return 0;}
Time Complexity: O(log n)
Auxiliary Space: O(1) 
Iterative
C/C++
C
#include <stdio.h>// A iterative binary search function. It returns location of x in// given array arr[l..r] if present, otherwise -1int binarySearch(int arr[], int l, int r, int x){while (l <= r){int m = l + (r-l)/2;// Check if x is present at midif (arr[m] == x)return m;// If x greater, ignore left halfif (arr[m] < x)l = m + 1;// If x is smaller, ignore right halfelser = m - 1;}// if we reach here, then element was not presentreturn -1;}int main(void){int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = binarySearch(arr, 0, n-1, x);(result == -1)? printf("Element is not present in array"): printf("Element is present at index %d", result);return 0;}
Time Complexity: O(log n)
Auxiliary Space: O(1) 
Please refer complete article on Binary Search for more details!
chandramauliguptach
Binary Search
C Programs
Searching
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert an element at a specific position in an Array in C++

21 Jun, 2022
An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C++. Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.  Approach: Here’s how to do it.
First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posThen shift the array elements from this position to one position forward, and do this for all the other elements next to pos.Insert the element x now at the position pos, as this is now empty.
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos.
Insert the element x now at the position pos, as this is now empty.
Below is the implementation of the above approach: 
CPP
// C++ Program to Insert an element// at a specific position in an Array #include <iostream>using namespace std; // Function to insert x in arr at position posint* insertX(int n, int arr[],            int x, int pos){    int i;     // increase the size by 1    n++;     // shift elements forward    for (i = n; i >= pos; i--)        arr[i] = arr[i - 1];     // insert x at pos    arr[pos - 1] = x;     return arr;} // Driver Codeint main(){    int arr[100] = { 0 };    int i, x, pos, n = 10;     // initial array of size 10    for (i = 0; i < 10; i++)        arr[i] = i + 1;     // print the original array    for (i = 0; i < n; i++)        cout << arr[i] << " ";    cout << endl;     // element to be inserted    x = 50;     // position at which element is to be inserted    pos = 5;     // Insert x at pos    insertX(n, arr, x, pos);     // print the updated array    for (i = 0; i < n + 1; i++)        cout << arr[i] << " ";    cout << endl;     return 0;}
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 50 5 6 7 8 9 10
Time Complexity: O(n)
Auxiliary Space: O(1)
harshmaster07705
cpp-array
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.