code-rag-bench/online-tutorials huggingface dataset:
PHP array_column() Function

The array_column() function returns the values from a single column of the input array and identified by the column_key.
Optionally, you can pass index_key to index the values in the returned array by the values from the index_key column of the input array.
array array_column( array $input , mixed $column_key [, mixed $index_key = NULL ] )

input (mandatory)
A multi-dimensional array or an array of objects from which to pull a column of values from.
column_key (mandatory)
The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. This value can be NULL to return complete arrays or objects
index_key (optional)
The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.
The function array_column returns an array of values representing a single column from the input array.
This function was first introduced in PHP Version 5.5.0. The the ability for the input parameter to be an array of objects was introduced in 7.0.0
Try out following example to get the column of first names from a recordset −
<?php

 $records = array(
    array(
        'id' => 2135,
        'first_name' => 'Zara',
        'last_name' => 'Ali',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Nuha',
        'last_name' => 'Mac',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Shifa',
        'last_name' => 'Alam',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Riya',
        'last_name' => 'Sweet',
    )
  );

 $first_names = array_column($records, 'first_name');
 print_r($first_names);
?>
This will produce following result −
Array
(
    [0] => Zara
    [1] => Nuha
    [2] => Shifa
    [3] => Riya
)

Now let's try one more example to get the column of first names from a recordset but this time we will index recordset using id −
<?php

 $records = array(
    array(
        'id' => 2135,
        'first_name' => 'Zara',
        'last_name' => 'Ali',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Nuha',
        'last_name' => 'Mac',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Shifa',
        'last_name' => 'Alam',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Riya',
        'last_name' => 'Sweet',
    )
 );
 $first_names = array_column($records, 'first_name', 'id');
 print_r($first_names);
?>
This will produce following result −
Array
(
    [2135] => Zara
    [3245] => Nuha
    [5342] => Shifa
    [5623] => Riya
)


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Namespaces and Scope in Python

In python we deal with variables, functions, libraries and modules etc. There is a chance the name of the variable you are going to use is already existing as name of another variable or as the name of another function or another method. In such scenario, we need to learn about how all these names are managed by a python program. This is the concept of namespace.
Following are the three categories of namespace
Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p>
Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p>
Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace.
Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace.
Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace.
Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace.
The namespace has a lifetime when it is available. That is also called the scope. Also the scope will depend on the coding region where the variable or object is located. You can see in the below program how the variables declared in an inner loop are available to the outer loop but not vice-versa. Also please note how the name of the outer function also becomes part of a global variable.
prog_var = 'Hello'
def outer_func():
   outer_var = 'x'
   def inner_func():
      inner_var = 'y'
      print(dir(), ' Local Variable in Inner function')

      inner_func()
      print(dir(), 'Local variables in outer function')

      outer_func()
      print(dir(), 'Global variables ')
Running the above code gives us the following result −
['inner_var'] Local Variable in Inner function
['inner_func', 'outer_var'] Local variables in outer function
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'outer_func', 'prog_var'] Global variables
RSpec - Tags

RSpec Tags provide an easy way to run specific tests in your spec files. By default, RSpec will run all tests in the spec files that it runs, but you might only need to run a subset of them. Let’s say that you have some tests that run very quickly and that you’ve just made a change to your application code and you want to just run the quick tests, this code will demonstrate how to do that with RSpec Tags.
describe "How to run specific Examples with Tags" do 
   it 'is a slow test', :slow = > true do 
      sleep 10 
      puts 'This test is slow!' 
   end 
   
   it 'is a fast test', :fast = > true do 
      puts 'This test is fast!' 
   end 
end
Now, save the above code in a new file called tag_spec.rb. From the command line, run this command: rspec --tag slow tag_spec.rb
You will see this output −
Run options: include {: slow = >true}
This test is slow! 
. 
Finished in 10 seconds (files took 0.11601 seconds to load) 
1 example, 0 failures

Then, run this command: rspec --tag fast tag_spec.rb
You will see this output −
Run options: include {:fast = >true} 
This test is fast! 
. 
Finished in 0.001 seconds (files took 0.11201 seconds to load) 
1 example, 0 failures

As you can see, RSpec Tags makes it very easy to a subset of tests!

    9 Lectures 
     37 mins

 Harshit Srivastava

    27 Lectures 
     7 hours 

 Atul Tiwari
 Print
 Add Notes
 Bookmark this page
What are the rules about using an underscore in a C++ identifier?

From MSDN docs −
Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.
So you should avoid using names like −
__foo, __FOO, _FOO
And names like the following should not be used in the global namespace −
_foo, _bar
Other than this, there are some more prefixes like LC_, SIG_, and suffixes like _t should not be used as they're also reserved for the implementation.
So you can create variables that contain the underscore between the name or ends with an underscore.
Replace Tab with space in SAP ABAP

You just need to make a small change. You need to add an “If condition” for handling the tab as shown below −
if <field Name> CO gc_hex_char

I think it should sort out your issue and neither it looks like hardcoding or a wrong implementation.
GATE | GATE CS Mock 2018 | Set 2 | Question 64 - GeeksforGeeks

15 Oct, 2019
Consider the given schedule and choose the suitable option.
S = T1:R(x), T1:R(y), T1:W(x), T2:R(y), T3:W(y), T1:W(x), T2:R(y) 
(A) Schedule is view serializable(B) Schedule is conflict serializable but not view serializable(C) Schedule is view serializable but not conflict serializable(D) Neither view serializable nor conflict serializableAnswer: (C)Explanation: Since there is cycle found in precedence graph, it is not Conflict Serializable. Also, there is a blind write in T3 so we need to test further for view serializability using polygraph. From polygraph, we can derive that it is View serializable.Option (C) is Correct.Quiz of this Question
shahfenil1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
MySQL ALTER column to remove primary key and auto_increment?

You can use ALTER command to remove primary key and auto_increment. The syntax is as follows −
ALTER TABLE yourTableName DROP PRIMARY KEY,change yourColumnName yourColumnName data type;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table removePrimaryKey
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT,
   -> StudentFirstName varchar(20),
   -> StudentLastName varchar(20),
   -> PRIMARY KEY(StudentId)
   -> );
Query OK, 0 rows affected (0.47 sec)
Check the description of table using DESC command. The syntax is as follows −
desc yourTableName;
Check the description of the table ‘removePrimaryKey’ using DESC. The query is as follows −
mysql> desc removePrimaryKey;
The following is the output −
+------------------+-------------+------+-----+---------+----------------+
| Field            | Type        | Null | Key | Default | Extra          |
+------------------+-------------+------+-----+---------+----------------+
| StudentId        | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentFirstName | varchar(20) | YES  |     | NULL    |                |
| StudentLastName  | varchar(20) | YES  |     | NULL    |                |
+------------------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
Now look at the column Key and Extra above. In the Key column, there is PRI and in the Extra column there is auto_increment. You need to remove both of them, using the ALTER DROP command discussed in the beginning −
The query is as follows −
mysql> alter table removePrimaryKey DROP PRIMARY KEY,change StudentId StudentId int;
Query OK, 0 rows affected (1.79 sec)
Records − 0 Duplicates − 0 Warnings − 0
We have successfully removed primary key and auto increment above. Now you check the primary key and auto_increment have been removed from the table or not using the following query −
mysql> desc removePrimaryKey;
The following is the output −
+------------------+-------------+------+-----+---------+-------+
| Field            | Type        | Null | Key | Default | Extra |
+------------------+-------------+------+-----+---------+-------+
| StudentId        | int(11)     | YES  |     | NULL    |       |
| StudentFirstName | varchar(20) | YES  |     | NULL    |       |
| StudentLastName  | varchar(20) | YES  |     | NULL    |       |
+------------------+-------------+------+-----+---------+-------+
3 rows in set (0.07 sec)
Java Program to convert Boolean to String

To convert Boolean to String in Java, use the toString() method. For this, firstly, we have declared two booleans.
boolean bool1 = false;
boolean bool2 = true;
Now, convert Boolean to String using the toString() method in Java as shown below −
String str1 = new Boolean(bool1).toString();
String str2 = new Boolean(bool2).toString();
Now, when you will display the values “str1” and “str2”, the output would be in String.
Let us now see the complete example to convert Boolean to String.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      boolean bool1 = false;
      boolean bool2 = true;
      String str1 = new Boolean(bool1).toString();
      String str2 = new Boolean(bool2).toString();
      System.out.println(str1);
      System.out.println(str2);
   }
}
false
true
How to delete multiple ids in MongoDB?

To delete multiple ids in MongoDB, you can use $in operator. Following is the syntax
db.yourCollectionName.remove( { _id : { $in: [yourObjectId1, yourObjectId2, yourObjectId3)] } } );
Let us create a collection with documents
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"Chris","ClientAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cd7d6a629b87623db1b19")
}
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"Robert","ClientAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cd7dea629b87623db1b1a")
}
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"Sam","ClientAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cd7e9a629b87623db1b1b")
}
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"John","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cd7f7a629b87623db1b1c")
}
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"Carol","ClientAge":36});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cd803a629b87623db1b1d")
}
Following is the query to display all documents from a collection with the help of find() method
> db.deleteMultipleIdsDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9cd7d6a629b87623db1b19"),
   "ClientName" : "Chris",
   "ClientAge" : 26
}
{
   "_id" : ObjectId("5c9cd7dea629b87623db1b1a"),
   "ClientName" : "Robert",
   "ClientAge" : 28
}
{
   "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"),
   "ClientName" : "Sam",
   "ClientAge" : 25
}
{
   "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"),
   "ClientName" : "John",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5c9cd803a629b87623db1b1d"),
   "ClientName" : "Carol",
   "ClientAge" : 36
}
Following is the query to delete multiple ids in MongoDB
> db.deleteMultipleIdsDemo.remove( { _id : { $in: [ObjectId("5c9cd7dea629b87623db1b1a"),
... ObjectId("5c9cd803a629b87623db1b1d"),
... ObjectId("5c9cd7d6a629b87623db1b19")
... ] } } );
WriteResult({ "nRemoved" : 3 })
Let us check the multiple ids have been deleted or not
> db.deleteMultipleIdsDemo.find().pretty();
The following is the output displaying we have successfully deleted 3 ids and now only 2 are remaining
{
   "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"),
   "ClientName" : "Sam",
   "ClientAge" : 25
}
{
   "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"),
   "ClientName" : "John",
   "ClientAge" : 34
}
Perl while Loop

A while loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in Perl programming language is −
while(condition) {
   statement(s);
}

Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.
The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value.
Here the key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
#!/usr/local/bin/perl
 
$a = 10;

# while loop execution
while( $a < 20 ) {
   printf "Value of a: $a\n";
   $a = $a + 1;
}
Here we are using the comparison operator < to compare value of variable $a against 20. So while value of $a is less than 20, while loop continues executing a block of code next to it and as soon as the value of $a becomes equal to 20, it comes out. When executed, above code produces the following result −
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
What is an alert box in JavaScript?

An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
You can try to run the following code to learn how to add an alert box −
Live Demo
<html>
   <head>
      <script>
         <!--
            function Warn() {
               alert ("This is a warning message!");
               document.write ("This is a warning message!");
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button to see the result: </p>
      <form>
         <input type="button" value="Click Me" onclick="Warn();" />
      </form>
   </body>
</html>
MongoDB - ObjectId

We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId.
An ObjectId is a 12-byte BSON type having the following structure −
The first 4 bytes representing the seconds since the unix epoch
The next 3 bytes are the machine identifier
The next 2 bytes consists of process id
The last 3 bytes are a random counter value
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.
To generate a new ObjectId use the following code −
>newObjectId = ObjectId()
The above statement returned the following uniquely generated id −
ObjectId("5349b4ddd2781d08c09890f3")
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
This will return the creation time of this document in ISO date format −
ISODate("2014-04-12T21:49:17Z")
In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code −
>newObjectId.str
The above code will return the string format of the Guid −
5349b4ddd2781d08c09890f3


    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Bokeh - Circle Glyphs

The figure object has many methods using which vectorised glyphs of different shapes such as circle, rectangle, polygon, etc. can, be drawn.
Following methods are available for drawing circle glyphs −
The circle() method adds a circle glyph to the figure and needs x and y coordinates of its center. Additionally, it can be configured with the help of parameters such as fill_color, line-color, line_width etc.
The circle_cross() method adds circle glyph with a ‘+’ cross through the center.
The circle_x() method adds circle with an ‘X’ cross through the center.
Following example shows use of various circle glyphs added to Bokeh figure −
from bokeh.plotting import figure, output_file, show
plot = figure(plot_width = 300, plot_height = 300)
plot.circle(x = [1, 2, 3], y = [3,7,5], size = 20, fill_color = 'red')
plot.circle_cross(x = [2,4,6], y = [5,8,9], size = 20, fill_color = 'blue',fill_alpha = 0.2, line_width = 2)
plot.circle_x(x = [5,7,2], y = [2,4,9], size = 20, fill_color = 'green',fill_alpha = 0.6, line_width = 2)
show(plot)
 Print
 Add Notes
 Bookmark this page
How to delete last element from a List in C++ STL

Suppose we have one STL list in C++. There are few elements. We have to delete the last element from that list. So if the elements are like [10, 41, 54, 20, 23, 69, 84, 75], then last element is 75. We will see the C++ code to delete last element from list.
 Live Demo
#include<iostream>
#include<list>
using namespace std;
void display(list<int> my_list){
   for (auto it = my_list.begin(); it != my_list.end(); ++it)
   cout << *it << " ";
}
int main() {
   int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};
   int n = sizeof(arr)/sizeof(arr[0]);
   list<int> my_list;
   for(int i = 0; i<n; i++){
      my_list.push_back(arr[i]);
   }
   cout << "List before delete: ";
   display(my_list);
   my_list.pop_back();//delete last element
   cout << "\nList after delete: ";
   display(my_list);
}
List before delete: 10 41 54 20 23 69 84 75
List after delete: 10 41 54 20 23 69 84
How to add 1 day to the date in MySQL?

We can add 1 day to the date with the help of DATE_ADD() function.
Creating a table.
mysql> create table Add1DayDemo
   -> (
   -> id int,
   -> MyDate datetime not null
   -> );
Query OK, 0 rows affected (1.06 sec)
Insert some records.
mysql> insert into Add1DayDemo values(1,now());
Query OK, 1 row affected (0.08 sec)

mysql>   insert into Add1DayDemo values(2,date_add(now(),interval 5 day));
Query OK, 1 row affected (0.16 sec)
To display all records.
mysql> select *from Add1DayDemo;
The following is the output.
+------+---------------------+
| id   | MyDate              |
+------+---------------------+
|    1 | 2018-10-30 10:51:21 |
|    2 | 2018-11-04 10:51:30 |
+------+---------------------+
2 rows in set (0.00 sec)

To add 1 day in field “MyDate”, use the SELECT
mysql> SELECT DATE_ADD(`MyDate`, INTERVAL 1 DAY) from Add1DayDemo
    ->  where id=2;
The following is the output that shows the day, which was 4th November, increments by one, since we added a day.
+------------------------------------+
| DATE_ADD(`MyDate`, INTERVAL 1 DAY) |
+------------------------------------+
| 2018-11-05 10:51:30                |
+------------------------------------+
1 row in set (0.00 sec)
How to match beginning of a particular string/line using Java RegEx

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example,
The expression “^\\d” matches the string/line starting with a digit.
The expression “^\\d” matches the string/line starting with a digit.
The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^[^a-zA-Z0-9//s].*";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("Match occurred");
      } else { 
         System.out.println("Match not occurred");
      }
   }
}
Enter a String
#starting with a special character
Match occurred
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\\.$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println("String "+i+" ends with '.'");
         }
      }
   }
}
Enter 5 input strings:
hello how are you.
where do you live
what is your name.
welcome to tutorialspoint
The Biggest Online Tutorials Library.
String 0 ends with '.'
String 2 ends with '.'
String 4 ends with '.'
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "^[A-Z]";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println("String "+i+" starts with a capital letter");
         }
      }
   }
}
Enter 5 input strings:
Sample text1
sample text2
hello how are you
Welcome to tutorialspoint
Good morning
String 0 starts with a capital letter
String 3 starts with a capital letter
String 4 starts with a capital letter
C++ Environment Setup

If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer.
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows  as well as Linux, or UNIX.
The files you create with your editor are called source files and for C++ they typically are named with the extension .cpp, .cp, or .c.
A text editor should be in place to start your C++ programming.
This is an actual C++ compiler, which will be used to compile your source code into final executable program.
Most C++ compilers don't care what extension you give to your source code, but if you don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems.
If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line −
$ g++ -v

If you have installed GCC, then it should print a message such as the following −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)

If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions.
Xcode is currently available at developer.apple.com/technologies/tools/.
To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Swap two variables in one line in Java

In order to swap two variable using single expression or in single line we could use bitwise XOR operator of Java.
As we now that in Java XOR functions as XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differs.
So for swapping of two variable we would use this operator as
 Live Demo
public class SwapUsingBitwise {
   public static void main(String[] args) {
      int a = 8 ; int b = 10;
      System.out.println("Before swaping : a = " + a + " b = "+b);
      a = a^b^(b = a);
      System.out.println("After swaping : a = "+ a + " b = "  + b);
   }
}
Before swaping : a = 8 b = 10
After swaping : a = 10 b = 8
Square every digit of a number - JavaScript

We are required to write a JavaScript function that takes in a number and returns a new number in which all the digits of the original number are squared and concatenated
For example: If the number is −
9119
Then the output should be −
811181
because 9^2 is 81 and 1^2 is 1.
Following is the code −
const num = 9119;
const squared = num => {
   const numStr = String(num);
   let res = '';
   for(let i = 0; i < numStr.length; i++){
      const square = Math.pow(+numStr[i], 2);
      res += square;
   };
   return res;
};
console.log(squared(num));
This will produce the following output in console −
811181
How to update a range of records in MySQL?

To update a range of records in MySQL, you can use BETWEEN. Let us first create a table:
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Age int
);
Query OK, 0 rows affected (0.53 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable(Name,Age) values('Larry',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name,Age) values('Chris',21);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Carol',25);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Age) values('David',22);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Robert',26);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('John',20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Mike',27);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name,Age) values('Johnny',28);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Age) values('James',23);
Query OK, 1 row affected (0.23 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+----+--------+------+
| Id | Name | Age |
+----+--------+------+
| 1 | Larry | 23 |
| 2 | Sam | 24 |
| 3 | Chris | 21 |
| 4 | Carol | 25 |
| 5 | David | 22 |
| 6 | Robert | 26 |
| 7 | John | 20 |
| 8 | Mike | 27 |
| 9 | Johnny | 28 |
| 10 | James | 23 |
+----+--------+------+
10 rows in set (0.00 sec)
Following is the query to update a range of records in MySQL. We are updating the Name to ‘Bob’ for Ids in the range 5 to 10:
mysql> update DemoTable set Name='Bob', Age=23 where Id between 5 AND 10;
Query OK, 6 rows affected (0.25 sec)
Rows matched: 6 Changed: 6 Warnings: 0
Let us now display all records including updated records:
mysql> select *from DemoTable;
This will produce the following output
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Larry | 23   |
|  2 | Sam   | 24   |
|  3 | Chris | 21   |
|  4 | Carol | 25   |
|  5 | Bob   | 23   |
|  6 | Bob   | 23   |
|  7 | Bob   | 23   |
|  8 | Bob   | 23   |
|  9 | Bob   | 23   |
| 10 | Bob   | 23   |
+----+-------+------+
10 rows in set (0.00 sec)
Java - String Buffer replace() Method

This method replaces the characters in a substring of this StringBuffer with characters in the specified String.
The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer, if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start.
Here is the syntax of this method −
public StringBuffer replace(int start, int end, String str)

Here is the detail of parameters −
start − The beginning index, inclusive.
start − The beginning index, inclusive.
end − The ending index, exclusive.
end − The ending index, exclusive.
str − String that will replace previous contents.
str − String that will replace previous contents.
This method returns the modified StringBuffer object.
public class Test {

   public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("abcdefghijk");
      sb.replace(3, 8, "ZARA");
      System.out.println(sb); 
   }  
}
This will produce the following result −
abcZARAijk


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How do I see what character set a MySQL database  / table / column is?

To check what character set a MySQL database/ table/ column is, let us see an example: A database which has the name ‘business’ and table name is ‘student’ which is already present in the database is used.
Syntax in order to check the table character set.
SELECT CCSA.character_set_name 
FROM information_schema.`TABLES` T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
AND T.table_schema = "yourDatabaseName"
AND T.table_name = "yourTableName";
Applying the above syntax to display character set for table student.
mysql> SELECT CCSA.character_set_name 
FROM information_schema.`TABLES` T,
   -> information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
   -> WHERE CCSA.collation_name = T.table_collation
   ->   AND T.table_schema = "business"
   -> AND T.table_name = "student";
The following is the output.
+--------------------+
| CHARACTER_SET_NAME |
+--------------------+
| utf8mb4            |
+--------------------+
1 row in set (0.13 sec)

To find character set for database, here is the syntax.
SELECT default_character_set_name FROM information_schema.SCHEMATA
    WHERE schema_name = "yourDatabaseName";
Applying the above syntax in order to see the character set for database.
mysql> SELECT default_character_set_name FROM information_schema.SCHEMATA
   -> WHERE schema_name = "business";
The following is the output.
+----------------------------+
| DEFAULT_CHARACTER_SET_NAME |
+----------------------------+
| utf8mb4                    |
+----------------------------+
1 row in set (0.00 sec)

To find the character set for column.
SELECT character_set_name FROM information_schema.`COLUMNS`
   WHERE table_schema = "yourDatabaseName"
   AND table_name = "yourTableName"
   AND column_name = "yourColumnName";
Applying the above syntax in order to see what character set is for column name ‘Name’ for the “student” table and “business” database.
mysql> SELECT character_set_name FROM information_schema.`COLUMNS`
   -> WHERE table_schema = "business"
   ->  AND table_name = "student"
   -> AND column_name = "Name";
The following is the output.
+--------------------+
| CHARACTER_SET_NAME |
+--------------------+
| utf8mb4            |
+--------------------+
1 row in set (0.00 sec)
How to perform double click on an element in Selenium with python?

We can perform double click on an element in Selenium with the help of
Action Chains class. These classes are generally used for automating interactions
like context menu click, mouse button actions, key press and mouse movements.
These types of actions are mainly common in complex scenarios like drag and drop
and hovering over an element on the page. The methods of the Action Chains class
are utilized by advanced scripts. We can manipulate DOM with the help of Action
Chains in Selenium.
The action chain object implements the ActionChains in the form of a queue and
then executes the perform() method. On calling the method perform(), all the
actions on action chains will be performed.
The method of creating an Action Chain object is listed below −
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
Now all the operations of action chains can be done with the help of this
object.
Now all the operations of action chains can be done with the help of this
object.
Syntax for creating an object of Action Chains −
from selenium import webdriver
# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)
After creating an object of Action Chains, we can perform numerous operations
one by one like a chain which is queued.
double_click() - This method performs double click operation on an element of the
page.
double_click(args)
Where args is the element which has to be double clicked. If omitted, the click on
the present mouse position is performed.
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# double click operation
action.double_click(source)
Code Implementation for double click operation.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//*[text()='GATE Exams']");
# action chain object creation
action = ActionChains(driver)
# double click operation and perform
action.double_click(source).perform()
#to close the browser
driver.close()
Find all divisors of a natural number in java

Following is the Java program which prints all the divisors of a given number.
import java.util.Scanner;

public class DivisorsOfNaturalNumber {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter required number :");
      int num = sc.nextInt();
     
      for(int i = 1; i<num; i++) {
         if(num % i == 0) {
            System.out.println(" "+i);
         }
      }
   }
}
Enter required number :
200
1
2
4
5
8
10
20
25
40
50
100
How to convert numeric columns to factor using dplyr package in R?

If we have a numeric column in an R data frame and the unique number of values in the column is low that means the numerical column can be treated as a factor. Therefore, we can convert numeric columns to factor. To do this using dplyr package, we can use mutate_if function of dplyr package.
Loading dplyr package and converting numerical columns in BOD data set (available in base R) to factor columns −
library(dplyr)
str(BOD)
'data.frame': 6 obs. of 2 variables:
$ Time : num 1 2 3 4 5 7
$ demand: num 8.3 10.3 19 16 15.6 19.8
- attr(*, "reference")= chr "A1.4, p. 270"
BOD%>%mutate_if(is.numeric,as.factor)
  Time demand
1  1   8.3
2  2   10.3
3  3   19
4  4   16
5  5   15.6
6  7   19.8
Converting numerical columns in Formaldehyde data set (available in base R) to factor columns −
str(Formaldehyde)
'data.frame': 6 obs. of 2 variables:
$ carb : num 0.1 0.3 0.5 0.6 0.7 0.9
$ optden: num 0.086 0.269 0.446 0.538 0.626 0.782
Formaldehyde%>%mutate_if(is.numeric,as.factor)
   carb  optden
1  0.1   0.086
2  0.3   0.269
3  0.5   0.446
4  0.6   0.538
5  0.7   0.626
6  0.9   0.782
Converting numerical columns in InsectSprays data set (available in base R) to factor columns −
str(InsectSprays)
'data.frame': 72 obs. of 2 variables:
$ count: num 10 7 20 14 14 12 10 23 17 20 ...
$ spray: Factor w/ 6 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
InsectSprays%>%mutate_if(is.numeric,as.factor)
   count spray
1  10    A
2  7     A
3  20    A
4  14    A
5  14    A
6  12    A
7  10    A
8  23    A
9  17    A
10 20    A
11 14    A
12 13    A
13 11    B
14 17    B
15 21    B
16 11    B
17 16    B
18 14    B
19 17    B
20 17    B
21 19    B
22 21    B
23 7     B
24 13    B
25 0     C
26 1     C
27 7     C
28 2     C
29 3     C
30 1     C
31 2     C
32 1     C
33 3     C
34 0     C
35 1     C
36 4     C
37 3     D
38 5     D
39 12    D
40 6     D
41 4     D
42 3     D
43 5     D
44 5     D
45 5     D
46 5     D
47 2     D
48 4     D
49 3     E
50 5     E
51 3     E
52 5     E
53 3     E
54 6     E
55 1     E
56 1     E
57 3     E
58 2     E
59 6     E
60 4     E
61 11    F
62 9     F
63 15    F
64 22    F
65 15    F
66 16    F
67 13    F
68 10    F
69 26    F
70 26    F
71 24    F
72 13    F
Seaborn - Facet Grid

A useful approach to explore medium-dimensional data, is by drawing multiple instances of the same plot on different subsets of your dataset.
This technique is commonly called as “lattice”, or “trellis” plotting, and it is related to the idea of “small multiples”.
To use these features, your data has to be in a Pandas DataFrame.
In the previous chapter, we have seen the FacetGrid example where FacetGrid class helps in visualizing distribution of one variable as well as the relationship between multiple variables separately within subsets of your dataset using multiple panels.
A FacetGrid can be drawn with up to three dimensions − row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.
FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid.
The variables should be categorical and the data at each level of the variable will be used for a facet along that axis.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time")
plt.show()

In the above example, we have just initialized the facetgrid object which doesn’t draw anything on them.
The main approach for visualizing data on this grid is with the FacetGrid.map() method. Let us look at the distribution of tips in each of these subsets, using a histogram.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time")
g.map(plt.hist, "tip")
plt.show()

The number of plots is more than one because of the parameter col. We discussed about col parameter in our previous chapters.
To make a relational plot, pass the multiple variable names.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "sex", hue = "smoker")
g.map(plt.scatter, "total_bill", "tip")
plt.show()


    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    11 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy
 Print
 Add Notes
 Bookmark this page
Batch Script - Writing to Files

Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command to write data to files.
@echo off
dir C:\>C:\new.txt
The above code snippet first uses the DIR command to get the directory listing of the entire C:\ . It then takes that output and with the help of the redirection command sends it to the file new.txt.
If you open up the file new.txt on your C drive, you will get the contents of your C drive in this file. Following is a sample output.
Volume in drive C is Windows8_OS
Volume Serial Number is E41C-6F43

Directory of C:\

12/22/2015 09:02 PM   <DIR>       01 - Music
06/14/2015 10:31 AM   <DIR>       02 - Videos
09/12/2015 06:23 AM   <DIR>       03 - Pictures
12/17/2015 12:19 AM   <DIR>       04 - Software
12/15/2015 11:06 PM   <DIR>       05 - Studies
12/20/2014 09:09 AM   <DIR>       06 - Future
12/20/2014 09:07 AM   <DIR>       07 - Fitness
09/19/2015 09:56 AM   <DIR>       08 - Tracking
10/19/2015 10:28 PM   <DIR>       09 – Misc

 Print
 Add Notes
 Bookmark this page
How to read text file into a list or array with Python?

f = open('my_file.txt', 'r+')
my_file_data = f.read()
f.close()
The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. The read function reads the whole file at once. You can use the following to read the file line by line and store it in a list:
f = open('my_file', 'r+')
lines = [line for line inf.readlines()]
f.close()
Word Segmentation for Languages Without Spaces Between Words | by Xu LIANG | Towards Data Science

If you are working on some NLP tasks related to Chinese, Japanese and Korean, you might notice that the NLP workflow is different from the English NLP task. Because different from the English, there is no space in these languages to separate the words naturally. So word segmentation is very important for these languages. I have done a little research about different word segmentation methods. In this post, I will give simple advice to choose the best approach.
Use the Unigram Language Model. You can the implementation from SentencePiece, which is a language-independent subword tokenizer. No matter what language you use, this is a good start.
The below sentence in English is separated with space, but the sentence in Japanese has no space.
The corresponding tokens in two languages look like below.
I -> 私will be -> になるthe prirate king -> 海賊王
So how to extract the “海賊王” is the word segmentation problem we need to deal with. Usually, there are three levels we can use, the word level, character level, subword level. But in recent years, the subword level approach has shown its superiority over other approaches, so in this post, I will focus on the subword level.
This post gives a great introduction about 3 subword algorithms:
Byte Pair Encoding (BPE)
WordPiece
Unigram Language Model
The author of the Unigram Language Model also implements a library, SentencePiece, which contains two subword algorithms, BPE and Unigram Language Model.
In the recent powerful language model, BERT uses the WordPiece model and XLNet uses the Unigram Language Model.
The greatest advantage of Unigram Language Model is that this is a language-independent model. No matter what language you use, this is a good start.
Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu