code-rag-bench/online-tutorials huggingface dataset:
Key press in (Ctrl+A) Selenium WebDriver.

We can perform key press of (CTRL+A) with Selenium Webdriver. There are multiple ways to do this. We can use the Keys.chord() method to simulate this keyboard action.
The Keys.chord() method helps to press multiple keys simultaneously. It accepts the sequence of keys or strings as a parameter to the method. To press CTRL+A, it takes, Keys.CONTROL, "a" as parameters.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class PressCtrlA{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // enter text then ctrl+a with Keys.chord()
      l.sendKeys("Selenium");
      String s = Keys.chord(Keys.CONTROL, "a");
      l.sendKeys(s);
      driver.quit()
   }
}
We can also perform a CTRL+A press by simply using the sendKeys() method. We have to pass Keys.CONTROL along with the string A by concatenating with +, as an
argument to the method.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class SendCtrlA{
   public static void main(String[] args) {     System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // enter text then ctrl+a
      l.sendKeys("Selenium");
      l.sendKeys(Keys.CONTROL+"A");
      driver.quit()
   }
}
Remove All Adjacent Duplicates In String in Python

Suppose we have a string S of lowercase letters; a duplicate removal operation will be performed. This will be done by choosing two adjacent and equal letters, and removing them.
We will repeatedly remove duplicates from S until no duplicates are remaining.
Return the string after all such duplicate removals have been completed. It is guaranteed that the answer is unique.
Suppose the string is “abbacaca”, then answer will be “caca”. At first delete duplicates bb, then string is “aacaca”, then remove aa, then string is “caca”, then no such duplicates are there.
To solve this, we will follow these steps −
Define an array st, and initialize i := 0
while i < length of string −if st has some element, and last element of st = st[i], then increase i by 1, and delete last element from stotherwise add string[i] into st, increase i by 1
if st has some element, and last element of st = st[i], then increase i by 1, and delete last element from st
otherwise add string[i] into st, increase i by 1
finally join all elements in st as a string and return
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def removeDuplicates(self, S):
      st = []
      i = 0
      while i < len(S):
         if len(st)!=0 and st[-1]==S[i]:
            i+=1
            st.pop(-1)
         else:
            st.append(S[i])
            i+=1
      return "".join(i for i in st)
ob1 = Solution()
print(ob1.removeDuplicates("abbacaca"))
"abbacaca"
"caca"
log4j - PatternLayout

If you want to generate your logging information in a particular format based on a pattern, then you can use org.apache.log4j.PatternLayout to format your logging information.
The PatternLayout class extends the abstract org.apache.log4j.Layout class and overrides the format() method to structure the logging information according to a supplied pattern.
PatternLayout is also a simple Layout object that  provides the following-Bean Property which can be set using the configuration file:
Sets the conversion pattern. Default is %r [%t] %p %c %x - %m%n
The following table explains the characters used in the above pattern and all other characters that you can use in your custom pattern:
By default, the relevant information is displayed as output as is. However, with the aid of format modifiers, it is possible to change the minimum field width, the maximum field width, and justification.
Following table covers various modifiers scenarios:
Following is a simple configuration file for PatternLayout:
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n

Now consider the following Java Example which would generate logging information:
import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{
   /* Get actual class name to be printed on */
   static Logger log = Logger.getLogger(log4jExample.class.getName());
   
   public static void main(String[] args)throws IOException,SQLException{
      log.debug("Hello this is an debug message");
      log.info("Hello this is an info message");
   }
}
Compile and run the above program. It would create a log.out file in /usr/home/log4j directory which would have the following log information:
2010-03-23-main--DEBUG-log4jExample:Hello this is an debug message
2010-03-23-main--INFO -log4jExample:Hello this is an info message

 Print
 Add Notes
 Bookmark this page
How to create and write JSON array to a file in java?

Java provides javax.json.Json package which contains classes to read a JSON array:
import java.io.FileOutputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonWriter;

public class JSONArrayToFile {
   public static void main(String args[]) throws Exception {
      JsonArray value = Json.createArrayBuilder()
         .add(Json.createObjectBuilder()
         .add("id", "1001")
         .add("Technology", "JavaFX"))
         .add(Json.createObjectBuilder()
         .add("id", "1002")
         .add("Technology", "OpenCV"))
         .build();
      System.out.println(value);
      JsonWriter writer = Json.createWriter(new FileOutputStream("sampleData"));
      writer.writeArray(value);
      writer.close();
   }
}
["JavaFX","HBase","JOGL","WebGL"]
After deleting ::["JavaFX","HBase","JOGL"]
Count the number of items in an array in MongoDB?

To count the number of items in an array, you can use $size operator. The syntax is as follows:
db.yourCollectionName.aggregate({$project:{anyFieldName:{$size:"$yourArrayName"}}}).prett
y();
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
>db.getSizeOfArray.insertOne({"StudentId":1,"StudentName":"Larry","StudentMarks":[87,34,5
6,77,89,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc536fd07954a4890680")
}
>db.getSizeOfArray.insertOne({"StudentId":2,"StudentName":"Sam","StudentMarks":[90,76,56
]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc6b6fd07954a4890681")
}
>db.getSizeOfArray.insertOne({"StudentId":3,"StudentName":"Carol","StudentMarks":[90,76]})
;
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc7a6fd07954a4890682")
}
Now you can display all documents from a collection with the help of find() method. The query is as follows:
> db.getSizeOfArray.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ebc536fd07954a4890680"),
   "StudentId" : 1,
   "StudentName" : "Larry",
   "StudentMarks" : [
      87,
      34,
      56,
      77,
      89,
      90
   ]
}
{
   "_id" : ObjectId("5c6ebc6b6fd07954a4890681"),
   "StudentId" : 2,
   "StudentName" : "Sam",
   "StudentMarks" : [
      90,
      76,
      56
   ]
}
{
   "_id" : ObjectId("5c6ebc7a6fd07954a4890682"),
   "StudentId" : 3,
   "StudentName" : "Carol",
   "StudentMarks" : [
      90,
      76
   ]
}
The following is the query to count the number of items in an array:
>db.getSizeOfArray.aggregate({$project:{NumberOfItemsInArray:{$size:"$StudentMarks"}}}).p
retty();
The following is the output:
{ "_id" : ObjectId("5c6ebc536fd07954a4890680"), "NumberOfItemsInArray" : 6 }
{ "_id" : ObjectId("5c6ebc6b6fd07954a4890681"), "NumberOfItemsInArray" : 3 }
{ "_id" : ObjectId("5c6ebc7a6fd07954a4890682"), "NumberOfItemsInArray" : 2 }
Java char Keyword

❮ Java Keywords

char myGrade = 'B';
System.out.println(myGrade);


Try it Yourself »

The char keyword is a data type that is used to store a single character.
A char value must be surrounded by single quotes, like 'A' or 'c'.
Read more about data types in our Java Data Types Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Overloading unary operator in C++?

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
The unary operators operate on a single operand and following are the examples of Unary operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how bang(!) operator can be overloaded for prefix usage −
#include <iostream>
using namespace std;

class Distance {
   private:
   int feet; // 0 to infinite
   int inches; // 0 to 12

   public:
   // Constructor
   Distance(int f, int i) {
      feet = f;
      inches = i;
   }

   // method to display distance
   void display() {
      cout << "F: " << feet << " I:" << inches <<endl;
   }

   // overloaded bang(!) operator
   Distance operator!() {
      feet = -feet;
      inches = -inches;
      return Distance(feet, inches);
   }
};
int main() {
   Distance D1(3, 4), D2(-1, 10);

   !D1;
   D1.display();   // display D1

   !D2;            // apply negation
   D2.display();   // display D2

   return 0;
}
This will give the output −
F: -3 I:-4
F: 1 I:-10
Average with the Reduce Method in JavaScript

We are required to write a JavaScript function that takes in array of Numbers. The function should calculate the average of all the numbers in the array.
The only condition for us is that we have to do this using Array.prototype.reduce() method.
const arr = [129, 139, 155, 176];
const calculateAverage = (arr = []) => {
   const reducer = (acc, value, index, array) => {
      let val = acc + value;
      if (index === array.length - 1) {
         return val / array.length;
      };
      return val;
   };
   const res = arr.reduce(reducer, 0);
   return res;
};
console.log(calculateAverage(arr));
And the output in the console will be −
149.75
Java Program to add year to current date using Calendar.add method

Firstly, you need to import the following package for Calendar class in Java
import java.util.Calendar;
Create a Calendar object and display the current date and time
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us add year using the calendar.add() method and Calendar.YEAR constant
calendar.add(Calendar.YEAR, 20);
The following is an example
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.println("Current Date = " + calendar.getTime());
      // Add 20 Years
      calendar.add(Calendar.YEAR, 20);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}
Current Date = Thu Nov 22 18:19:06 UTC 2018
Updated Date = Sun Nov 22 18:19:06 UTC 2038
How to connect to an SQLite database using a JDBC program?

A. SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, which means like other databases you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or dynamically as per your requirement with your application. SQLite accesses its storage files directly.
The URL to connect with SQLite database is jdbc:sqlite:test.db and, the driver class name to connect to it is org.sqlite.JDBC.
Before you proceed with the example:
Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbcrepository.
Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbcrepository.
Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples.
Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples.
Assume we have a table named employee_data in SQLite database with 4 records as shown below:
ID      NAME       AGE    ADDRESS     SALARY
------- -------- ------- ---------- ----------
1        Paul       32   California   20000.0
2        Allen      25   Texas        15000.0
3        Teddy      23   Norway       20000.0
4        Mark       25   Richmond     65000.0
Following JDBC program establishes connection with SQLite database, retrieves the content of the table named employee_data and displays it.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectToSQLite {
   public static void main(String[] args) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new org.sqlite.JDBC());
      //Getting the connection
      String url = "jdbc:sqlite:test.db";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Query to retrieve records
      String query = "Select * from employee_data";
      //Executing the query
      ResultSet rs = stmt.executeQuery(query);
      System.out.println("Contents of the employee_data table:");
      while(rs.next()) {
         System.out.print("ID: "+rs.getInt("ID")+", ");
         System.out.print("Name: "+rs.getString("Name")+", ");
         System.out.print("Age: "+rs.getInt("Age")+", ");
         System.out.print("Salary: "+rs.getInt("Salary")+", ");
         System.out.print("Address: "+rs.getString("Address"));
         System.out.println();
      }
   }
}
Connections established......
Contents of the employee_data table:
ID: 1, Name: Paul, Age: 32, Salary: 20000, Address: California
ID: 2, Name: Allen, Age: 25, Salary: 15000, Address: Texas
ID: 3, Name: Teddy, Age: 23, Salary: 20000, Address: Norway
ID: 4, Name: Mark, Age: 25, Salary: 65000, Address: Rich-Mond
MongoDB query select and display only a specific field from the document?

Let us first create a collection with documents −
> db.querySelectDemo.insertOne({UserId:100,UserName:"Chris",UserAge:25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce90eb478f00858fb12e90e")
}
> db.querySelectDemo.insertOne({UserId:101,UserName:"Robert",UserAge:26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce90ec578f00858fb12e90f")
}
> db.querySelectDemo.insertOne({UserId:103,UserName:"David",UserAge:27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce90ed478f00858fb12e910")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.querySelectDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ce90eb478f00858fb12e90e"),
   "UserId" : 100,
   "UserName" : "Chris",
   "UserAge" : 25
}
{
   "_id" : ObjectId("5ce90ec578f00858fb12e90f"),
   "UserId" : 101,
   "UserName" : "Robert",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5ce90ed478f00858fb12e910"),
   "UserId" : 103,
   "UserName" : "David",
   "UserAge" : 27
}
Following is the query to include only a specific field by setting it to TRUE in find() −
> db.querySelectDemo.find({},{_id:0,UserName:true});
This will produce the following output −
{ "UserName" : "Chris" }
{ "UserName" : "Robert" }
{ "UserName" : "David" }
Add CSS to the Jupyter Notebook using Pandas - GeeksforGeeks

06 Dec, 2019
In Jupyter Notebook, when we print the output table of our data, it shows a very basic table containing the data. But what if we want to customize this default style? In this article, we will see how we can add styles to our output data table.
This is how a default data table looks like in Jupyter Notebook:
import pandas as pd    df = pd.DataFrame({'A':[1, 2, 3, 4, 5, 6, 7, 8],                    'B':[1, 2, 3, 4, 5, 6, 7, 8],                    'C':[1, 2, 3, 4, 5, 6, 7, 8],                   'D':[1, 2, 3, 4, 5, 6, 7, 8]})  df.head()
Output:
Now let’s try to change the style. We can do it by the set_table_styles method of pandas module.
df.style.set_table_styles()
Now we need to pass the ‘selectors’ and ‘props’ as argument to this method, i.e. we need to select the CSS tags of the table (eg: th, td etc) and change the values of their properties (eg: background, font-color, font-family etc).
So, if we need to change the font-family of the text in the data section of the table, we can do it like this:
df.style.set_table_styles(  [{'selector': 'td',  'props': [('font-family', 'Sans-serif')]},])
 Let’s try to add more changes and see the output.
df = pd.DataFrame({'A':[1, 2, 3, 4, 5, 6, 7, 8],                    'B':[1, 2, 3, 4, 5, 6, 7, 8],                    'C':[1, 2, 3, 4, 5, 6, 7, 8],                   'D':[1, 2, 3, 4, 5, 6, 7, 8],                   'E':[1, 2, 3, 4, 5, 6, 7, 8]})    df.style.set_table_styles([ {'selector': 'th',  'props': [('background', '# 606060'),             ('color', 'white'), ]}, {'selector': 'td',  'props': [('color', 'blue')]},])
Output:
We can also hide the index column by hide_index() method:
df.style.set_table_styles([ {'selector': 'th',  'props': [('background', '# 606060'),             ('color', 'yellow'), ]}, {'selector': 'td',  'props': [('color', 'red')]},]).hide_index()
Output:
Python-pandas
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to make text italic in HTML?

To make text italic in HTML, use the <i>...</i> tag or <em>...</em> tag. Both the tags have the same functioning, but <em> tag is a phrase tag, which renders as emphasized text.
Just keep in mind that you can get the same result in HTML with CSS font-style property.
You can try to run the following code to make text italic in HTML using <em>...</em> tag
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML italic text</title>
   </head>

   <body>
      <h1>Products</h1>
      <p>
         Our products: <em>Online HTML Editor</em> and <em>Online Image Editor</em>.
      </p>
   </body>
</html>
You can try to run the code make text italic in HTML using the font-style property
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML italic text</title>
   </head>

   <body>
      <h1>Our Products</h1>
      <p style="font-style: italic;">Learning website</p>
   </body>
</html>
Tryit Editor v3.7

CSS Color Keywords
Tryit: Using the currentcolor keyword
How to set cursor style to pointer for links without href ? - GeeksforGeeks

25 Sep, 2019
Method 1: Using a CSS class for the linksA CSS class is created that changes the cursor property. The cursor property is used to specify the mouse cursor to be displayed when the mouse is pointed over an element. Using the ‘pointer’ value in this property will change the cursor to a ‘pointer’ indicating a link.
This class can then be used on any link that does not have any href property to show the pointer.
Syntax:
.pointer-link {  cursor: pointer;}
Example:
<!DOCTYPE html><html>  <head>    <title>How to set cursor style       to pointer for links without href ?</title>    <style>        .pointer-link {            cursor: pointer;        }    </style></head>  <body>    <h1 style="color: green">      GeeksforGeeks  </h1>    <b>How to set cursor style to      pointer for links without href ?</b>        <p>The <a> link below      has the cursor style set to pointer.</p>        <a class="pointer-link">Example link</a></body>  </html>
Output:
Method 2: Using the onmouseover event for each link to change the styleThe onmouseover event is triggered whenever the mouse pointer is moved over an element or its children. The style property of the element is accessed and the cursor property is changed.The cursor property is used to specify the mouse cursor to be displayed when it is pointed over an element. Using the ‘pointer’ value in this property will change the cursor to a pointer indicating a link.
This event can be used on any link that does not have any href property to show the pointer.
Syntax:
<a onmouseover="this.style.cursor='pointer'>Example link</a>
Example:
<!DOCTYPE html><html>  <head>    <title>How to set cursor style      to pointer for links without href ?</title></head>  <body>    <h1 style="color: green">      GeeksforGeeks  </h1>    <b>How to set cursor style       to pointer for links without href ?</b>        <p>The <a> link below       has the cursor style set to pointer.</p>        <a onmouseover="this.style.cursor='pointer'">Example link</a></body>  </html>
Output:
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer

To fetch the consecutive 1’s, use the Bitwise Left Shift Operator. Here is our decimal number.
i = (i & (i << 1));
Loop the above until the value of I is 0 and fetch the length using a variable; count here.
while (i != 0) {
   i = (i & (i << 1));
   count++;
}
The example we have taken here is 150.
The binary for 150 is 10010110. Therefore, we have two consecutive one’s.
 Live Demo
using System;
class Demo {
   private static int findConsecutive(int i) {
      int count = 0;
      while (i != 0) {
         i = (i & (i < 1));
         count++;
      }
      return count;
   }

   // Driver code
   public static void Main() {
      // Binary or 150 is 10010110
      Console.WriteLine(findConsecutive(150));
   }
}
2
abs() function for complex number in c++ ?

The abs function in C++ is used to find the absolute value of a complex number. The absolute value of a complex number (also known as modulus) is the distance of that number from the origin in the complex plane. This can be found using the formula −
For complex number a+bi:
mod|a+bi| = √(a2+b2)
The abs() function returns the result of the above calculation in C++. It is defined in the complex library that is needed to be included.
#include <iostream>
#include <complex>
using namespace std;
int main () {
   float a= 13.0 , b = 5.0;
   complex<double> complexnumber (a, b);
   cout << "The absolute value of " << a<<"+"<<b<<"i" << " is: ";
   cout << abs(complexnumber) << endl;
   return 0;
}
The absolute value of 13+5i is: 13.9284
MySQL - SHOW CREATE PROCEDURE STATEMENT

Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures.
Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets.
The SHOW CREATE PROCEDURE statement displays the (string) query used to create the specified procedure.
Following is the syntax of the SHOW CREATE PROCEDURE statement −
SHOW CREATE PROCEDURE procedureName;

Where, procedure_name is the name of the procedure you need to alter.
Suppose we have created a table named Employee in the database using the CREATE statement and inserted three records in it as shown below −
mysql> CREATE TABLE Employee(Name VARCHAR(255), Salary INT, Location VARCHAR(255));
mysql> INSERT INTO Employee VALUES ('Amit', 6554, 'Hyderabad');
mysql> INSERT INTO Employee VALUES ('Sumith', 5981, 'Vishakhapatnam');
mysql> INSERT INTO Employee VALUES ('Sudha', 7887, 'Vijayawada');
Assume we have created a stored procedure named myProcedure. Here we are inserting a column in to the Employee table taking values from user. (through input parameters)
mysql> DELIMITER //
mysql> Create procedure myProcedure (
   IN name VARCHAR(30),
   IN sal INT,
   IN loc VARCHAR(45))
   BEGIN
      INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc);
   END //
Query OK, 0 rows affected (0.20 sec)
mysql> DELIMITER ;
Following query displays the CREATE statement used to create the above procedure −
mysql> SHOW CREATE PROCEDURE myProcedure\G
*************************** 1. row ***************************
       Procedure: myProcedure
        sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `myProcedure`(
   IN name VARCHAR(30),
   IN sal INT,
   IN loc VARCHAR(45))
   COMMENT 'This is a sample comment'
   BEGIN
      INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc);
   END
character_set_client: cp850
collation_connection: cp850_general_ci
  Database Collation: utf8mb4_0900_ai_ci
1 row in set (0.07 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Batch Script - Remove

The string substitution feature can also be used to remove a substring from another string.
@echo off 
set str = Batch scripts is easy. It is really easy. 
echo %str% 

set str = %str:is = % 
echo %str%
The key thing to note about the above program is, the ‘is’ word is being removed from the string using the :’stringtoberemoved’ = command.
The above command produces the following output.
Batch scripts is easy. It is really easy. 
Batch scripts easy. It really easy.

 Print
 Add Notes
 Bookmark this page
Selecting a single row in MySQL?

If you want to select a single row on the basis of primary key, use the WHERE clause. The syntax is as follows −
SELECT * FROM yourTableName WHERE yourPrimaryKeyColumnName = someValue;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table selectWithPrimaryKey
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> Marks int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Larry',24,98);
Query OK, 1 row affected (0.15 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('John',23,89);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Mike',21,85);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Sam',26,56);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Carol',21,59);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Bob',20,91);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('David',28,93);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from selectWithPrimaryKey;
The following is the output −
+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
|  1 | Larry |   24 |    98 |
|  2 | John  |   23 |    89 |
|  3 | Mike  |   21 |    85 |
|  4 | Sam   |   26 |    56 |
|  5 | Carol |   21 |    59 |
|  6 | Bob   |   20 |    91 |
|  7 | David |   28 |    93 |
+----+-------+------+-------+
7 rows in set (0.00 sec)
The following is the query to select a single row from the table −
mysql> select *from selectWithPrimaryKey where Id = 6;
Here is the output −
+----+------+------+-------+
| Id | Name | Age  | Marks |
+----+------+------+-------+
| 6  | Bob  | 20   | 91    |
+----+------+------+-------+
1 row in set (0.00 sec)
Compressing and Decompressing files in C#

Use the System.IO.Compression Namespace in C# to compress and decompress files in C#.
To zip a file, use the GZipStream class with the FileStream class. Set the following parameters: File to be zipped and the name of the output zip file.
Here, outputFile is the output file and the file is read into the FileStream.
using(var compress = new GZipStream(outputFile, CompressionMode.Compress, false)) {
   byte[] b = new byte[inFile.Length];
   int read = inFile.Read(b, 0, b.Length);
   while (read > 0) {
      compress.Write(b, 0, read);
      read = inFile.Read(b, 0, b.Length);
   }
}
To decompress a file, use the same the GZipStream class. Seth the following parameters: source file and the name of the output file.
From the source zip file, open a GZipStream.
using (var zip = new GZipStream(inStream, CompressionMode.Decompress, true))
To decompress, use a loop and read as long as you have data in the stream. Write it to the output stream and a file generates. The file is our decompressed file.
using(var zip = new GZipStream(inputStream, CompressionMode.Decompress, true)) {
   byte[] b = new byte[inputStream.Length];
   while (true) {
      int count = zip.Read(b, 0, b.Length);
      if (count != 0)
      outputStream.Write(b, 0, count);
      if (count != b.Length)
      break;
   }
}
DAX Date & Time - CALENDAR function

Returns a table with a single column named “Date” that contains a contiguous set of dates. The range of dates is from the specified start date to the specified end date, inclusive of those two dates.
DAX CALENDAR function is new in Excel 2016.
CALENDAR (<start_date>, <end_date>) 

start_date
Any DAX expression that returns a datetime value.
end_date
Any DAX expression that returns a datetime value.
Returns a table with a single column named “Date” containing a contiguous set of dates.
An error is returned if start_date is greater than end_date.
= COUNTROWS (CALENDAR (DATE (2016,8,1), DATE (2016,10,31))) returns 92. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Callback function in C

The callback is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time. We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function.
In C we have to use the function pointer to call the callback function. The following code is showing how the callback function is doing its task.
#include<stdio.h>
void my_function() {
   printf("This is a normal function.");
}
void my_callback_function(void (*ptr)()) {
   printf("This is callback function.\n");
   (*ptr)();    //calling the callback function
}
main() {
   void (*ptr)() = &my_function;
   my_callback_function(ptr);
}
This is callback function.
This is a normal function.
How to save a csv and read using fread in R?

To save a csv file, we can use write.csv function in R and if we want to read it using fread then fread function will be used with the name of the csv file. The benefit of reading the csv file with fread function is that there will be a variable added to the original csv file which contains the id as integers starting from 1 to the length of column values.
Consider the below data frame −
 Live Demo
x<-rpois(20,5)
y<-rpois(20,5)
z<-rpois(20,5)
df<-data.frame(x,y,z)
df
   x  y  z
1  8  2  4
2  2  5  4
3  5  5  3
4  7  3  9
5  3  3  7
6  1  10 6
7  5  5  3
8  4  5  3
9  5  5  2
10 8  9  7
11 6  5  6
12 8  4  3
13 6  5  10
14 4  5  3
15 4  5  7
16 6  5  6
17 6  4  6
18 2  8  7
19 6  4  3
20 8  5  6
Saving the above data frame in csv file −
write.csv(df,"FreadReadingEx.csv")
Reading the csv file using fread function −
fread("FreadReadingEx.csv")
    V1 x  y  z
1:  1  8  2  4
2:  2  2  5  4
3:  3  5  5  3
4:  4  7  3  9
5:  5  3  3  7
6:  6  1 10  6
7:  7  5  5  3
8:  8  4  5  3
9:  9  5  5  2
10: 10 8  9  7
11: 11 6  5  6
12: 12 8  4  3
13: 13 6  5  10
14: 14 4  5  3
15: 15 4  5  7
16: 16 6  5  6
17: 17 6  4  6
18: 18 2  8  7
19: 19 6  4  3
20: 20 8  5  6
How to handle invalid arguments with argparse in Python?

We rewrite the given code as follows
#foo.py
import argparse
class InvalidArgError(Exception):pass
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
try:
print (args.echo)
raise InvalidArgError
except InvalidArgError as e:
print e
When this script is run at the terminal as follows
$ python foo.py echo bar
We get the following output
usage: foo.py [-h] echo
foo.py: error: unrecognized arguments: bar
Kotlin | Class Properties and Custom Accessors - GeeksforGeeks

18 Aug, 2021
The basic and most important idea of a class is Encapsulation. It is a property to encapsulate code and data, into a single entity. In Java, the data are stored in the fields and these are mostly private. So, accessor methods – a getter and a setter are provided to let the clients of the given class access the data. For sending notifications about the change or validating the passed value, additional logic is also present in the setter.  
It is the combination of accessories and the fields in the case of Java. In the case of Kotlin, properties are meant to be a first-class language feature. These features replace fields and accessor methods. A property in a class is declared the same as declaring a variable with val and var keywords. A property declared as var is mutable and thus, can be changed.
Defining a class:
Kotlin
class Abc(    val name: String,    val ispassed : Boolean)
Readable Property: Generates a field and a trivial getter Writable Property: A getter, a setter, and a field
Basically what happens is that the declaration of the property declares the related accessors (both setter and getter for writable and getter for readable property). A field stores the value.
Let’s see the class usage 
Kotlin
class Abc(    val name: String,    val ispassed : Boolean) fun main(args: Array<String>) {     val abc = Abc("Bob",true)    println(abc.name)    println(abc.ispassed)     /*    In Java    Abc abc = new Abc("Bob",true);    System.out.println(person.getName());    System.out.println(person.isMarried());     */}
Output: 
Bob
true
In Kotlin, the constructor can be called without a new keyword. Instead of invoking the getter, the property is referenced directly. The logic remains the same and the code is much more concise. Setters of mutable property works in a similar manner.  
Custom implementation of property accessor.  
Kotlin
class Rectangle(val height: Int, val width: Int){    val isSquare: Boolean        get() {            return height == width        }}  fun main(args: Array<String>) {      val rectangle = Rectangle(41, 43)    println(rectangle.isSquare)    }
Output: 
false
The property isSquare needs no field to store the value. It only has a custom getter with the implementation provided. Every time the property is accessed, the value is computed.
panwaravishkar
marktahu7
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
Android UI Layouts
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Change the Color of Status Bar in an Android App?
Android Menus
ImageView in Android with Example
How to Get Current Location in Android?
Kotlin Android Tutorial
C++ Array Library - fill() Function

The C++ function std::array::fill() sets given value to all elements of array.
Following is the declaration for std::array::fill() function form std::array header.
void fill(const value_type &val);
val − value to be set
None
None
Linear i.e. O(n)
The following example shows the usage of std::array::fill() function.
#include <iostream>
#include <array>

using namespace std;

int main(void) {

   int i;
   array<int, 5> arr;

   for(i = 0; i < 5; ++i)
      arr[i] = i + 1;

   cout << "Original array\n";
   for(i = 0; i < 5; ++i)
      cout << arr[i] << " ";
   cout << endl;

   arr.fill(10);

   cout << "Modified array\n";
   for(i = 0; i < 5; ++i)
      cout << arr[i] << " ";
   cout << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Original array
1 2 3 4 5 

Modified array
10 10 10 10 10

 Print
 Add Notes
 Bookmark this page
Building Multiple Indexes at once in MongoDB?

In order to build multiple indexes at once, you need to use createIndexes() and pass multiple keys into an array. Following is the query for building multiple indexes at once.
>db.multipleIndexesDemo.createIndexes([{"First":1},{"Second":1},{"Third":1},{"Fourth":1},{"Fifth":1}]);
This will produce the following output
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 6,
   "ok" : 1
}
Now get all the indexes
> db.multipleIndexesDemo.getIndexes();
This will produce the following output
[
   {
      "v" : 2,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "test.multipleIndexesDemo"
   },
   {
      "v" : 2,
      "key" : {
         "First" : 1
      },
      "name" : "First_1",
      "ns" : "test.multipleIndexesDemo"
   },
   {
      "v" : 2,
      "key" : {
         "Second" : 1
      },
      "name" : "Second_1",
      "ns" : "test.multipleIndexesDemo"
   },
   {
      "v" : 2,
      "key" : {
         "Third" : 1
      },
      "name" : "Third_1",
      "ns" : "test.multipleIndexesDemo"
   },
   {
      "v" : 2,
      "key" : {
         "Fourth" : 1
      },
      "name" : "Fourth_1",
      "ns" : "test.multipleIndexesDemo"
   },
   {
      "v" : 2,
      "key" : {
         "Fifth" : 1
      },
      "name" : "Fifth_1",
      "ns" : "test.multipleIndexesDemo"
   }
]
AngularJS | angular.isString() Function - GeeksforGeeks

12 Apr, 2019
The angular.isString() function in AngularJS is used to determine the parameter inside isString function is a string or not. It returns true if the reference is a string otherwise returns false.
Syntax:
angular.isString( value )
Return Value: It returns true if the value passed is a string otherwise return false.
Example: This example uses angular.isString() function to determine the parameter inside isString function is a string or not.
<!DOCTYPE html><html>    <head>        <title>angular.isString() function</title>                  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">        </script>    </head>      <body ng-app="app" style="text-align:center">        <h1 style="color:green">GeeksforGeeks</h1>        <h2>angular.isString()</h2>                  <div ng-controller="geek">            <b>Input1: </b>                 <span>                    <code>123</code>                </span>            <br>                          <b>isString: </b>{{isString1}}<br /><br><br>            <b>Input2: </b>                           <code>                "geeksforgeeks"            </code>            <br>                          <b>isString:</b> {{isString2}}        </div>                  <!-- Script to use angular.isString() function -->        <script>            var app = angular.module("app", []);            app.controller('geek', ['$scope', function ($scope) {                var obj1 = 123;                var obj2 = "geeksforgeeks";                $scope.isString1 = angular.isString(obj1);                $scope.isString2 = angular.isString(obj2);            }]);        </script>    </body></html>                    
Output:
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Adding new enum column to an existing MySQL table?

To add a new enum column to an existing MySQL table, you can use ALTER command. Following is the syntax:
ALTER TABLE yourTableName ADD yourColumnName ENUM('yourValue1','yourValue2’....N) NOT NULL;
Let us first create a table:
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(200),
   StudentAge int
);
Query OK, 0 rows affected (0.62 sec)
Check the description of table using DESC command:
mysql> DESC DemoTable;
This will produce the following output:
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| StudentId   | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName | varchar(200) | YES  |     | NULL    |                |
| StudentAge  | int(11)      | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
Following is the query to add a new enum column to existing table. We have set it for Student Gender:
mysql> ALTER TABLE DemoTable ADD StudentGender ENUM('Male','Female') NOT NULL;
Query OK, 0 rows affected (0.40 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again:
mysql> desc DemoTable;
This will produce the following output and display the enum values as well for GENDER:
+---------------+-----------------------+------+-----+---------+----------------+
| Field         | Type                  | Null | Key | Default | Extra          |
+---------------+-----------------------+------+-----+---------+----------------+
| StudentId     | int(11)               | NO   | PRI | NULL    | auto_increment |
| StudentName   | varchar(200)          | YES  |     | NULL    |                |
| StudentAge    | int(11)               | YES  |     | NULL    |                |
| StudentGender | enum('Male','Female') | NO   |     | NULL    |                |
+---------------+-----------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Look at the above sample output, the column StudentGender has data type ENUM.
How to find the highest number in a column?

You can find the highest number in a column with the help of aggregate function MAX. The syntax is as follows −
select max(yourColumnName) as anyVariableName from yourTableName;
To understand the above concept, let us create a table with an int column. The following is the query to create a table.
mysql> create table HighestNumberDemo
   −> (
      −> BigNumber int
   −> );
Query OK, 0 rows affected (0.87 sec)
Now insert some values in the table. The query to insert records are as follows −
mysql> insert into HighestNumberDemo values(1234);
Query OK, 1 row affected (0.43 sec)

mysql> insert into HighestNumberDemo values(9999);
Query OK, 1 row affected (0.18 sec)

mysql> insert into HighestNumberDemo values(10000);
Query OK, 1 row affected (0.17 sec)

mysql> insert into HighestNumberDemo values(989898);
Query OK, 1 row affected (0.14 sec)

mysql> insert into HighestNumberDemo values(999987);
Query OK, 1 row affected (0.18 sec)
Now you can display all records with the help of select statement. The query to display all records are as follows −
mysql> select *from HighestNumberDemo;
The following is the output −
+-----------+
| BigNumber |
+-----------+
|      1234 |
|      9999 |
|     10000 |
|    989898 |
|    999987 |
+-----------+
5 rows in set (0.00 sec)
Implement the syntax we discussed above to find the highest number in a column. The query is as follows −
mysql> select max(BigNumber) as HighestNumber from HighestNumberDemo;
The following is the output −
+---------------+
| HighestNumber |
+---------------+
| 999987        |
+---------------+
1 row in set (0.00 sec)
How to extract column from data frame as vector in R ?

07 Apr, 2021
In this article, we are going to convert dataframe column into a vector in R Programming Language.
Create vectors
Create a dataframe by passing these vectors
Convert dataframe column using“[[]]” operator (indexing). [[]] is used to access the dataframe column.It is used to index the dataframe.
Syntax:
dataframe_name[[‘column_name’]]
Display vectors
Example 1:
R
# creating a vector for namesnames=c('siva nagulu','bhavanarayana','sireesha',        'priyank chowdary','sridevi','ravi kumar')  # creating a vector for agesages=c(40,49,38,42,36,39)  #create a dataframe using these vectorsdataframe=data.frame(names,ages)print(dataframe)  # converting ages dataframe column into vector# by passing as indexmy_data = dataframe[['names']]print("--------convert into vector of names column-------")print(my_data)  my_data = dataframe[['ages']]print("--------convert into vector of ages column-------")print(my_data)
Output:
Example 2:
R
# creating a vector for citycity=c('kakumanu','hyd','noida')  # create a dataframe using this vectordataframe=data.frame(city)print(dataframe)  # converting city dataframe column into vector# by passing as indexmy_data = dataframe[['city']]print("--------convert into vector of city column-------")print(my_data)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.