code-rag-bench/online-tutorials huggingface dataset:
Access the last value of a given vector in R - GeeksforGeeks

07 Apr, 2021
In this article, we will discuss how to access the last value of a given vector in R Programming Language. So let’s begin by first creating an example vector because to get the last value of a vector we need to first create the vector.
R
vec1 <- c("John" , "Smith", "Tina" , "Brad" , "Emma")print(vec1)
Output:
 "John"  "Smith" "Tina"  "Brad"  "Emma" 
Our first vector is a character string with some names, now we have to extract the last name from this vector.
To do this task we can use the length() function from the R Language. This not only enables to find out the length of the string but also access to the elements.
Syntax: length(x)
Parameter:  x: vector
Example:
R
vec1 <- c("John" , "Smith", "Tina" , "Brad" , "Emma")length(vec1)
Output:
[1] 5
Now, let’s use length() function to get the last element of the vector:
R
vec1 <- c("John" , "Smith", "Tina" , "Brad" , "Emma")length(vec1)  # To Extract last element with lengthvec1[length(vec1)]
Output:
[1] 5
[1] "Emma"
To find the last element of the vector we can also use tail() function.
Again to demonstrate it let’s first create an example vector.
R
vec2 <- c(123 , 124 , 125 , 126, 128)print(vec2)
Output:
123 124 125 126 128
W have an example vector, and we have to access its last element.
Syntax: tail()
Parameters: 
x: data frame
n: number of rows to be displayed
Here we are passing n=1 so that it will display only the last element in the vector.
R
vec2 <- c(123 , 124 , 125 , 126)tail(vec2 , 1)
Output:
126
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
How to use Boto3 to get a list of all secrets in AWS Secret Manager

Problem Statement: Use boto3 library in Python to get a list of all secrets in AWS Secret Manager
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2: There are no parameters here.
Step 2: There are no parameters here.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4: Create an AWS client for secretmanager.
Step 4: Create an AWS client for secretmanager.
Step 5: Call list_secrets function to retrieve all secrets.
Step 5: Call list_secrets function to retrieve all secrets.
Step 6: It returns the metadata of all secrets.
Step 6: It returns the metadata of all secrets.
Step 7: Handle the generic exception if something went wrong while getting details of all secrets.
Step 7: Handle the generic exception if something went wrong while getting details of all secrets.
Use the following code to get the list of all secrets in AWS Secret Manager −
import boto3
from botocore.exceptions import ClientError

def get_all_secrets():
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   try:
   response = s3_client.list_secrets()
   return response
   except ClientError as e:
      raise Exception("boto3 client error in get_all_secrets: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in get_all_secrets: " + e.__str__())

a = get_all_secrets()
for details in a['SecretList']:
print(details['Name'])
tests/secrets
tests/aws/secrets
tests/aws/users
How To Adjust Position of Axis Labels in Matplotlib? - GeeksforGeeks

11 Dec, 2020
In this article, we will see how to adjust positions of the x-axis and y-axis labels in Matplotlib which is a library for plotting in python language. By default, these labels are placed in the middle, but we can alter these positions using the “loc” parameter in set_xlabel and set_ylabel function of matplotlib. 
Note: “loc” parameter is only available in Matplotlib version 3.3.0 onwards.
Let’s understand with step wise:
Step 1:
First, let’s import all the required libraries.
Python3
import matplotlib.pyplot as pltimport numpy as np
Step 2:
Now we will create fake data using the NumPy library. Here we are using the sample sub-module from the random module to create a dataset of random values.
Python3
from random import sampledata = sample(range(1, 1000), 100)
Step 3:
Now we have created data let’s plot this data using the default options of matplotlib and then start experimenting with its positions. We can clearly see that these labels are in the center by default. The bins parameter tells you the number of bins that your data will be divided into. Matplotlib allows you to adjust the transparency of a graph plot using the alpha attribute. By default, alpha=1 
Python3
fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel("X-Label" , fontsize = 16)ax.set_ylabel("Y-label" , fontsize = 16)
Output:
The default position of labels
Here we will move the y-label to the bottom and x-label to the extreme right using the loc parameter.
Python3
fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel("X-Label",              fontsize = 16, loc = "right")  ax.set_ylabel("Y-Label",               fontsize = 16, loc = "bottom")
Output:
Y-label to the bottom and X-label to extreme right
Let’s take another example here we will move the y-label to the top.
Python3
fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel("X-Label",               fontsize = 16, loc = "right")  ax.set_ylabel("Y-Label",               fontsize = 16, loc = "top")
Output:
Y-label to the top and X-label to extreme right
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to set the space between cells in a table with JavaScript?

To set the space between cells in a table with JavaScript, use the borderSpacing property. Set the spacing using this property.
You can try to run the following code to learn how to set the space between table cells −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <table id="newTable" border="2">
         <tr>
            <th>EmpID</th>
            <th>EmpName</th>
            <th>EmpDept</th>
         </tr>
         <tr>
            <td>001</td>
            <td>Amit</td>
            <td>IT</td>
         </tr>
         <tr>
            <td>002</td>
            <td>John</td>
            <td>Finance</td>
         </tr>
         <tr>
             <td>003</td>
             <td>David</td>
             <td>Marketing</td>
         </tr>
      </table>
      <br>
      <button onclick="display()">Click to set space between cells</button>
      <script>
         function display() {
            document.getElementById("newTable").style.borderSpacing = "15px";
         }
      </script>
   </body>
</html>
How to create a child window and communicate with parents in Tkinter?

Unlike other Python libraries, Tkinter has many features that are used to create a full-fledged application. It supports multiple window operations and threading for processing the operation on Windows.
Following the thread, we will create an application that will pull the data from root window and put it into a child window. The concept of child window can be referred to as Dialog Boxes which present some information to the user during the happening of an event. The child window in Tkinter is created very easily by using Toplevel(root) constructor.
In this example, we will create an entry widget along with a button in the main window. Further, the data stored in the entry widget will be pulled by a button that displays the input value in a new window or child window.
#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
win.title("Main Window")
#Define a function to Open a new window
def open_win():
   child_win= Toplevel(win)
   child_win.title("Child Window")
   child_win.geometry("750x250")
   content= entry.get()
   Label(child_win, text=content, font=('Bell MT', 20, 'bold')).pack()
   win.withdraw()
#Create an Entry Widget
entry=ttk.Entry(win, width= 40)
entry.pack(ipady=4,pady=20)
#Let us create a button in the Main window
button= ttk.Button(win, text="OK",command=open_win)
button.pack(pady=20)
win.mainloop()
When we execute the above code, it will show a window with an entry widget and a button to open a new window.
Write something in the entry widget and click the OK button,
How to wrap the text within the width of the window in JavaFX?

In JavaFX, the text node is represented by the Javafx.scene.text.Text class. To
insert/display text in JavaFx window you need to −
Instantiate the Text class.
Instantiate the Text class.
Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor.
Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor.
Add the created node to the Group object.
Add the created node to the Group object.
If the length of the lines in the text you have passed, longer than the width of the window part of the text will be chopped as shown below −
As a solution you can wrap the text within the width of the window by setting the value to the property wrapping with, using the setWrappingWidth() method.
This method accepts a double value representing the width (in pixels) of the text. If you pass a value that is less than the width of the window, the text will be wrapped within it(the given width).
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class WrappingTheText extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Reading the contents of a text file.
      InputStream inputStream = new FileInputStream("D:\\sample.txt");
      Scanner sc = new Scanner(inputStream);
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine()+"\n");
      }
      //Creating a text object
      Text text = new Text(10.0, 25.0, sb.toString());
      //Wrapping the text
      text.setWrappingWidth(590);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Wrapping The Text");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Assume following are the contents of the sample.txt file −
JavaFX is a Java library used to build Rich Internet Applications. The applications written 
using this library can run consistently across multiple platforms. The applications developed 
using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..
To develop GUI Applications using Java programming language, the programmers rely on libraries 
such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers 
can now develop GUI applications effectively with rich content.
Font Name: Brush Script MT
Python 3 - Number round() Method

Following is the syntax for the round() method −
round( x [, n]  )

x − This is a numeric expression.
n − Represents number of digits from decimal point up to which x is to be rounded. Default is 0.
This method returns x rounded to n digits from the decimal point.
The following example shows the usage of round() method.
#!/usr/bin/python3

print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))
When we run the above program, it produces the following result −
round(70.23456) :  70
round(56.659,1) :  56.7
round(80.264, 2) :  80.26
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0


    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 load a hyperlink from one iframe to another iframe ? - GeeksforGeeks

25 Jul, 2021
HTML Iframe or inline frame allows embedment of multiple HTML pages in an HTML page. In this article, we will see how to change the content of one iframe using hyperlinks in another iframe. 
This can be achieved by the proper usage of the name attribute in the iframe tag and the target attribute in the anchor tag. The name attribute allows each inline frame to have its own unique name while the target attribute tells the hyperlinks, where the page has to be opened when the link is clicked. Our problem will be solved if we keep the value of the target as the name of the destination iframe where the hyperlink contents should be displayed.
We will create an HTML page consisting of two iframes.
Give each iframe a unique name.
Create another HTML page with multiple hyperlinks in it.
Add the name of the second iframe in the target attribute of every hyperlink.
Click the links in the first iframe, and you should see the pages opening in the second iframe.
Example: The HTML document will embed two iframes inside it.
index.html
<!DOCTYPE html><html>  <body>    <center>      <h2>Hello world!!</h2>      <br />      <iframe src="iframe1.html"               name="iframe1"               width="70%"               height="250">      </iframe>      <br /><br />      <iframe src=""               name="iframe2"               width="70%" height="300">      </iframe>    </center>  </body></html>
The following code is the content for “iframe1.html” used in the above code.
iframe1.html
<!DOCTYPE html><html>  <body>    <center>      <h1 style="color: green">GeeksforGeeks</h1>        <p>        <a href="https://media.geeksforgeeks.org/wp-content/uploads/20210720232031/gfglogo-300x300.png"          target="iframe2">GfG Logo</a>      </p>        <p>        <a href="https://media.geeksforgeeks.org/wp-content/uploads/20210720234436/gfglogo2-300x300.jpg"          target="iframe2">GfG Logo 2</a>      </p>        <p>        <a href="https://www.youtube.com/embed/sa9l-dTv9Gk" target="iframe2">          GfG youtube video        </a>      </p>        <p>click the above links to see changes in the frame below</p>    </center>  </body></html>
Output: This page will contain hyperlinks, each targeting the second iframe.
iframe to another iframe
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
C# String CopyTo() Method

The CopyTo() method in C# is used to copy a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.
public void CopyTo (int srcIndex, char[] dest, int desIndex, int count);
Above,
srcIndex − Index of the first character in this instance to copy.
dest − Array of Unicode characters to which characters in this instance are copied.
destIndex − The index in destination at which the copy operation begins.
Count − Number of characters in this instance to copy to destination.
Let us now see an example -
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string str = "JohnAndJacob";
      Console.WriteLine("String = "+str);
      char[] destArr = new char[20];
      str.CopyTo(1, destArr, 0, 4);
      Console.Write(destArr);
   }
}
String = JohnAndJacob
ohnA
Let us now see another example -
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string str = "JohnAndJacob";
      Console.WriteLine("String = "+str);
      char[] destArr = new char[20];
      destArr[0] = 'A';
      destArr[1] = 'B';
      destArr[2] = 'C';
      destArr[3] = 'D';
      Console.WriteLine(destArr);
      str.CopyTo(2, destArr, 3, 4);
      Console.Write(destArr);
   }
}
This will produce the following output -
String = JohnAndJacob
ABCD
ABChnAn
Java Examples - String Reverse

How to reverse a String?
Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method.
public class StringReverseExample{
   public static void main(String[] args) {
      String string = "abcdef";
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("\nString before reverse: "+string);
      System.out.println("String after reverse: "+reverse);
   }
}
The above code sample will produce the following result.
String before reverse:abcdef
String after reverse:fedcba

Following another example shows how to reverse a String after taking it from command line argument
import java.io.*;
import java.util.*;

public class HelloWorld {
   public static void main(String[] args) {
      String input = "tutorialspoint";
      char[] try1 = input.toCharArray();
      for (int i = try1.length-1;i >= 0; i--) System.out.print(try1[i]);
   }
}
The above code sample will produce the following result.
tniopslairotut 

 Print
 Add Notes
 Bookmark this page
AtomicInteger updateAndGet() method in Java with Examples - GeeksforGeeks

17 Jun, 2019
The Java.AtomicInteger.updateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value. It takes an object of IntUnaryOperator interface as its parameter and applies the operation specified in the object to the current value. It returns the updated value.
Syntax:
public final int updateAndGet(IntUnaryOperator function)

Parameters: This method accepts as parameter an IntUnaryOperator function.It applies the given function to the current value of the object.
Return Value: The function returns the updated value of the current object.
Example to demonstrate the function.
Program 1:
// Java program to demonstrate the above function  import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntUnaryOperator;  public class Demo {    public static void main(String[] args)    {          // Atomic Integer initialized with a value of 10        AtomicInteger ai = new AtomicInteger(10);          // Unary operator defined to negate the value        IntUnaryOperator unaryOperator = (x) -> - x;          System.out.println("Initial Value is " + ai);          // Function called and the unary operator        // is passed as an argument        int x = ai.updateAndGet(unaryOperator);        System.out.println("Updated value is " + x);    }}
Initial Value is 10
Updated value is -10

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
Java-AtomicInteger
Java-Functions
Java-util-concurrent-atomic package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
Set in Java
How can we extract a substring from the value of a column in MySQL table?

We can apply any of the functions like SUBSTRING(), MID() or SUBSTR() to extract a substring from the value of a column. In this case, we must have to provide the name of the column as the first argument of the function i.e. at the place of string we have to give the name of the column. Following example will demonstrate it.
Suppose we want to extract a substring from the ‘Name’ column of ‘Student’ table then it can be done by using the different functions as follows −
mysql> Select name, SUBSTR(name,2,4) from student;
+---------+------------------+
| name    | SUBSTR(name,2,4) |
+---------+------------------+
| Gaurav  | aura             |
| Aarav   | arav             |
| Harshit | arsh             |
| Gaurav  | aura             |
| Yashraj | ashr             |
+---------+------------------+
5 rows in set (0.00 sec)

mysql> Select name, MID(name,2,4) from student;
+---------+---------------+
| name    | MID(name,2,4) |
+---------+---------------+
| Gaurav  | aura          |
| Aarav   | arav          |
| Harshit | arsh          |
| Gaurav  | aura          |
| Yashraj | ashr          |
+---------+---------------+
5 rows in set (0.00 sec)

mysql> Select name, substring(name,2,4) from student;
+---------+---------------------+
| name    | substring(name,2,4) |
+---------+---------------------+
| Gaurav  | aura                |
| Aarav   | arav                |
| Harshit | arsh                |
| Gaurav  | aura                |
| Yashraj | ashr                |
+---------+---------------------+
5 rows in set (0.00 sec)
We can also apply condition/s in the above queries as follows −
mysql> Select name, substring(name,2,4) from student WHERE address = 'delhi';
+---------+---------------------+
| name    | substring(name,2,4) |
+---------+---------------------+
| Gaurav  | aura                |
| Harshit | arsh                |
+---------+---------------------+
2 rows in set (0.16 sec)

mysql> Select name, MID(name,2,4) from student WHERE address = 'delhi';
+---------+---------------+
| name    | MID(name,2,4) |
+---------+---------------+
| Gaurav  | aura          |
| Harshit | arsh          |
+---------+---------------+
2 rows in set (0.00 sec)

mysql> Select name, SUBSTR(name,2,4) from student WHERE address = 'delhi';
+---------+------------------+
| name    | SUBSTR(name,2,4) |
+---------+------------------+
| Gaurav  | aura             |
| Harshit | arsh             |
+---------+------------------+
2 rows in set (0.00 sec)
Relational Set Operators in DBMS

DBMS supports relational set operators as well. The major relational set operators are union, intersection and set difference. All of these can be implemented in DBMS using different queries.
The relational set operators in detail using given example are as follows as follows −
Union combines two different results obtained by a query into a single result in the form of a table. However, the results should be similar if union is to be applied on them. Union removes all duplicates, if any from the data and only displays distinct values. If duplicate values are required in the resultant data, then UNION ALL is used.
An example of union is −
Select Student_Name from Art_Students
UNION
Select Student_Name from Dance_Students
This will display the names of all the students in the table Art_Students and Dance_Students i.e John, Mary, Damon and Matt.
The intersection operator gives the common data values between the two data sets that are intersected. The two data sets that are intersected should be similar for the intersection operator to work. Intersection also removes all duplicates before displaying the result.
An example of intersection is −
Select Student_Name from Art_Students
INTERSECT
Select Student_Name from Dance_Students
This will display the names of the students in the table Art_Students and in the table Dance_Students i.e all the students that have taken both art and dance classes .Those are Mary and Damon in this example.
The set difference operators takes the two sets and returns the values that are in the first set but not the second set.
An example of set difference is −
Select Student_Name from Art_Students
MINUS
Select Student_Name from Dance_Students
This will display the names of all the students in table Art_Students but not in table Dance_Students i.e the students who are taking art classes but not dance classes.
That is John in this example.
Convert a string to hexadecimal ASCII values in C++

In this tutorial, we will be discussing a program to convert a string to hexadecimal ASCII values.
For this we will be provided with a string of characters. Our task is to print that particular given string into its hexadecimal equivalent.
 Live Demo
#include <stdio.h>
#include <string.h>
//converting string to hexadecimal
void convert_hexa(char* input, char* output){
   int loop=0;
   int i=0;
   while(input[loop] != '\0'){
      sprintf((char*)(output+i),"%02X", input[loop]);
      loop+=1;
      i+=2;
   }
   //marking the end of the string
   output[i++] = '\0';
}
int main(){
   char ascii_str[] = "tutorials point";
   int len = strlen(ascii_str);
   char hex_str[(len*2)+1];
   //function call
   convert_hexa(ascii_str, hex_str);
   printf("ASCII: %s\n", ascii_str);
   printf("Hexadecimal: %s\n", hex_str);
   return 0;
}
ASCII: tutorials point
Hexadecimal: 7475746F7269616C7320706F696E74
Automated software testing with Python

In this tutorial, we are going to learn about automating testing in Python. After writing code, we have to test them by giving different types of input and check whether the code is working correctly or not.
We can do it manually or automatically. Doing manual testing is very hard. So, we are going to learn about automated testing in Python. Let's start.
We have a module called unittest, which is used to test the code automatically. We are going to work with this module in this tutorial. It's straightforward for a beginner to get started with the unittest module for testing. Let's start the coding with basics.
The method which you have to test must start with the test text.
# importing unittest module
import unittest
class SampleTest(unittest.TestCase):
   # return True or False
   def test(self):
      self.assertTrue(True)
# running the test
unittest.main()
If you run the above program, you will get the following results.
Ran 1 test in 0.001s
OK
Now, we are going to test different string methods with sample test cases. Remember that the method name must start with a test.
# importing unittest module
import unittest
class TestingStringMethods(unittest.TestCase):
   # string equal
   def test_string_equality(self):
      # if both arguments are then it's succes
      self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')
   # comparing the two strings
   def test_string_case(self):
      # if both arguments are then it's succes
      self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')
   # checking whether a string is upper or not
   def test_is_string_upper(self):
      # used to check whether the statement is True or False
      self.assertTrue('TUTORIALSPOINT'.isupper())
      self.assertFalse('TUTORIALSpoint'.isupper())
# running the tests
unittest.main()
If you run the above program, you will get the following results.
Ran 3 tests in 0.001s
OK
You can use the testing in your programs to save a lot of time. If you have any doubts in the tutorial, mention them in the comment section.
Order randomly in MySQL with a random value column?

Let us first create a table. After that we will create a new random value column and order the
record randomly:
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20)
);
Query OK, 0 rows affected (0.57 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable(StudentName) values('Larry');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.14 sec)
Following is the query to display records from the table using select statement:
mysql> select *from DemoTable;
This will produce the following output
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Larry       |
|         2 | Sam         |
|         3 | Mike        |
|         4 | Carol       |
|         5 | Robert      |
|         6 | Chris       |   
+-----------+-------------+
6 rows in set (0.00 sec)
Here is the query to order by random fields. We have created a new random field here:
mysql> SELECT *
FROM (SELECT StudentName, RAND()+1 AS randomRecord
FROM DemoTable
) tbl
ORDER BY RandomRecord DESC;
This will produce the following output
+-------------+--------------------+
| StudentName | RandomRecord       |
+-------------+--------------------+
| Carol       | 1.8973721451101566 |
| Chris       | 1.7821308670399065 |
| Mike        | 1.4640037673190271 |
| Larry       | 1.4134691557041081 |
| Sam         | 1.1408822407395414 |
| Robert      | 1.0948494543273461 |
+-------------+--------------------+
6 rows in set (0.00 sec)
Pull an element in sub of sub-array in MongoDB?

To pull an element, use $pull along with $(positional) operator. Let us create a collection with documents −
> db.demo679.insertOne(
...    {
...       id:1,
...       "details": [
...          {
...             CountryName:"US",
...             "information": [
...
...                { "Name": "Chris", "FirstName": "Name=Chris" },
...
...                {"Name": "Bob", "FirstName": "Name=Bob" }
...             ]
...          },
...          {
...             CountryName:"UK",
...             "information": [
...
...                { "Name": "Robert", "FirstName": "Name=Robert" },
...
...                {"Name": "Sam", "FirstName": "Name=Sam" }
...             ]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea442cf04263e90dac943fd")
}
Display all documents from a collection with the help of find() method −
> db.demo679.find();
This will produce the following output −
{ "_id" : ObjectId("5ea442cf04263e90dac943fd"), "id" : 1, "details" : [
   { "CountryName" : "US", "information" :  [
      { "Name" : "Chris", "FirstName" : "Name=Chris" },
      { "Name" : "Bob", "FirstName" : "Name=Bob" }
   ] },
   { "CountryName" : "UK", "information" : [
      { "Name" : "Robert", "FirstName" : "Name=Robert" },
      { "Name" : "Sam", "FirstName" : "Name=Sam" }
   ] } 
] }
Following is the query to pull an element in sub of sub-array in MongoDB −
> db.demo679.update(
...    { "details.CountryName":"US" },
...    { $pull: { 'details.$.information': { "Name" : "Bob", "FirstName" : "Name=Bob" } } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo679.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ea442cf04263e90dac943fd"),
   "id" : 1,
   "details" : [
      {
         "CountryName" : "US",
         "information" : [
            {
               "Name" : "Chris",
               "FirstName" : "Name=Chris"
            }
         ]
      },
      {
         "CountryName" : "UK",
         "information" : [
            {
               "Name" : "Robert",
               "FirstName" : "Name=Robert"
            },
            {
               "Name" : "Sam",
               "FirstName" : "Name=Sam"
            }
         ]
      }
   ]
}
How to add background music to your web page?

To add background music on a web page, use <embed>...</embed> element. Also, use the autoplay attribute. This will run music in the background whenever the page loads.
Set the width and height in a way the player hides on the web page. The loop attribute is added to specify whether the audio will start over again. Add the music file to the server and mention the link in src attribute.
You can try to run the following code to add background music to your web page:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML background music</title>
   </head>
   <body>
      <p>The music is running in the background.</p>
      <p>(Song: Kalimba which is provided as a Sample Music in Windows)</p>
      <embed src="/html/Kalimba.mp3" loop="true" autostart="true" width="2" height="0">
   </body>
</html>
Kotlin - Sealed Class

In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class.
sealed class MyExample {
   class OP1 : MyExample() // MyExmaple class can be of two types only
   class OP2 : MyExample()
}
fun main(args: Array<String>) {
   val obj: MyExample = MyExample.OP2() 
   
   val output = when (obj) { // defining the object of the class depending on the inuputs 
      is MyExample.OP1 -> "Option One has been chosen"
      is MyExample.OP2 -> "option Two has been chosen"
   }
   
   println(output)
}
In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output.
In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser.
option Two has been chosen


    68 Lectures 
     4.5 hours 

 Arnab Chakraborty

    71 Lectures 
     5.5 hours 

 Frahaan Hussain

    18 Lectures 
     1.5 hours 

 Mahmoud Ramadan

    49 Lectures 
     6 hours 

 Catalin Stefan

    49 Lectures 
     2.5 hours 

 Skillbakerystudios

    22 Lectures 
     1 hours 

 CLEMENT OCHIENG
 Print
 Add Notes
 Bookmark this page
Python - Case Insensitive string counter - GeeksforGeeks

02 Sep, 2020
Given a List of Strings, find frequency of strings case insensitive.
Input : test_list = [“Gfg”, “Best”, “GFG”, “is”, “IS”, “BEST”]Output : {‘gfg’: 2, ‘best’: 2, ‘is’: 2}Explanation : All occur twice.
Input : test_list = [“Gfg”, “gfg”, “GFG”]Output : {‘gfg’: 3}Explanation : Only “gfg” 3 occurrences.
Method : Using defaultdict() + lower()
In this, we perform lower() to all the strings, before mapping in defaultdict. This ensures case insensitivity while mapping and cumulating frequency.
Python3
# Python3 code to demonstrate working of # Strings Frequency (Case Insensitive)# Using defaultdict() + lower()from collections import defaultdict  # initializing listtest_list = ["Gfg", "Best", "best", "gfg", "GFG", "is", "IS", "BEST"]  # printing original listprint("The original list is : " + str(test_list))  res = defaultdict(int)for ele in test_list:          # lowercasing to cater for Case Insensitivity    res[ele.lower()] += 1  # printing result print("Strings Frequency : " + str(dict(res)))
The original list is : ['Gfg', 'Best', 'best', 'gfg', 'GFG', 'is', 'IS', 'BEST']
Strings Frequency : {'gfg': 3, 'best': 3, 'is': 2}

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
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Binary Search (Recursive and Iterative)
Python | Split string into list of characters
Objective-C Extensions

A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension).
The methods declared by a class extension are implemented in the implementation block for the original class, so you can't, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.
Extensions are actually categories without the category name. It's often referred as anonymous categories.
The syntax to declare a extension uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it just adds parentheses, as shown below −
@interface ClassName ()

@end
An extension cannot be declared for any class, only for the classes that we have original implementation of source code.
An extension cannot be declared for any class, only for the classes that we have original implementation of source code.
An extension is adding private methods and private variables that are only specific to the class.
An extension is adding private methods and private variables that are only specific to the class.
Any method or variable declared inside the extensions is not accessible even to the inherited classes.
Any method or variable declared inside the extensions is not accessible even to the inherited classes.
Let's create a class SampleClass that has an extension. In the extension, let's have a private variable internalID.
Then, let's have a method getExternalID that returns the externalID after processing the internalID.
The example is shown below and this wont work on online compiler.
#import <Foundation/Foundation.h>

@interface SampleClass : NSObject {
   NSString *name;
}

- (void)setInternalID;
- (NSString *)getExternalID;

@end

@interface SampleClass() {
   NSString *internalID;
}

@end

@implementation SampleClass

- (void)setInternalID {
   internalID = [NSString stringWithFormat: 
   @"UNIQUEINTERNALKEY%dUNIQUEINTERNALKEY",arc4random()%100];
}

- (NSString *)getExternalID {
   return [internalID stringByReplacingOccurrencesOfString: 
   @"UNIQUEINTERNALKEY" withString:@""];
}

@end

int main(int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass setInternalID];
   NSLog(@"ExternalID: %@",[sampleClass getExternalID]);        
   [pool drain];
   return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-22 21:18:31.754 Extensions[331:303] ExternalID: 51

In the above example, we can see that the internalID is not returned directly. We here remove the UNIQUEINTERNALKEY and only make the remaining value available to the method getExternalID.
The above example just uses a string operation, but it can have many features like encryption/decryption and so on.

    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Design Patterns - State Pattern

In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.
We are going to create a State interface defining an action and concrete state classes implementing the State interface. Context is a class which carries a State.
StatePatternDemo, our demo class, will use Context and state objects to demonstrate change in Context behavior  based on type of state it is in.
Create an interface.
State.java
public interface State {
   public void doAction(Context context);
}
Create concrete classes implementing the same interface.
StartState.java
public class StartState implements State {

   public void doAction(Context context) {
      System.out.println("Player is in start state");
      context.setState(this);	
   }

   public String toString(){
      return "Start State";
   }
}
StopState.java
public class StopState implements State {

   public void doAction(Context context) {
      System.out.println("Player is in stop state");
      context.setState(this);	
   }

   public String toString(){
      return "Stop State";
   }
}
Create Context Class.
Context.java
public class Context {
   private State state;

   public Context(){
      state = null;
   }

   public void setState(State state){
      this.state = state;		
   }

   public State getState(){
      return state;
   }
}
Use the Context to see change in behaviour when State changes.
StatePatternDemo.java
public class StatePatternDemo {
   public static void main(String[] args) {
      Context context = new Context();

      StartState startState = new StartState();
      startState.doAction(context);

      System.out.println(context.getState().toString());

      StopState stopState = new StopState();
      stopState.doAction(context);

      System.out.println(context.getState().toString());
   }
}
Verify the output.
Player is in start state
Start State
Player is in stop state
Stop State


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Python – Incremental List Extension

27 Dec, 2019
Sometimes, while working with Python list, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat contents of list and while doing that, each time new list must add a number to original list. This incremental expansion has applications in many domains. Let’s discuss a way in which this task can be performed.
Method : Using list comprehensionThis task can be performed in a brute manner, but having a shorter implementation using list comprehension always is better. In this, we perform task in 2 steps, first we make a helper list to form a addition factor list and then cumulate the result using original list.
# Python3 code to demonstrate working of# Incremental List Extension# Using list comprehension  # initializing listtest_list = [7, 8, 9]  # printing original listprint("The original list is : " + str(test_list))  # Extension factorN = 4  # Addition factor M = 3  # Incremental List Extension# Using list comprehensiontemp = [1 * M**i for i in range(N)]temp[0] = 0res = list([ele + tele for tele in temp for ele in test_list])  # printing result print("List after extension and addition : " + str(res))
The original list is : [7, 8, 9]
List after extension and addition : [7, 8, 9, 10, 11, 12, 16, 17, 18, 34, 35, 36]

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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to create Popup box in ReactJS ?

08 Nov, 2021
In this article, we are going to learn how we can create Popup in ReactJs. A pop-up is a graphical user interface display area, usually a small window, that suddenly appears in the foreground of the visual interface.
React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To create our Popup we are going to use the reactjs-popup package because it is powerful, lightweight, and fully customizable. After that, we will add our popup on our homepage with a button to trigger the popup using the installed package.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the reactjs-popup package using the below command:
npm i reactjs-popup
Project Structure: It will look like this.
Adding Popup: In this example, we are going to add the popup on the homepage of our app using the package that we installed. For this, add the below content in the App.js file.
Javascript
import React from 'react';import Popup from 'reactjs-popup';import 'reactjs-popup/dist/index.css';  export default function PopupGfg(){  return(  <div>    <h4>Popup - GeeksforGeeks</h4>    <Popup trigger={<button> Click to open popup </button>}      position="right center">      <div>GeeksforGeeks</div>      <button>Click here</button>    </Popup>  </div>  )};
Explanation: In the above example first, we are importing the Popup component from the react-popup package. After that, we are using our Popup component to add a popup with a button to trigger the popup.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
Output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React