code-rag-bench/online-tutorials huggingface dataset:
Compare two strings in Julia - cmp() Method - GeeksforGeeks

26 Mar, 2020
The cmp() is an inbuilt function in julia which is used to return 0 if the both specified strings are having the same length and the character at each index is the same in both strings, return -1 if a is a prefix of b, or if a comes before b in alphabetical order and return 1 if b is a prefix of a, or if b comes before a in alphabetical order.
Syntax:cmp(a::AbstractString, b::AbstractString)
Parameters:
a::AbstractString: Specified first string
b::AbstractString: Specified second string
Returns: It returns 0 if the both specified strings are having the same length and the character at each index is the same in both strings, return -1 if a is a prefix of b, or if a comes before b in alphabetical order and return 1 if b is a prefix of a, or if b comes before a in alphabetical order.
Example 1:
# Julia program to illustrate # the use of String cmp() method  # Comparing two strings and # getting the values 0, -1 or 1println(cmp("abc", "abc"))println(cmp("a", "b"))println(cmp("c", "b"))println(cmp("ab", "abc"))println(cmp("abc", "ab"))println(cmp("ab", "ac"))
Output:
0
-1
1
-1
1
-1

Example 2:
# Julia program to illustrate # the use of String cmp() method  # Comparing two strings and # getting the values 0, -1 or 1println(cmp("1", "2"))println(cmp("1", "1"))println(cmp("12", "21"))println(cmp("123", "23"))println(cmp("31", "23"))
Output:
-1
0
-1
-1
1

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Getting the maximum value from a list in Julia - max() Method
Find maximum element along with its index in Julia - findmax() Method
Exception handling in Julia
Getting the absolute value of a number in Julia - abs() Method
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Working with Date and Time in Julia
C / C++ Program for Dijkstra's shortest path algorithm

We are given a graph with a source vertex in the graph. And we have to find the shortest path from the source vertex to all other vertices of the graph.
The Dijikstra’s algorithm is a greedy algorithm to find the shortest path from the source vertex of the graph to the root node of the graph.
Step 1 : Create a set shortPath to store vertices that come in the way of the shortest path tree.
Step 2 : Initialize all distance values as INFINITE and assign distance values as 0 for source vertex so that it is picked first.
Step 3 : Loop until all vertices of the graph are in the shortPath.
   Step 3.1 : Take a new vertex that is not visited and is nearest.
   Step 3.2 : Add this vertex to shortPath.
   Step 3.3 : For all adjacent vertices of this vertex update distances. Now check every adjacent vertex of V, if sum of distance of u and weight of edge is elss the update it.
Based on this algorithm lets create a program.
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
   int min = INT_MAX, min_index;
   for (int v = 0; v < V; v++)
   if (sptSet[v] == false && dist[v] <= min)
      min = dist[v], min_index = v;
   return min_index;
}
int printSolution(int dist[], int n) {
   printf("Vertex Distance from Source\n");
   for (int i = 0; i < V; i++)
      printf("%d \t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
   int dist[V];
   bool sptSet[V];
   for (int i = 0; i < V; i++)
      dist[i] = INT_MAX, sptSet[i] = false;
      dist[src] = 0;
   for (int count = 0; count < V - 1; count++) {
      int u = minDistance(dist, sptSet);
      sptSet[u] = true;
      for (int v = 0; v < V; v++)
         if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v];
   }
   printSolution(dist, V);
}
int main() {
   int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
      { 6, 0, 8, 0, 0, 0, 0, 13, 0 },
      { 0, 8, 0, 7, 0, 6, 0, 0, 2 },
      { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
      { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
      { 0, 0, 6, 14, 10, 0, 2, 0, 0 },
      { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
      { 8, 13, 0, 0, 0, 0, 1, 0, 7 },
      { 0, 0, 2, 0, 0, 0, 6, 7, 0 }
   };
   dijkstra(graph, 0);
   return 0;
}
Vertex Distance from Source
0 0
1 6
2 14
3 21
4 21
5 11
6 9
7 8
8 15
BCD Adder in Digital Logic - GeeksforGeeks

25 Nov, 2019
BCD stand for binary coded decimal. Suppose, we have two 4-bit numbers A and B. The value of A and B can varies from 0(0000 in binary) to 9(1001 in binary) because we are considering decimal numbers.
The output will varies from 0 to 18, if we are not considering the carry from the previous sum. But if we are considering the carry, then the maximum value of output will be 19 (i.e. 9+9+1 = 19).When we are simply adding A and B, then we get the binary sum. Here, to get the output in BCD form, we will use BCD Adder.
Example 1:
Input :
A = 0111  B = 1000 
Output :
Y = 1 0101

Explanation: We are adding A(=7) and B(=8). 
The value of binary sum will be 1111(=15). 
But, the BCD sum will be 1 0101, 
where 1 is 0001 in binary and 5 is 0101 in binary.

Example 2:
Input :
A = 0101  B = 1001
Output :
Y = 1 0100

Explanation: We are adding A(=5) and B(=9). 
The value of binary sum will be 1110(=14). 
But, the BCD sum will be 1 0100, 
where 1 is 0001 in binary and 4 is 0100 in binary.

Note – If the sum of two number is less than or equal to 9, then the value of BCD sum and binary sum will be same otherwise they will differ by 6(0110 in binary).Now, lets move to the table and find out the logic when we are going to add “0110”.
We are adding “0110” (=6) only to the second half of the table.The conditions are:
If C’ = 1 (Satisfies 16-19)If S3′.S2′ = 1 (Satisfies 12-15)If S3′.S1′ = 1 (Satisfies 10 and 11)
If C’ = 1 (Satisfies 16-19)
If S3′.S2′ = 1 (Satisfies 12-15)
If S3′.S1′ = 1 (Satisfies 10 and 11)
So, our logic is
C' + S3'.S2' + S3'.S1' = 1

Implementation :
Read related articles: BCD to 7 Segment Decoder, BCD(8421) to/from Excess-3
shruti_sharma
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IEEE Standard 754 Floating Point Numbers
4-bit binary Adder-Subtractor
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Difference between RAM and ROM
Shift Micro-Operations in Computer Architecture
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Three way partitioning of an array around a given range using Python

Given an array and the range of the array [startval, endval].Array is divided by three parts.
All elements smaller than startval come first.
All elements in range startval to endval come next.
All elements greater than endval appear in the end.
Input: A = [1, 14, 51, 12, 4, 2, 54, 20, 87, 98, 3, 1, 32]
startval = 14, endval = 54
Output: A = [1, 12, 4, 2, 3, 1, 14, 51, 20, 32,54, 87, 98]

Step1: First the list is divided into three parts, first part will contain elements less than startval, second part will contain elements between startval and endval and third part will contain elements greater than endval.
Step2: Concatenate all three parts together.

def partition_array(input, lowVal, highVal):
   # Separate input list in three parts
   my_first = [ num for num in input if num<lowVal ]
   my_second = [ num for num in input if (num>=lowVal and num<=highVal) ]
   my_third = [ num for num in input if num>highVal ]
# concatenate all three parts
print(my_first + my_second + my_third)
# Driver program
if __name__ == "__main__":
   my_input = [10, 140, 50, 200, 40, 20, 540, 200, 870, 980, 30, 10, 320]
   my_lowVal = 140
   my_highVal = 200
   partition_array(my_input, my_lowVal, my_highVal)
[10, 50, 40, 20, 30, 10, 140, 200, 200, 540, 870, 980, 320]
Query in MySQL for string fields with a specific length?

To query for string fields with a specific length, use the char_length() or length() from MySQL.
The syntax is as follows −
Case 1 − Use of char_length()
This can be used when we are taking length in a number of characters.
The syntax −
select *from yourTableName where
char_length(yourColumnName)=anySpecificLengthValue;
Case 2 − Use of length()
This can be used when we are taking the length in bytes.
The syntax −
select *from yourTableName where length(yourColumnName)=anySpecificLengthValue;
To understand the above concept, let us first create a table. The query to create a table is as follows −
mysql> create table StringWithSpecificLength
-> (
-> Id int,
-> Name varchar(100),
-> FavouriteLanguage varchar(50)
-> );
Query OK, 0 rows affected (0.52 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into StringWithSpecificLength values(1,'John','Java');
Query OK, 1 row affected (0.66 sec)

mysql> insert into StringWithSpecificLength values(2,'Bob','PHP');
Query OK, 1 row affected (0.17 sec)

mysql> insert into StringWithSpecificLength values(3,'Carol','Python');
Query OK, 1 row affected (0.16 sec)

mysql> insert into StringWithSpecificLength values(4,'Sam','Ruby');
Query OK, 1 row affected (0.25 sec)

mysql> insert into StringWithSpecificLength values(5,'Mike','Pascal');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from StringWithSpecificLength;
+------+-------+-------------------+
| Id   | Name  | FavouriteLanguage |
+------+-------+-------------------+
|    1 | John  | Java              |
|    2 | Bob   | PHP               |
|    3 | Carol | Python            |
|    4 | Sam   | Ruby              |
|    5 | Mike  | Pascal            |
+------+-------+-------------------+
5 rows in set (0.00 sec)
The following is the query to fetch string fields with specific length −
mysql> select *from StringWithSpecificLength where char_length(FavouriteLanguage)=6;
+------+-------+-------------------+
| Id    | Name | FavouriteLanguage |
+------+-------+-------------------+
| 3    | Carol | Python            |
| 5    | Mike  | Pascal            |
+------+-------+-------------------+
2 rows in set (0.00 sec)
Simple way to find if two different lists contain exactly the same elements in Java

Two lists are equal if they consist of same number of elements in the same order.
Let’s say we have the following two lists −
List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 });
List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120});
Now, let’s find out whether both the lists are equal or not −
arrList1.equals(arrList2);
If both the above lists have equal elements, then TRUE is returned, else FALSE is the return value.
 Live Demo
import java.util.Arrays;
import java.util.List;
public class Demo {
   public static void main(String[] a) {
      List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 });
      List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120});
      List<Integer>arrList3 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100});
      System.out.println("Are List 1 and List2 equal? "+arrList1.equals(arrList2));
      System.out.println("Are List 2 and List3 equal? "+arrList2.equals(arrList2));
      System.out.println("Are List 1 and List3 equal? "+arrList1.equals(arrList3));
   }
}
Are List 1 and List2 equal? false
Are List 2 and List3 equal? true
Are List 1 and List3 equal? true
Can you cast a Byte object to a double value in java?

Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects).
Converting one primitive data type into another is known as type casting. There are two types of casting −
Widening− Converting a lower datatype to a higher datatype is known as widening. It is done implicitly.
Narrowing− Converting a higher datatype to a lower datatype is known as narrowing. You need to do it explicitly using the cast operator (“( )”).
For every primitive variable a wrapper class is available, the objects of these wrapper classes wraps their respective primitive variable.
Autoboxing− The implicit conversion of a primitive variable to its wrapper class object is known as autoboxing.
Integer i = 20;
Unboxing− In the same way the conversion of a wrapper class object to a primitive variable is known as unboxing.
int i = new Integer(400);
Yes, you can cast Byte object to a double value, to do so, you just need to assign byte object to byte variable, internally it will be −
Unboxed as primitive byte value.
And, implicitly casted to double (widening).
 Live Demo
import java.util.Scanner;
public class CastingExample {
   public static void main(String args[]){
      //Reading a byte value form user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a byte value: ");
      byte by = sc.nextByte();
      //Creating a Byte object using the obtained value
      Byte byteObject = new Byte(by);
      //Converting the byte object into a double
      double d = byteObject;
      //Printing the result
      System.out.println("double value: "+d);
   }
}
Enter a byte value:
24
double value: 24.0
How to cut part of a string with a MySQL query?

For this, use substring_index() function from MySQL. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('STU-1011');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('STU-95968686');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| StudentId    |
+--------------+
| STU-1011     |
| STU-95968686 |
+--------------+
2 rows in set (0.00 sec)
Following is the query to cut part of a string in MySQL before hyphen (-) −
mysql> select substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) from DemoTable;
This will produce the following output displaying part of the string before hyphen (-)
+------------------------------------------------------------------------+
| substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) |
+------------------------------------------------------------------------+
| 1011                                                                   |
| 95968686                                                               |
+------------------------------------------------------------------------+
2 rows in set (0.02 sec)
Comparing corresponding values of two arrays in JavaScript

Suppose we have two array of numbers of the same length like this −
const arr1 = [23, 67, 12, 87, 33, 56, 89, 34, 25];
const arr2 = [12, 60, 45, 54, 67, 84, 36, 73, 44];
We are required to write a JavaScript function that takes in two such arrays as the first and the second argument. The function should then compare the corresponding values of both the arrays, and the function should return −
-1, if the count of corresponding numbers greater in the first array than the second array are more than corresponding numbers greater in the second array
-1, if the count of corresponding numbers greater in the first array than the second array are more than corresponding numbers greater in the second array
1, if the count of corresponding numbers greater in the second array than the first array are more than the corresponding numbers greater in the first array.
1, if the count of corresponding numbers greater in the second array than the first array are more than the corresponding numbers greater in the first array.
0, if both the counts are equal.
0, if both the counts are equal.
For example −
For the above arrays, the output should be −
const output = 1;
because arr1 has 4 greater corresponding elements while arr2 has 5 greater corresponding elements.
The code for this will be −
 Live Demo
const arr1 = [23, 67, 12, 87, 33, 56, 89, 34, 25];
const arr2 = [12, 60, 45, 54, 67, 84, 36, 73, 44];
const findDominance = (arr1 = [], arr2 = []) => {
   if(arr1.length !== arr2.length){
      return;
   };
   let count = 0;
   for(let i = 0; i < arr1.length; i++){
      const el1 = arr1[i];
      const el2 = arr2[i];
      const diff = el2 - el1;
      console.log(diff)
      count += diff / Math.abs(diff);
   };
   return count / Math.abs(count);
};
console.log(findDominance(arr1, arr2));
And the output in the console will be −
-11
-7
33
-33
34
28
-53
39
19
1
Tryit Editor v3.6 - Show Node.js

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  //Open a file on the server and return its content:
  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
How to get raw content from a string including carriage return ? - GeeksforGeeks

05 Jun, 2020
The raw content of a string includes the carriage returns, i.e. it contains the new line escape sequence.
Note: The line feed, represented by “\n” and a carriage return “\r” are very different. A line feed means moving the cursor one line forward. A carriage return means moving the cursor to the beginning of the line. Windows editors still use the combination of both as ‘\r\n’ in text files. Unix uses mostly only the ‘\n’. For simplicity, we will consider line breaks as ‘\n’, i.e., move to the next line.
The conversion of the string to its raw form can be done using two methods that are discussed below:
Method 1: Using JSON.stringify() method: The JSON.stringify() method is used to convert a JavaScript object or value to a JSON string. The below example represents how the raw content can be obtained using this method:
javascript
<script>// Define the original stringconst str = 'Geeks\nFor\nGeeks';  console.log('Original String:');console.log(str);console.log('');  // Find the raw content// using JSON.stringify()console.log('Raw content:');console.log(JSON.stringify(str));</script>
Output:
Original String:
Geeks
For
Geeks

Raw Content:
"Geeks\nFor\nGeeks"
Method 2: Using string.replace() method: The string.replace() method is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Regular expressions are used to replace the needed parts of the string. The ‘g’ parameter in the regular expression make sure that all ‘\n’ characters are converted to their raw forms.
 The below example represents how the raw content can be obtained using this method:
javascript
<script>// Define the original stringconst str = 'Geeks\nFor\nGeeks';  console.log('Original String:');console.log(str);console.log('');  // Find the raw content// using JSON.stringify()console.log('Raw content:');console.log(str.replace(/\n/g, `\\n`));</script>
Output:
Original String:
Geeks
For
Geeks

Raw Content:
"Geeks\nFor\nGeeks"
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to update a Timestamp and set to current date in MongoDB?

To update, use update() in MongoDB. To set it to current date, you need to get the current date −
var todayDate = new Date();
Let us first create a collection with documents −
> db.demo644.insertOne({"ShippingDate":new ISODate("2018-04-19")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c76896c954c74be91e6e6")
}
> db.demo644.insertOne({"ShippingDate":new ISODate("2019-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c76966c954c74be91e6e7")
}
Display all documents from a collection with the help of find() method −
> db.demo644.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate" : ISODate("2018-04-19T00:00:00Z") }
{ "_id" : ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate" : ISODate("2019-01-10T00:00:00Z") }
Following is the query to update timestamp −
> var todayDate = new Date();
> todayDate .setHours(todayDate.getHours() + 1);
1587315898453
> db.demo644.update({}, {$set: {ShippingDate:todayDate}}, {multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Display all documents from a collection with the help of find() method −
> db.demo644.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate" : ISODate("2020-04-19T17:04:58.453Z") }
{ "_id" : ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate" : ISODate("2020-04-19T17:04:58.453Z") }
Pascal - Variants

Pascal supports a unique type of storage named variants.  You can assign any simple type of values in a variant variable. The type of a value stored in a variant is only determined at runtime. Almost any simple type can be assigned to variants: ordinal types, string types, int64 types.
Structured types such as sets, records, arrays, files, objects and classes are not assignment-compatible with a variant.  You can also assign a pointer to a variant.
Free Pascal supports variants.
You can declare variant type like any other types using the var keyword. The syntax for declaring a variant type is −
var
   v: variant;
Now, this variant variable v can be assigned to almost all simple types including the enumerated types and vice versa.
type  
   color = (red, black, white);  
var  
   v : variant;  
   i : integer;  
   b : byte;  
   w : word;  
   q : int64;  
   e : extended;  
   d : double;  
   en : color;  
   as : ansistring;  
   ws : widestring;  

begin  
   v := i;  
   v := b;  
   v := w;  
   v := q;  
   v := e;  
   v := en;  
   v := d:  
   v := as;  
   v := ws;  
end;
The following example would illustrate the concept −
Program exVariant;

uses variants;
type
   color = (red, black, white);

var
   v : variant;
   i : integer;
   r: real;
   c : color;
   as : ansistring;


begin
   i := 100;
   v:= i;
   writeln('Variant as Integer: ', v);

   r:= 234.345;
   v:= r;
   writeln('Variant as real: ', v);

   c := red;
   v := c;
   writeln('Variant as Enumerated data: ', v);

   as:= ' I am an AnsiString';
   v:= as;
   writeln('Variant as AnsiString: ', v);
end.
When the above code is compiled and executed, it produces the following result −
Variant as Integer: 100
Variant as real: 234.345
Variant as Enumerated data: 0
Variant as AnsiString: I am an AnsiString


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
C library function - strpbrk()

The C library function char *strpbrk(const char *str1, const char *str2)  finds the first character in the string str1 that matches any character specified in str2. This does not include the terminating null-characters.
Following is the declaration for strpbrk() function.
char *strpbrk(const char *str1, const char *str2)
str1 − This is the C string to be scanned.
str1 − This is the C string to be scanned.
str2 − This is the C string containing the characters to match.
str2 − This is the C string containing the characters to match.
This function returns a pointer to the character in str1 that matches one of the characters in str2, or NULL if no such character is found.
The following example shows the usage of strpbrk() function.
#include <stdio.h>
#include <string.h>

int main () {
   const char str1[] = "abcde2fghi3jk4l";
   const char str2[] = "34";
   char *ret;

   ret = strpbrk(str1, str2);
   if(ret) {
      printf("First matching character: %c\n", *ret);
   } else {
      printf("Character not found");
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
First matching character: 3


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Dictionary.ContainsValue() Method in C#

The Dictionary.ContainsValue() method in C# is used to check whether the Dictionary<TKey,TValue> contains a specific value or not.
public bool ContainsValue (TValue val);
Above, Val is the value to be searched.
Let us now see an example to implement the Dictionary.ContainsValue() method −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      if (dict.ContainsValue("Kevin"))
         Console.WriteLine("Value found!");
      else
         Console.WriteLine("Value isn't in the dictionary!");
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Value found!
Cleared Key/value pairs...
Count of elements now = 0
Let us now see another example to implement the Dictionary.ContainsValue() method −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Chris");
      dict.Add("Two", "Steve");
      dict.Add("Three", "Messi");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      if (dict.ContainsValue("Angelina"))
         Console.WriteLine("Value found!");
      else
         Console.WriteLine("Value isn't in the dictionary!");
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}

This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value isn't in the dictionary!
Cleared Key/value pairs...
Count of elements now = 0
How to apply CROSS JOIN correctly in MySQL?

The CROSS JOIN in MySQL returns the Cartesian product of rows from the joined tables. Let us see an example by creating a table −
mysql> create table PairDemo
    -> (
    -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> UserName varchar(20),
    -> UserRelationshipName varchar(20)
    -> );
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into PairDemo(UserName,UserRelationshipName) values('John','James');
Query OK, 1 row affected (0.15 sec)
mysql> insert into PairDemo(UserName,UserRelationshipName) values('Carol','James');
Query OK, 1 row affected (0.20 sec)
mysql> insert into PairDemo(UserName,UserRelationshipName) values('Carol','David');
Query OK, 1 row affected (0.25 sec)
mysql> insert into PairDemo(UserName,UserRelationshipName) values('Sam','David');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from PairDemo;
+--------+----------+----------------------+
| UserId | UserName | UserRelationshipName |
+--------+----------+----------------------+
|      1 |     John |                James |
|      2 |    Carol |                James |
|      3 |    Carol |                David |
|      4 |      Sam |                David |
+--------+----------+----------------------+
4 rows in set (0.00 sec)
The following is the query to apply CROSS JOIN −
mysql> SELECT U.UserName, UR.UserRelationshipName
    -> FROM (
    -> (SELECT DISTINCT UserName from PairDemo) U
    -> CROSS JOIN
    -> (SELECT DISTINCT UserRelationshipName from PairDemo) UR
    -> ) WHERE NOT EXISTS (
    -> SELECT * FROM PairDemo tbl
    -> WHERE tbl.UserName = U.UserName
    -> AND tbl.UserRelationshipName = UR.UserRelationshipName
    -> ) ;
Here is the output that displays the result of the above query implementing CROSS JOIN −
+----------+----------------------+
| UserName | UserRelationshipName |
+----------+----------------------+
|      Sam |                James |
|     John |                David |
+----------+----------------------+
2 rows in set (0.03 sec)
\varepsilon - Tex Command

\varepsilon - Used to create varepsilon symbol.
{ \varepsilon}
\varepsilon command draws varepsilon symbol.

\varepsilon

ε



\varepsilon

ε


\varepsilon

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Majority Element in Python

Let’s suppose we have an array of integers. The task is to find the index of a particular element in the given array. For example,
Input-1 −
N = 8 A[ ] = { 1,2,4,3,3,1,1,5}
Output −
1
Explanation − In the given array of integers, the most appearing number is ‘1’. Thus the output is ‘1’.
Input-2 −
N = 6 A[ ] = {1,5,4,4,1,1}
Output −
1
Explanation − In the given array of integers, the most appearing number is ‘1’. Thus we can return the output ‘1’.
The given array contains multiple integers in which we have to find the most frequent element present in the array. To solve this problem in linear time O(n) and Linear Space O(n) we can use the approach of a hashmap.
In this approach, we will create an unordered map(STL Library) consist of key-value pair in which the key will be an element and the Value will be the occurrence of the element. While traversing through the map we will find the maximum occurrence of the number and return the number as Output.
Take Input an array of size N
Take Input an array of size N
An Integer function maxOccurrence(int A[], int size) takes an array and its size as an input and returns the numbers with maximum frequency.
An Integer function maxOccurrence(int A[], int size) takes an array and its size as an input and returns the numbers with maximum frequency.
Creating a hashmap of all the elements of the array by taking the key as an element and value as its frequency.
Creating a hashmap of all the elements of the array by taking the key as an element and value as its frequency.
Iterating over the map and checking if any of the elements having the most frequency then return the result as the number. Otherwise, if there is not any number present in the array then return ‘-1’.
Iterating over the map and checking if any of the elements having the most frequency then return the result as the number. Otherwise, if there is not any number present in the array then return ‘-1’.
 Live Demo
def checkMajorityElement(arr, N):
   mp = {}
   for i in range(0, N):
      if arr[i] in mp.keys():
         mp[arr[i]] += 1
      else:
         mp[arr[i]] = 1
   for key in mp:
      if mp[key] > (N / 2):
         return key
   return -1
print("Enter size of array:")
N = int(6)
print("Enter elements of array:")
arr = [2,1,1,2,2,2]
ans = checkMajorityElement(arr, N)
if ans != -1:
   print("Majority Element is: %d" % ans)
else:
   print("No majority element in array")
Running the above code will generate the output as,
Enter size of array: 6
Enter elements of array: 2 1 1 2 2 2
Majority Element is: 2
p5.js | getLevel() Function - GeeksforGeeks

17 Jan, 2020
The getLevel() function is an inbuilt function in p5.js library. This function is used to returns a single Amplitude reading at the moment it is called. For continuous readings, you can run in the draw loop.
Syntax:
getLevel(channel)
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.
Parameter: This function accepts a single parameter as mentioned above and described below:
channel: This parameter is use to return channel that is Boolean value 0 means left and 1 means right, it is optional.
Below example illustrates the p5.getLevel() function in JavaScript:
function preload(){  sound1 = loadSound('song.mp3');  sound2 = loadSound('pfivesound.mp3');}function setup(){  amplitude = new p5.Amplitude();  sound1.play();  sound2.play();  amplitude.setInput(sound2);}function draw() {  background(255);  fill(200);  let gfg = amplitude.getLevel();  let size = map(gfg, 0, 1, 0, 400);  ellipse(width/1, height/1, size*2, size*2);}function mousePressed(){  sound2.pause();}   function mouseReleased(){  sound2.play();}
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Supported Browsers: The browsers supported by p5.js getLevel() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Draw Multiple Graphs and Lines in Same Plot in R - GeeksforGeeks

06 Jun, 2021
A visualization can sometimes make more sense when multiple graphs and line plots are combined into one plot. In this article, we will discuss how we can do the same in the R programming language.
Base R supports certain methods that can be used to generate the desired plot. In this example plot, a scatter plot, a line plot, and a bar graph in the same frame for the same data. 
barplot() function is used to produce a barplot with appropriate parameters.
Syntax:
barplot(H, xlab, ylab, main, names.arg, col)
Parameters:
H: This parameter is a vector or matrix containing numeric values which are used in bar chart.
xlab: This parameter is the label for x axis in bar chart.
ylab: This parameter is the label for y axis in bar chart.
main: This parameter is the title of the bar chart.
names.arg: This parameter is a vector of names appearing under each bar in bar chart.
col: This parameter is used to give colors to the bars in the graph.
points() function in R Language is used to add a group of points of specified shapes, size and color to an existing plot.
Syntax: points(x, y, cex, pch, col)
Parameters:x, y: Vector of coordinatescex: size of pointspch: shape of pointscol: color of points
lines() function in R Language is used to add lines of different types, color, and width to an existing plot.
Syntax: lines(x, y, col, lwd, lty)
Parameters:x, y: Vector of coordinatescol: Color of linelwd: Width of linelty: Type of line
The idea is simple and straightforward. Methods to add different visualizations just needs to be added to the code one by one, the plot will interpret each function and draw the plot accordingly.
Example:
R
df<-data.frame(x = c("A","B","C","D","E","F","G"),               y = c(10,23,32,65,16,89,78))  barplot(df$y, xlab = df$x, col = "yellow")points(df$x, df$y, type = "o",col = "blue")lines(df$x, df$y)
Output:
ggplot is a library supported by R which visualization easier. This again can be used to combine multiple graphs into one. A plot is generalized using ggplot() function and then all plots are added to the same plot using + sign.
Here, geom_bar() is used to draw the bar plot, geom_line() is used to draw the line chart and geom_point() is used for scatter plot.
Example:
R
library(ggplot2)  df<-data.frame(x = c("A","B","C","D","E","F","G"),               y = c(10,23,32,65,16,89,78),)  ggplot(df, aes(x, y, group = 1))+geom_bar(stat = "identity")+geom_line(color = "green")+geom_point(color = "blue")
Output:
Picked
R-Charts
R-ggplot
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Logistic Regression in R Programming
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
How to change the order of bars in bar chart in R ?
R - if statement
Replace Specific Characters in String in R
How to list non-hidden files and directories in windows using Python?

On Unix OS(OSX, Linux, etc) hidden files start with a '.' so we can filter them out using a simple startswith check. On windows, we need to check file attributes and then determine whether the file is hidden or not.
For example, you can use the following code to get a listing without hidden files:
import os
if os.name == 'nt':
    import win32api, win32con
def file_is_hidden(p):
    if os.name== 'nt':
        attribute = win32api.GetFileAttributes(p)
        return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
    else:
        return p.startswith('.') #linux-osx
file_list = [f for f in os.listdir('.') if not file_is_hidden(f)]
print(file_list)
How to remove last array element in JavaScript and return it?

To remove last array element in JavaScript, use the pop() method. JavaScript array pop() method removes the last element from an array and returns that element.
You can try to run the following code to remove last array element −
Live Demo
<html>
   <head>
      <title>JavaScript Array pop Method</title>
   </head>
   <body>
      <script>
         var numbers = [40, 70, 80, 100];
         var element = numbers.pop();
         document.write("element is : " + element );
         var element = numbers.pop();
         document.write("<br />element is : " + element );
      </script>
   </body>
</html>
element is : 100
element is : 80
Java program to print a multiplication table for any number

Following is a Java program which accepts an integer variable from user and prints the multiplication table of that particular integer.
import java.util.Scanner;
public class MultiplicationTable {
   public static void main(String args[]) {
      System.out.println("Enter an integer variable :: ");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();
      for(int i=1; i<= 20; i++) {
         System.out.println(""+num+" X "+i+" = "+(num*i));
      }
   }
}
Enter an integer variable ::
17
17 X 1 = 17
17 X 2 = 34
17 X 3 = 51
17 X 4 = 68
17 X 5 = 85
17 X 6 = 102
17 X 7 = 119
17 X 8 = 136
17 X 9 = 153
17 X 10 = 170
17 X 11 = 187
17 X 12 = 204
17 X 13 = 221
17 X 14 = 238
17 X 15 = 255
17 X 16 = 272
17 X 17 = 289
17 X 18 = 306
17 X 19 = 323
17 X 20 = 340
How to write long strings in Multi-lines C/C++?

Long strings can be written in multiple lines by using two double quotes ( “ “ ) to break the string at any point in the middle.
A program that demonstrates this in C is given as follows.
 Live Demo
#include <stdio.h>
int main() {
   char *str = "This is the method "
               "to write long strings "
               "in multiple lines in C";
   puts(str);
   return 0;
}
The output of the above program is as follows.
This is the method to write long strings in multiple lines in C
Now let us understand the above program.
The string str can be written in multiple lines by using two double quotes ( “ “ ) to break the string at any point in the middle. Then the string is displayed using puts. The code snippet that shows this is as follows.
char *str = "This is the method "
"to write long strings "
"in multiple lines in C";
puts(str);
jQuery - parent( [selector] ) Method

The parent( [selector] ) method gets the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
Here is the simple syntax to use this method −
selector.parent( [selector] )

Here is the description of all the parameters used by this method −
selector − This is optional selector to filter the parent with.
selector − This is optional selector to filter the parent with.
Following is a simple example a simple showing the usage of this method.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function(){
            $("p").parent().addClass('hilight');
         });
      </script>
		
      <style>
         .hilight { background:yellow; }
      </style>
   </head>
	
   <body>
      <scan>Top Element</scan>
      <div>
         <div>sibling<div>child</div></div>
         <p>sibling</p>
         <scan>sibling</scan>
      </div>
   </body>
</html>
This will produce following result −
sibling
Following is a simple example a simple showing the usage of this method.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function(){
            $("p").parent().addClass('hilight');
         });
      </script>
		
      <style>
         .hilight { background:yellow; }
      </style>
   </head>
	
   <body>
      <scan>Top Element</scan>
      <div class = "hilight">
         <div>sibling<div>child</div></div>
         <p>sibling</p>
         <scan>sibling</scan>
      <div>
   </body>
</html>
This will produce following result −
sibling

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
PyQt5 - QMessageBox

QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number.
Important methods and enumerations associated with QMessageBox class are given in the following table −
setIcon()
Displays predefined icon corresponding to severity of the message
Question
Information
Warning
Critical
setText()
Sets the text of the main message to be displayed
setInformativeText()
Displays additional information
setDetailText()
Dialog shows a Details button. This text appears on clicking it
setTitle()
Displays the custom title of dialog
setStandardButtons()
List of standard buttons to be displayed. Each button is associated with
QMessageBox.Ok 0x00000400
QMessageBox.Open 0x00002000
QMessageBox.Save 0x00000800
QMessageBox.Cancel 0x00400000
QMessageBox.Close 0x00200000
QMessageBox.Yes 0x00004000
QMessageBox.No 0x00010000
QMessageBox.Abort 0x00040000
QMessageBox.Retry 0x00080000
QMessageBox.Ignore 0x00100000
setDefaultButton()
Sets the button as default. It emits the clicked signal if Enter is pressed
setEscapeButton()
Sets the button to be treated as clicked if the escape key is pressed
In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog.
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")

setStandardButton() function displays desired buttons.
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal.
msg.buttonClicked.connect(msgbtn)

The complete code for the example is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Show message!")
   
   b.move(100,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt MessageBox demo")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   msg = QMessageBox()
   msg.setIcon(QMessageBox.Information)
   
   msg.setText("This is a message box")
   msg.setInformativeText("This is additional information")
   msg.setWindowTitle("MessageBox demo")
   msg.setDetailedText("The details are as follows:")
   msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
   msg.buttonClicked.connect(msgbtn)

   retval = msg.exec_()

def msgbtn(i):
   print ("Button pressed is:",i.text())

if __name__ == '__main__':
   window()
The above code produces the following output. Message Box pops up when main windows’ button is clicked −
If you click on Ok or Cancel button on MessageBox, the following output is produced on the console −
Button pressed is: OK
Button pressed is: Cancel


    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page