code-rag-bench/online-tutorials huggingface dataset:
PHP if...else...elseif Statements

Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for 
different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and another code if that condition is false
if...elseif...else statement  - executes different codes for more than two conditions
switch statement - selects one of many blocks of code to be executed
The if statement executes some code if one condition is true.
Output "Have a good day!" if the current time (HOUR) is less than 20:
The if...else statement executes some code if a condition is true and 
another code if that condition is false.
Output "Have a good day!" if the current time is less than 20, and "Have a 
  good night!" otherwise:
The if...elseif...else statement executes different codes for more than two 
conditions.
Output "Have a good morning!" if the current time is less than 10, and 
  "Have a good day!" if the current time is less than 20. Otherwise it will 
  output "Have a good night!":
The switch statement will be explained in the next chapter.
Output "Hello World" if $a is greater than $b.
$a = 50;
$b = 10;
  >  {
  echo "Hello World";
}

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.
MySQL - SHOW DATABASES Statement

After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own. You can create any database using the MySQL CREATE DATABASE statement.
The SHOW DATABASES Statement of MySQL lists out all the existing databases.
Following is the syntax of the Show DATABASES table −
SHOW {DATABASES | SCHEMAS}
   [LIKE 'pattern' | WHERE expr]

Following query creates a database with name myDatabase −
mysql> CREATE DATABASE myDatabase;
Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases as follows −
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydatabase         |
| performance_schema |
| world              |
+--------------------+
4 rows in set (0.00 sec)
Assume we have created four databases in MYSQL using the CREATE DATABASE statement as shown below −
mysql> CREATE DATABASE testDB1;
Query OK, 1 row affected (0.34 sec)

mysql> CREATE DATABASE testDB2;
Query OK, 1 row affected (0.19 sec)

mysql> CREATE DATABASE testDB3;
Query OK, 1 row affected (0.21 sec)

mysql> CREATE DATABASE testDB4;
Query OK, 1 row affected (0.25 sec)
Following query lists out the databases, you can observe the created ones in the list.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydatabase         |
| performance_schema |
| testdb1            |
| testdb2            |
| testdb3            |
| testdb4            |
| world              |
+--------------------+
8 rows in set (0.00 sec)
Now, let us delete three databases create above −
mysql> DROP DATABASE testDB1;
Query OK, 0 rows affected (0.15 sec)
mysql> DROP DATABASE testDB2;
Query OK, 0 rows affected (0.34 sec)
mysql> DROP DATABASE testDB3;
Query OK, 0 rows affected (0.21 sec)
if you verify the list of the tables again, you can observe that the deleted database names are missing −
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydatabase         |
| performance_schema |
| testdb4            |
| world              |
+--------------------+
5 rows in set (0.00 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
Python Program to Check if Two Strings are Anagram - GeeksforGeeks

17 Feb, 2022
Question:
Given two strings s1 and s2, check if both the strings are anagrams of each other.Examples: 
Input : s1 = "listen"
        s2 = "silent"
Output : The strings are anagrams.


Input : s1 = "dad"
        s2 = "bad"
Output : The strings aren't anagrams.
Python provides a inbuilt function sorted() which does not modify the original string, but returns sorted string.Below is the Python implementation of the above approach: 
Python
# function to check if two strings are# anagram or notdef check(s1, s2):         # the sorted strings are checked    if(sorted(s1)== sorted(s2)):        print("The strings are anagrams.")    else:        print("The strings aren't anagrams.")                 # driver code s1 ="listen"s2 ="silent"check(s1, s2)
The strings are anagrams.
Count all the frequencies of 1st string and 2 and using counter()
If they are equal then print anagram
Python3
# Python3 program for the above approachfrom collections import Counter # function to check if two strings are# anagram or notdef check(s1, s2):       # implementing counter function    if(Counter(s1) == Counter(s2)):        print("The strings are anagrams.")    else:        print("The strings aren't anagrams.")  # driver codes1 = "listen"s2 = "silent"check(s1, s2)
The strings are anagrams.
vikkycirus
adnanjsr
kapoorsagar226
mattjschaub
anagram
Python-Sorted
Python
Strings
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
YACC program which accept strings that starts and ends with 0 or 1

06 May, 2019
Problem: Write a YACC program which accept strings that starts and ends with Zero or One
Explanation:YACC (Yet another Compiler-Compiler) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc.
Examples:
Input: 001100
Output: Sequence Accepted

Input: 1001001
Output: Sequence Accepted

Input: 0011101
Output: Sequence Rejected

Input: 100110
Output: Sequence Rejected 
Lexical Analyzer Source Code :
%{  /* Definition section */  extern int yylval;%}  /* Rule Section */%%  0 {yylval = 0; return ZERO;}  1 {yylval = 1; return ONE;}  .|\n {yylval = 2; return 0;}  %%
Parser Source Code :
%{  /* Definition section */  #include<stdio.h>  #include <stdlib.h>  void yyerror(const char *str)   {   printf("\nSequence Rejected\n");          }  %}  %token ZERO ONE  /* Rule Section */%%  r : s {printf("\nSequence Accepted\n\n");};  s : n| ZERO a| ONE b;  a : n a| ZERO;  b : n b| ONE;  n : ZERO| ONE;  %%  #include"lex.yy.c"//driver codeint main()  {    printf("\nEnter Sequence of Zeros and Ones : ");    yyparse();    printf("\n");    return 0; }
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
D3.js | color.opacity

12 Jul, 2019
The color.opacity in D3.js is used to fade the color. The opacity value is in the range of [0, 1].
Syntax:
color.opacity
Parameters: This function does not accept any parameters.
Return Value: This function returns the opacity value of the specified color.
Below program illustrate the color.opacity function in D3.js:
Example:
<!DOCTYPE html><html>  <head>    <title>color.rgb() function</title>      <script src='https://d3js.org/d3.v4.min.js'>  </script></head>  <body>    <script>        // Calling the d3.color() function        // with some parameters        var color1 = d3.color("red");        var color2 = d3.color("green");        var color3 = d3.color("blue");          // Calling the color.opacity        var A = color1.opacity;        var B = color2.opacity;        var C = color3.opacity;          // Getting the opacity value        console.log(A);        console.log(B);        console.log(C);    </script></body>  </html>
Output:
1
1
1

Ref: https://devdocs.io/d3~5/d3-color#color_opacity
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the valid range of a Class A network address?

05 Jul, 2022
Let us know what an IP address is first, if you already know, skip this section. 
IP (Internet Protocol): It is one of the fundamental protocols inorder to have communications on the Internet. IP describes how the information is addressed, routed by networking devices. An IP address is a number identifying of a computer or another device on the Internet. A simple example could be mailing address.
There are 2 types of IP
1. IPv4 : 32 bit long, Ex: 35.244.11.196
2. IPv6 : 128 bit long, it is so much longer than IPv4
Example for IPv4 :
1. Dotted Decimal Notation 
IPv4: 32 bit long ( Dotted Decimal )
2. Hexadecimal Notation
IPv4: 32 bit long ( Hexadecimal )
CLASS ADDRESSING :
So, In IPv4 addressing, there are 5 classes to range IP Values : Class A, B, C, D and E.
The order of bits in the first octet determine the classes of IP address.
IPv4 address is divided into two parts:1. Network ID 2. Host ID
The class can determine the bits used for network ID and host ID.
The number of total networks and hosts possible in that particular class can be calculated.
Only class A, B and C are commonly used. classes D and E are reserved classes, D for multicast groups and E for future purposes.
CLASS A :
IP address belonging to class A are assigned to the networks that contain a large number of hosts. Here, class A can support 16 million hosts on 127 networks.
Here, the network ID is 8 bits long and the host ID is 24 bits long.
IP addresses belonging to class A ranges from 1.x.x.x – 126.x.x.x
Default Subnet Mask: 255.x.x.x
Number Of Hosts and Networks:

Number of Hosts: (2^24)-2= 16,777,214 i.e 16 million hosts
Number of Networks: (2^7)-2=126 
Note: Reducing 2 because, 0.0.0.0 and 127.a.b.c are different addresses
>> The range of class A is 1.0.0.1 to 126.255.255.254
Other classes
Class B: 128.1.0.1 to 191.255.255.254Class C: 192.0.1.1 to 223.255.254.254Class D: 244.0.0.0 to 239.255.255.255Class E: 240.0.0.0 to 254.255.255.254
emailten9r
vinayedula
Picked
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Ways to find nth occurrence of substring in a string

10 Jul, 2022
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let’s discuss a few methods to solve the given task. Method #1: Using re 
Python3
# Python code to demonstrate# to find nth occurrence of substring import re # Initialising valuesini_str = "abababababab"substr = "ab"occurrence = 4  # Finding nth occurrence of substringinilist = [m.start() for m in re.finditer(r"ab", ini_str)]if len(inilist)>= 4:     # Printing result  print ("Nth occurrence of substring at", inilist[occurrence-1])else:  print ("No {} occurrence of substring lies in given string".format(occurrence))
  Method #2: Using find() method 
Python3
# Python code to demonstrate# to find nth occurrence of substring # Initialising valuesini_str = "abababababab"sub_str = "ab"occurrence = 4  # Finding nth occurrence of substringval = -1for i in range(0, occurrence):  val = ini_str.find(sub_str, val + 1)   # Printing nth occurrenceprint ("Nth occurrence is at", val)
  Method #3: Using startswith() and list comprehension 
Python3
# Python code to demonstrate# to find nth occurrence of substring # Initialising valuesini_str = "abababababab"substr = "ab"occurrence = 4  # Finding nth occurrence of substringinilist = [i for i in range(0, len(ini_str))      if ini_str[i:].startswith(substr)] if len(inilist)>= 4:     # Printing result  print ("Nth occurrence of substring at", inilist[occurrence-1])else:  print ("No {} occurrence of substring lies in given string".format(occurrence))    
The Time and Space Complexity is the same for all the methods:
Time Complexity: O(n)
Space Complexity: O(n) (length of the string)
nidhi_biet
harshmaster07705
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert a date format in MySQL?

To convert a date format, use STR_TO_DATE() −
mysql> create table DemoTable2010
(
   DueDate varchar(20)
);
Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2010 values('12/10/2019 12:34:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable2010 values('12/12/2011 11:00:20');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable2010 values('31/01/2017 11:00:20');
Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2010;
This will produce the following output −
+---------------------+
| DueDate             |
+---------------------+
| 12/10/2019 12:34:00 |
| 12/12/2011 11:00:20 |
| 31/01/2017 11:00:20 |
+---------------------+
3 rows in set (0.00 sec)
Here is the query to convert date format −
mysql> select str_to_date(DueDate,'%d/%m/%Y %k:%i') from DemoTable2010;
This will produce the following output −
+---------------------------------------+
| str_to_date(DueDate,'%d/%m/%Y %k:%i') |
+---------------------------------------+
| 2019-10-12 12:34:00                   |
| 2011-12-12 11:00:00                   |
| 2017-01-31 11:00:00                   |
+---------------------------------------+
3 rows in set, 3 warnings (0.00 sec)
yes command in Linux with Examples

08 Nov, 2019
yes command in linux is used to print a continuous output stream of given STRING. If STRING is not mentioned then it prints ‘y’;
Syntax:
yes [STRING]
Note: To stop printing please press Ctrl + C.
Question: Where it is used ?
Ans: Lets say that we want to delete all the .txt file present in the current directory. Instead of writing rm -i *.txt and then typing y at the end for every file, what we can do is we can use yes | rm -i *.txt.
Options:
yes –help : It displays help information.
yes –version : It displays version information.
nidhi_biet
shubham_singh
linux-command
Linux-text-processing-commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
'dd' command in Linux
Start/Stop/Restart Services Using Systemctl in Linux
How to Find Out File Types in Linux
uniq Command in LINUX with examples
mv command in Linux with examples
Tree command in Linux with examples
vi Editor in UNIX
source command in Linux with Examples
Multi-Line Comment in Shell Script
How are variables scoped in C – Static or Dynamic?

12 Sep, 2018
In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack.
For example, output for the below program is 0, i.e., the value returned by f() is not dependent on who is calling it. f() always returns the value of global variable x.
# include <stdio.h>  int x = 0;int f(){   return x;}int g(){   int x = 1;   return f();}int main(){  printf("%d", g());  printf("\n");  getchar();}
References:http://en.wikipedia.org/wiki/Scope_%28programming%29
InathiSirayi
C-Variable Declaration and Scope
C Language
GFacts
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Return values of printf() and scanf() in C/C++
What are the Operators that Can be and Cannot be Overloaded in C++?
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Difference between YOLO and SSD
fseek() vs rewind() in C
HTML | Window innerHeight Property

25 Nov, 2021
The Window innerHeight property is used for returning the height of a window’s content area. It is a read-only property and returns a number which represents the height of the browser window’s content area in pixels.Syntax:  
window.innerHeight
Return Value: It returns a number that represents browser window’s content area height in pixels.
Below program illustrates the Window innerheight Property:Returning the current frame’s height. 
html
<!DOCTYPE html><html><head>    <title>      Window innerHeight Property in HTML    </title>    <style>        h1 {            color: green;        }                 h2 {            font-family: Impact;        }                 body {            text-align: center;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>Window innerHeight Property</h2>        <p>For returning the current frame's height,      double click the "Check Height" button: </p>        <button ondblclick="height()">Check Height</button>    <p id="measure"></p>        <script>        function height() {             var h = window.innerHeight;            document.getElementById("measure").innerHTML                               = "Frame's Height: " + h;        }    </script>   </body> </html>  
Output:  
After clicking the button  
Supported Browsers: The browser supported by Window innerHeight Property are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
ManasChhabra2
HTML-Property
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
MongoDB. max length of field name?

MongoDB supports the BSON format data, so there is no max length of field name. Let us first create a collection with documents −
>db.maxLengthDemo.insertOne({"maxLengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh":"This is demo"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce97ac978f00858fb12e926")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.maxLengthDemo.find();
This will produce the following output.
{ "_id" : ObjectId("5ce97ac978f00858fb12e926"), "maxLengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh" : "This is demo" }
GATE | GATE CS 1999 | Question 43 - GeeksforGeeks

09 Oct, 2017
RAID configurations of disks are used to provide
(A) Fault-tolerance(B) High speed(C) High data density(D) None of the aboveAnswer: (A)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post
GATE CS 1999
GATE-GATE CS 1999
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
How to compare two arrays in JavaScript and make a new one of true and false? JavaScript

We have 2 arrays in JavaScript and we want to compare one with the other to see if the
elements of master array exists in keys array, and then make one new array of the same length
that of the master array but containing only true and false (being true for the values that exists in
keys array and false the ones that don't).
Let’s say, if the two arrays are −
const master = [3,9,11,2,20];
const keys = [1,2,3];
Then the final array should be −
const finalArray = [true, false, false, true, false];
Therefore, let’s write the function for this problem −
const master = [3,9,11,2,20];
const keys = [1,2,3];
const prepareBooleans = (master, keys) => {
   const booleans = master.map(el => {
      return keys.includes(el);
   });
   return booleans;
};
console.log(prepareBooleans(master, keys));
The output in the console will be −
[ true, false, false, true, false ]
C++ Array of Pointers

Before we understand the concept of array of pointers, let us consider the following example, which makes use of an array of 3 integers −
#include <iostream>
 
using namespace std;
const int MAX = 3;
 
int main () {
   int  var[MAX] = {10, 100, 200};
 
   for (int i = 0; i < MAX; i++) {
   
      cout << "Value of var[" << i << "] = ";
      cout << var[i] << endl;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

There may be a situation, when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];

This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. Following example makes use of three integers which will be stored in an array of pointers as follows −
#include <iostream>
 
using namespace std;
const int MAX = 3;
 
int main () {
   int  var[MAX] = {10, 100, 200};
   int *ptr[MAX];
 
   for (int i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; // assign the address of integer.
   }
   
   for (int i = 0; i < MAX; i++) {
      cout << "Value of var[" << i << "] = ";
      cout << *ptr[i] << endl;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

You can also use an array of pointers to character to store a list of strings as follows −
#include <iostream>
 
using namespace std;
const int MAX = 4;
 
int main () {
const char *names[MAX] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali" };

   for (int i = 0; i < MAX; i++) {
      cout << "Value of names[" << i << "] = ";
      cout << (names + i) << endl;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = 0x7ffd256683c0
Value of names[1] = 0x7ffd256683c8
Value of names[2] = 0x7ffd256683d0
Value of names[3] = 0x7ffd256683d8


    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
C++ Stdexcept Library - logic_error

It is a logic error exception and this class defines the type of objects thrown as exceptions to report errors in the internal logical of the program, such as violation of logical preconditions or class invariants.
Following is the declaration for std::logic_error.
class logic_error;
class logic_error;
none
none
constructor − Here the string passed as what_arg has the same content as the value returned by member what.
 Print
 Add Notes
 Bookmark this page
How to use a line break in array values in JavaScript?

To add a line break in array values for every occurrence of ~, first split the array. After splitting, add a line break i.e. <br> for each occurrence of ~.
For example,
This is demo text 1!~This is demo text 2!~~This is demo text 3!
This will add line breaks like the following for ~ occurrence:
This is demo text 1!
This is demo text 2!
This is demo text 3!
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <h2>Adding line break</h2>
      <script>
         var myArray = 'This is demo text 1!~This is demo text 2!~~This is demo text 3!~This is demo text 4!~~This is demo text 5!';
         document.write("Original Array: "+myArray);
         var brk = myArray.split('~');
         var res = brk.join(" <br> ");
         document.write("<br><br>"+res);
      </script>
      <p>Each occurence of ~ adds a line break above.</p>
   </body>
</html>
DAX Text - UPPER function

Converts a text string to all uppercase letters.
UPPER (<text>) 

text
The text that you want to convert to uppercase, or a reference to a column that contains text.
Same text string in upper case.
The characters other than alphabets will not be changed.
= UPPER("ab") returns AB. 
= UPPER("12ab") returns 12AB. 

    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
Showing and Hiding widgets in Tkinter?

Let us suppose that we have to create an application such that we can show as well as hide the widgets whenever we need.
The widgets can be hidden through pack_forget() method.
The widgets can be hidden through pack_forget() method.
To show the hidden widgets, we can use the pack() method.
To show the hidden widgets, we can use the pack() method.
Both methods can be invoked using the lambda or anonymous function.
#Import the required library
from tkinter import *

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

#Define the geometry of the window
win.geometry("650x450")

#Define function to hide the widget
def hide_widget(widget):
   widget.pack_forget()

#Define a function to show the widget
def show_widget(widget):
   widget.pack()

#Create an Label Widget
label= Label(win, text= "Showing the Message", font= ('Helvetica bold', 14))
label.pack(pady=20)

#Create a button Widget
button_hide= Button(win, text= "Hide", command= lambda:hide_widget(label))
button_hide.pack(pady=20)

button_show= Button(win, text= "Show", command= lambda:show_widget(label))
button_show.pack()

win.mainloop()
Running the above code will display a window with two buttons “Show” and “Hide” which can be used to show and hide the widgets.
Now click on “Hide” button to hide the Label Text and “Show” to show the Label Text.
JQuery | map() Method

30 Apr, 2020
This map() Method in jQuery is used to translate all items in an array or object to new array of items.
Syntax:
jQuery.map( array/object, callback )
Parameters: This method accept two parameters which is mentioned above and described below:
array/object: This parameter holds the Array or object to translate.
callback: This parameter holds the function to process each item against.
Return Value: It returns the array.
Below examples illustrate the use of map() method in jQuery:
Example 1: This example use jQuery.map() method and return the square of array element.
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>JQuery | map() method</title>    <script src="https://code.jquery.com/jquery-3.4.1.js">    </script>  </head>  <body style="text-align:center;">      <h1 style="color: green">         GeeksforGeeks     </h1>      <h3>JQuery | map() method</h3>    <b>Array = [2, 5, 6, 3, 8, 9]</b>    <br>    <br>    <button onclick="geek()">Click</button>    <br>    <br>    <b id="root"></b>      <script>        function geek() {            var el = document.getElementById('root');            var arr = [2, 5, 6, 3, 8, 9];              var newArr = jQuery.map(arr, function(val, index) {                return {                    number: val,                    square: val * val                };            })            el.innerHTML = JSON.stringify(newArr);        }    </script></body>  </html>
Output:
Example 2: This example use map() method to concatenate character ‘A’ with every character of name.
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>JQuery | map() method</title>    <script src="https://code.jquery.com/jquery-3.4.1.js">    </script>  </head>  <body style="text-align:center;">      <h1 style="color: green">         GeeksforGeeks     </h1>      <h3>JQuery | map() method</h3>    <b>String = "Shubham"</b>    <br>    <br>    <button onclick="geek()">Click</button>    <br>    <br>    <b id="root"></b>      <script>        function geek() {            var el = document.getElementById('root');            var name = "Shubham";            name = name.split("");              // New array of character and names              // concatenated with 'A'              var newName = jQuery.map(name, function(item) {                return item + 'A<br>';            })            el.innerHTML = newName;        }    </script></body>  </html>                     
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between relative , absolute and fixed position in CSS

23 Jul, 2021
Relative Position: Setting the top, right, bottom, and left properties of an element with position: relative; property will cause it to adjust from its normal position. The other objects or elements will not fill the gap.
Syntax:
position: relative;
Absolute Position: An element with position: absolute; will cause it to adjust its position with respect to its parent. If no parent is present, then it uses the document body as parent.
position: absolute;
Fixed Position:
Position: fixed; property applied to an element will cause it to always stay in the same place even if the page is scrolled. To position the element we use top, right, bottom, left properties.
Syntax:
position: fixed;
Below example illustrates the differences between Relative Position and Absolute Position.
Relative Position:
HTML
<!DOCTYPE html><html> <head>    <style>        div.relative {            position: relative;            left: 50px;            border: 3px solid #73AD21;        }    </style></head> <body>    <h1>position: relative;</h1>     <div class="relative">        This element has position:relative;    </div></body> </html>
Output:
Absolute Position:
HTML
<!DOCTYPE html><html> <head>    <style>        div.relative {            position: relative;            width: 400px;            height: 200px;            border: 3px solid #73AD21;        }                 div.absolute {            position: absolute;            top: 80px;            right: 80px;            width: 200px;            height: 100px;            border: 3px solid #73AD21;        }    </style></head> <body>    <h1>position: absolute;</h1>     <div class="relative">        This element has position: relative;        <div class="absolute">            This element has position: absolute;        </div>    </div></body> </html>
Output:
Fixed Position:
HTML
<!DOCTYPE html><html> <head>  <style>    div.fixed {  position: fixed;  bottom: 0;  right: 0;  width: 300px;  border: 3px solid #73AD21;}    div.absolute {      position: absolute;      top: 150px;      right: 80;      width: 200px;      height: 100px;      border: 3px solid #73AD21;    }  </style></head> <body>   <h1>position: absolute;</h1>     <h2>position: fixed;</h2>    <div class="absolute">This element has position: absolute;</div>  </div> </body> </html>
Output:
aktmishra143
geekyquentin
CSS-Misc
HTML-Misc
CSS
Difference Between
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Python | Detect corner of an image using OpenCV

15 Oct, 2018
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos.
Let’s see how to detect the corner in the image.
cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi method. Note that the image should be a grayscale image. Specify the number of corners you want to find and the quality level (which is a value between 0-1). It denotes the minimum quality of corner below which everyone is rejected. Then provide the minimum Euclidean distance between corners detected.
Syntax : cv2.goodFeaturesToTrack(image, maxCorners, qualityLevel, minDistance[, corners[, mask[, blockSize[, useHarrisDetector[, k]]]]])
Image before corner detection:
# import the required libraryimport numpy as npimport cv2from matplotlib import pyplot as plt    # read the imageimg = cv2.imread('corner1.png')  # convert image to gray scale imagegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # detect corners with the goodFeaturesToTrack function.corners = cv2.goodFeaturesToTrack(gray, 27, 0.01, 10)corners = np.int0(corners)  # we iterate through each corner, # making a circle at each point that we think is a corner.for i in corners:    x, y = i.ravel()    cv2.circle(img, (x, y), 3, 255, -1)  plt.imshow(img), plt.show()
Image after corner detection –
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
HTML | Navigator userAgent Property

19 Aug, 2021
The Navigator userAgent property is used for returning the user-agent header’s value sent to the server by the browser. It returns a string representing values such as the name, version, and platform of the browser.Syntax:  
navigator.userAgent
Return Value: A String, representing the user agent string for the current browser
Below program illustrates the Navigator userAgent Property:  
html
<!DOCTYPE html><html> <head>    <title>      Navigator userAgent Property in HTML    </title>    <style>        h1 {            color: green;        }                 h2 {            font-family: Impact;        }                 body {            text-align: center;        }    </style></head> <body>     <h1>GeeksforGeeks</h1>    <h2>Navigator userAgent Property</h2>      <p>      For checking the browser's User-agent header name,      double click the "Check User Agent" button:    </p>      <button ondblclick="checkua()">      Check User Agent    </button>     <p id="header"></p>      <script>        function checkua() {            var u =                "User-agent header sent by the browser : "                                     + navigator.userAgent;            document.getElementById("header").innerHTML = u;        }    </script> </body> </html>  
Output:  
After clicking the button  
Supported Browsers: The browser supported by Navigator userAgent are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
ManasChhabra2
HTML-Property
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Command line arguments in Java

Sometimes you will want to pass some information on a program when you run it. This is accomplished by passing command-line arguments to main( ).
A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
The following program displays all of the command-line arguments that it is called with -
public class CommandLine {
   public static void main(String args[]) {
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " + args[i]);
      }
   }
}
Try executing this program as shown here -
$java CommandLine this is a command line 200 -100
This will produce the following result -
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Dynamically Resize Buttons When Resizing a Window using Tkinter

Python has many rich libraries for creating and developing GUI-based applications.
Tkinter is one of the most commonly used Python libraries for creating GUI-based
applications. It has many features like adding widgets and other necessary attributes necessary for creating an application.
A button is a widget which can be assigned for some particular task or event. However, to dynamically resize or position the button widget, we can configure its position and layout using the Grid module in tkinter. To resize the button dynamically, we can use rowconfiguration() and coloumnconfiguration() methods.
In a tkinter Grid system, there are four attributes which can be used to resize any widget. These attributes generally refer to the direction such as North, South, East, and West. To make the buttons responsive and dynamically resizable according to the screen or window size, we have to use the row and column property in it.
#Importing the tkinter library
from tkinter import *
win= Tk()
win.title("Dynamically Resize Buttons")
win.geometry("700x500")

#Configure Rows and column

Grid.rowconfigure(win, 0,weight=1)
Grid.columnconfigure(win,0,weight=1)
#Create buttons

b1= Button(win, text= "C++")
b2= Button(win, text= "Java")

#Create List of buttons
bl= [b1, b2]

row_no=0
#Loop through all the buttons and configure it row-wise
for button in bl:
   Grid.rowconfigure(win,row_no, weight=1)
   row_no+=1

#Adjust the position in grid and make them sticky

b1.grid(row=0, column=0, sticky= "nsew")
b2.grid(row=1, column=0, stick= "nsew")

win.mainloop()
Running the above code will generate the output and display two buttons
horizontally in a row−order, which can be dynamically resizable according to screen
or window size.
How to use Compare-Object in PowerShell?

Compare-Object command in PowerShell is used to compare two objects. Objects can be a variable content, two files, strings, etc. This cmdlet uses few syntaxes to show the difference between objects which is called side indicators.
=> - Difference in destination object.
<= - Difference in reference (source) object.
== - When the source and destination objects are equal.
PS C:\> Compare-Object "World" "Alpha"

InputObject SideIndicator
----------- -------------
Alpha =>
World <=
In the above example, the Alpha string shows the right indicator means it is the difference from the source object while the World string shows the left indicator means it is different from the destination string.
The below example won’t show any output because the source and destination reference objects are the same but when you use -IncludeEqual parameter, it will show the equal indicator (==) for the matching object
PS C:\> Compare-Object "World" "woRld"

PS C:\> Compare-Object "World" "woRld" -IncludeEqual

InputObject SideIndicator
----------- -------------
World ==
Please note, Comparison-Object is not case sensitive. For the case-sensitive comparison, use -CaseSensitive parameter.
PS C:\> Compare-Object "World" "woRld" -CaseSensitive


InputObject SideIndicator
----------- -------------
woRld =>
World <=
$sourcefiles = Get-ChildItem C:\Test1 -Recurse
$destfiles = Get-ChildItem C:\Test2\ -Recurse
Compare-Object $sourcefiles $destfiles -IncludeEqual
InputObject SideIndicator
----------- -------------
File1.txt ==
File3.txt =>
File2.txt <=
The above example shows that the file1.txt exists at both locations, while File3.txt is at the destination location but not at the source location and File2.txt exists at the source location but not at the destination location.
If we use -ExcludeDifference parameter, the output won’t be displayed unless we add -IncludeEqual parameter.
Compare-Object $sourcefiles $destfiles -ExcludeDifferent

The below command will display only the files which are matching.
PS C:\> Compare-Object $sourcefiles $destfiles -IncludeEqual -ExcludeDifferent

InputObject SideIndicator
----------- -------------
File1.txt ==
To compare two objects with the specific property name, use -Property parameter. In the below example, we will compare files LastWriteTime.
$sfiles = Get-ChildItem C:\Test1\ -Recurse
$dfiles = Get-ChildItem C:\Test2\ -Recurse

Compare-Object $sfiles $dfiles -Property LastWriteTime -IncludeEqual
LastWriteTime SideIndicator
------------- -------------
8/28/2020 7:27:11 AM ==
8/28/2020 7:29:00 AM =>
8/28/2020 7:49:37 AM <=
If you need the name of any specific property in the output then add that property first and then add the property name to compare. For example,
Compare-Object $sfiles $dfiles -Property Name, LastWriteTime -IncludeEqual

Name LastWriteTime SideIndicator
---- ------------- -------------
File1.txt 8/28/2020 7:27:11 AM ==
File3.txt 8/28/2020 7:29:00 AM =>
File2.txt 8/28/2020 7:49:37 AM <=
How to repair MySQL tables from the command line?

The repair of MySQL tables is only applicable to MyISAM engine type, not for InnoDB. Therefore, we need to change the Engine type to MyISAM.
The following is an example.
Creating a table
mysql> create table RepairTableDemo
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.51 sec)
To convert this table to engine type MyISAM, use ALTER.
mysql> ALTER TABLE RepairTableDemo ENGINE = MyISAM;
Query OK, 0 rows affected (1.14 sec)
Records: 0  Duplicates: 0  Warnings: 0
Inserting records into table.
mysql> insert into RepairTableDemo values(1,'John'),(2,'Carol'),(3,'Johnson');
Query OK, 3 rows affected (0.06 sec)
Records: 3  Duplicates: 0  Warnings: 0
To display all records.
mysql> select *from RepairTableDemo;
The following is the output.
+------+---------+
| id   | name    |
+------+---------+
|    1 | John    |
|    2 | Carol   |
|    3 | Johnson |
+------+---------+
3 rows in set (0.00 sec)

Let us now see the syntax to repair a table.
REPAIR TABLE yourTableName;

The following is the query −
mysql> REPAIR TABLE RepairTableDemo;
Here is the output. It shows that the repair status is fine.
+--------------------------+--------+----------+----------+
| Table                    | Op     | Msg_type | Msg_text |
+--------------------------+--------+----------+----------+
| business.repairtabledemo | repair | status   | OK       |
+--------------------------+--------+----------+----------+
1 row in set (0.10 sec)
Is it possible to synchronize the string type in Java?

A thread is a piece of code (under execution) in a program, which executes a sub task of the process independently. independent process.
In other words, a thread is a light weight process which executes a piece of code independently.
If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access a same resource an issue occurs.
To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access.
synchronized (Lock1) {
   System.out.println("Thread 1: Holding lock 1...");
}
It is not recommended to use objects which are pooled and reused, if you do so there is a chance of getting into deadlock condition down the line.
Since Strings are pooled in String constant pool and reused, it is not suggestable lock String types with Synchronization.
Program to Convert Milliseconds to a Date Format in Java

07 Dec, 2021
Given milliseconds. The task is to write a program in Java to convert Milliseconds to a Date which Displays the date in dd MMM yyyy HH:mm:ss:SSS Z format.The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create Date from milliseconds.The SimpleDateFormat class helps in formatting and parsing of data. We can change the date from one format to other. It allows the user to interpret string date format into a Date object. We can modify Date accordingly.Constructors of SimpleDateFormat:  
SimpleDateFormat(String pattern_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the default FORMAT locale.
SimpleDateFormat(String pattern_arg, Locale locale_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the given FORMAT Locale – locale_arg.
SimpleDateFormat(String pattern_arg, DateFormatSymbols formatSymbols) : Constructs a SimpleDateFormat using the given pattern – pattern_arg and date format symbols.
Below is the program to convert milliseconds to a Date Format in Java:  
Java
// Java program to convert milliseconds// to a Date format import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date; public class SectoDate {    public static void main(String args[])    {         // milliseconds        long milliSec = 3010;         // Creating date format        DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");         // Creating date from milliseconds        // using Date() constructor        Date result = new Date(milliSec);         // Formatting Date according to the        // given format        System.out.println(simple.format(result));    }}
01 Jan 1970 00:00:03:010 +0000
 
adnanirshad158
date-time-program
Java - util package
Java-Date-Time
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.