code-rag-bench/online-tutorials huggingface dataset:
Apex - nested if statement

We can also have the nested if-else statement for complex condition as given below −
if boolean_expression_1 {
   /* Executes when the boolean expression 1 is true */
   if boolean_expression_2 {
      /* Executes when the boolean expression 2 is true */
   }
}

String pinCode = '12345';
String customerType = 'Premium';
if (pinCode == '12345') {
   System.debug('Condition met and Pin Code is'+pinCode);
   if(customerType = 'Premium') {
      System.debug('This is a Premium customer living in pinCode 12345');
   }else if(customerType = 'Normal') {
      System.debug('This is a Normal customer living in pinCode 12345');
   }
}else {
   //this can go on as per the requirement
   System.debug('Pincode not found');
}

    14 Lectures 
     2 hours 

 Vijay Thapa

    7 Lectures 
     2 hours 

 Uplatz

    29 Lectures 
     6 hours 

 Ramnarayan Ramakrishnan

    49 Lectures 
     3 hours 

 Ali Saleh Ali

    10 Lectures 
     4 hours 

 Soham Ghosh

    48 Lectures 
     4.5 hours 

 GUHARAJANM
 Print
 Add Notes
 Bookmark this page
How to remove a specific element from array in MongoDB?

To remove a specific element, use $pull. Let us create a collection with documents −
> db.demo125.insertOne({"ListOfNames":["John","Chris","Bob","David","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f304068e7f832db1a7f55")
}
Display all documents from a collection with the help of find() method −
> db.demo125.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e2f304068e7f832db1a7f55"),
   "ListOfNames" : [
      "John",
      "Chris",
      "Bob",
      "David",
      "Carol"
   ]
}
Following is the query to remove a specific element from array in MongoDB −
> db.demo125.update(
... { },
... { $pull: { ListOfNames: { $in: [ "David"] }} },
... { multi: true }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo125.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e2f304068e7f832db1a7f55"),
   "ListOfNames" : [
      "John",
      "Chris",
      "Bob",
      "Carol"
   ]
}
Tryit Editor v3.7

Tryit: Some HEX color values
C++ Program for sorting variables of any data type

We are given with the values of different datatypes like it can be of type integer, float, string, bool, etc. and the task is to sort the variables of any data type using one common method or function and display the result.
In C++, we can use std::sort to sort any type of array which is available in C++ standard template library(STL). By default sort function sorts the array element in ascending order. Sort() function takes three arguments −
Start element in the array list i.e. from where you want to start your sort
End element in the array list i.e. till where you want your sorting to be done
Change the default setting of sort function to descending order by passing the greater() function to sort in descending order.
Input-: int arr[] = { 2, 1, 5, 4, 6, 3}
Output-: 1, 2, 3, 4, 5, 6

Input-: float arr[] = { 30.0, 21.1, 29.0, 45.0}
Output-: 21.1, 29.0, 30.0, 45.0

Input-: string str =  {"tutorials point is best", "tutorials point", "www.tutorialspoint.com"}
Output-: tutorials point   tutorials point is best   www.tutorialspoint.com
 
Approach used in the below program is as follows −
Input the variables of different data types like integer, float, string, etc.
Apply the sort() function that will sort the elements of any type of array
Print the results
Start
Step 1-> create template class for operating upon different type of data Template <class T>
Step 2-> Create function to display the sorted array of any data type
   void print(T arr[], int size)
   Loop For size_t i = 0 and i < size and ++i
      print arr[i]
   End
Step 3-> In main()
   Declare variable for size of an array int num = 6
   Create an array of type integer int arr[num] = { 10, 90, 1, 2, 3 }
   Call the sort function sort(arr, arr + num)
   Call the print function print(arr, num)
   Create an array of type string string str[num] = { "tutorials point is best",  "tutorials point", "www.tutorialspoint.com" }
   Call the sort function sort(str, str + num)
   Call the print function print(str, num)
   Create an array of type float float float_arr[num] = { 32.0, 12.76, 10.00 }
   Call the sort function sort(float_arr, float_arr+num)
   Call the print function print(float_arr, num)
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
// creating variable of template class
template <class T>
void print(T arr[], int size) {
   for (size_t i = 0; i < size; ++i)  
   cout << arr[i] << "   ";    
   cout << endl;
}
int main() {
   int num = 6;
   int arr[num] = { 10, 90, 1, 2, 3 };
   sort(arr, arr + num);
   print(arr, num);
   string str[num] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.com" };
   sort(str, str + num);
   print(str, num);
   float float_arr[num] = { 32.0, 12.76, 10.00 };
   sort(float_arr, float_arr+num);
   print(float_arr, num);
   return 0;
} 
0   1   2   3 10   90
tutorials point   tutorials point is best   www.tutorialspoint.com
10   12.76   32
Add more than one shadow to a text with CSS

Add the comma-separated list of shadows to add more than one shadow, with the text-shadow property. You can try to run the following to learn how to add multiple shadows in a single line
Example
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         h1 {
            text-shadow: 0 0 3px red, 0 0 4px green, 0 0 5px blue;
         }
      </style>
   </head>
   <body>
      <h1>Heading One</h1>
      <p>Above heading has multiple text shadow effects.</p>
   </body>
</html>
Scala List iterator() method with example - GeeksforGeeks

29 Jul, 2019
The iterator method is utilized to give an iterator.
Method Definition: def iterator: Iterator[A]
Return Type: It returns a non-empty iterator for non-empty list and returns an empty iterator for empty list.
Example #1:
// Scala program of iterator// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 2, 3, 4, 5)                  // Applying iterator method        val result = m1.iterator                  // Displays output        println(result)              }}
non-empty iterator

Example #2:
// Scala program of iterator// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating an empty list        val m1 = List()                   // Applying iterator method        val result = m1.iterator                  // Displays output        println(result)          }}
empty iterator

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Map
Scala List contains() method with example
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Throw Keyword in Scala
Scala | Arrays
How to get the first element of List in Scala
Lambda Expression in Scala
Enumeration in Scala
Scala String replace() method with example
Calculate difference between adjacent elements in given list using Python

In this article we will see how we create a new list from a given list by subtracting the values in the adjacent elements of the list. We have various approaches to do that.
In this approach we iterate through list elements by subtracting the values using their index positions and appending the result of each subtraction to a new list. We use the range and len function to keep track of how many iterations to do.
 Live Demo
listA= [25, 97, 13, 62, 14, 102]

print("Given list:\n",listA)
list_with_diff = []
for n in range(1, len(listA)):
   list_with_diff.append(listA[n] - listA[n-1])
print("Difference between adjacent elements in the list: \n",
   list_with_diff)
Running the above code gives us the following result −
Given list:
[25, 97, 13, 62, 14, 102]
Difference between adjacent elements in the list:
[72, -84, 49, -48, 88]
In the next approach we create a for loop to find the difference between the adjacent elements and keep appending the result to a new list.
 Live Demo
listA= [25, 97, 13, 62, 14, 102]

print("Given list:\n",listA)
list_with_diff = []
for i, j in zip(listA[0::], listA[1::]):
   list_with_diff.append(j - i)
print("Difference between adjacent elements in the list: \n",
   list_with_diff)
Running the above code gives us the following result −
Given list:
[25, 97, 13, 62, 14, 102]
Difference between adjacent elements in the list:
[72, -84, 49, -48, 88]
How to press ENTER inside an edit box in Selenium?

Selenium gives Enum Key macros to perform the enter action.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class PressEnter {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = " https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // Keys.ENTER passed through sendKeys() method
      driver.findElement(By.className("gsc-input")).sendKeys("Keys.ENTER");
      driver.close();
   }
}
CSS Image Opacity / Transparency

The opacity property specifies the opacity/transparency of an element.
The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent:
opacity 0.2
opacity 0.5
opacity 1(default)
The opacity property is often used together with the :hover 
selector to change the opacity on mouse-over:
The first CSS block is similar to the code in Example 1. In addition, we have added what should happen when a user hovers over one of the images. In this case we want the image to NOT be transparent when the user hovers over it. The CSS for this is opacity:1;.
When the mouse pointer moves away from the image, the image will be transparent again.
An example of reversed hover effect:
When using the opacity property to add transparency to the background of an element, all of its child elements 
inherit the same transparency. This can make the text inside a fully transparent element hard to read:
opacity 1
opacity 0.6
opacity 0.3
opacity 0.1
If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. 
The following example sets the opacity for the background color and not the text:
100% opacity
60% opacity
30% opacity
10% opacity
You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB, 
you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color.
An RGBA color value is specified with: rgba(red, green, blue, alpha). The 
alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.
This is some text that is placed in the transparent box.
First, we create a <div> element (class="background") with a background image, and a border.

Then we create another <div> (class="transbox") inside the first <div>. 
The 
<div class="transbox"> have a background color, and a border - 
the div is transparent. 
Inside the transparent 
<div>, we add some text inside a <p> element.
Use CSS to set the transparency of the image to 50%.
<style>
img {
  : ;
}
</style>

<body>
  <img src="klematis.jpg" width="150" height="113">
</body>

Start the Exercise
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.
Scikit Learn - Multinomial NaÃ ̄ve Bayes

It is another useful Naïve Bayes classifier. It assumes that the features are drawn from a simple Multinomial distribution. The Scikit-learn provides sklearn.naive_bayes.MultinomialNB to implement the Multinomial Naïve Bayes algorithm for classification.
Following table consist the parameters used by sklearn.naive_bayes.MultinomialNB method −
alpha − float, optional, default = 1.0
It represents the additive smoothing parameter. If you choose 0 as its value, then there will be no smoothing.
fit_prior − Boolean, optional, default = true
It tells the model that whether to learn class prior probabilities or not. The default value is True but if set to False, the algorithms will use a uniform prior.
class_prior − array-like, size(n_classes,), optional, Default = None
This parameter represents the prior probabilities of each class.
Following table consist the attributes used by sklearn.naive_bayes.MultinomialNB method −
class_log_prior_ − array, shape(n_classes,)
It provides the smoothed log probability for every class.
class_count_ − array, shape(n_classes,)
It provides the actual number of training samples encountered for each class.
intercept_ − array, shape (n_classes,)
These are the Mirrors class_log_prior_ for interpreting MultinomilaNB model as a linear model.
feature_log_prob_ − array, shape (n_classes, n_features)
It gives the empirical log probability of features given a class P(features⏐Y).
coef_ − array, shape (n_classes, n_features)
These are the Mirrors feature_log_prior_ for interpreting MultinomilaNB model as a linear model.
feature_count_ − array, shape (n_classes, n_features)
It provides the actual number of training samples encountered for each (class,feature).
The methods of sklearn.naive_bayes. MultinomialNB are same as we have used in sklearn.naive_bayes.GaussianNB.
The Python script below will use sklearn.naive_bayes.GaussianNB method to construct Gaussian Naïve Bayes Classifier from our data set −
import numpy as np
X = np.random.randint(8, size = (8, 100))
y = np.array([1, 2, 3, 4, 5, 6, 7, 8])

from sklearn.naive_bayes import MultinomialNB
MNBclf = MultinomialNB()
MNBclf.fit(X, y)
MultinomialNB(alpha = 1.0, class_prior = None, fit_prior = True)
Now, once fitted we can predict the new value aby using predict() method as follows −
print((MNBclf.predict(X[4:5]))
[5]

    11 Lectures 
     2 hours 

 PARTHA MAJUMDAR
 Print
 Add Notes
 Bookmark this page
How to compare dates in JavaScript?

Dates can be compared easily in javascript. The dates can belong to any frame i.e past, present and future. Past dates can be compared to future or future dates can be compared to the present. 
In the following example, a date in the year 2000 is compared with today's date and the respective message is displayed in the output. 
Live Demo
<html>
<body>
   <p id="compare"></p>
<script>
   var today = new Date();
   var otherday = new Date();
   otherday.setFullYear(2000, 2, 14);
   if (otherday > today) {
      var msg = "The date you provided is a future date ";
   } else {
       var msg = "The date you provided is a past date";
   }
   document.getElementById("compare").innerHTML = msg;
</script>
</body>
</html>
The date you provided is a past date
In the following example, a date in the year 2900 is compared with today's date and the respective message is displayed in the output. 
Live Demo
<html>
<body>
   <p id="compare"> </p>
<script>
   var today = new Date();
   var otherday = new Date();
   otherday.setFullYear(2900, 2, 14);
   if (otherday > today) {
      var msg = "The date you provided is a future date ";
   } else {
       var msg = "The date you provided is a past date";
   }
   document.getElementById("compare").innerHTML = msg;
</script>
</body>
</html>
The date you provided is a future date
Elixir - Environment

In order to run Elixir, you need to set it up locally on your system.
To install Elixir, you will first require Erlang. On some platforms, Elixir packages come with Erlang in them.
Let us now understand the installation of Elixir in different Operating Systems.
To install Elixir on windows, download installer from https://repo.hex.pm/elixirwebsetup.exe and simply click Next to proceed through all steps. You will have it on your local system.
If you have any problems while installing it, you can check this page for more info.
If you have Homebrew installed, make sure that it is the latest version. For updating, use the following command −
brew update

Now, install Elixir using the command given below −
brew install elixir

The steps to install Elixir in an Ubuntu/Debian setup is as follows −
Add Erlang Solutions repo −
wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo 
dpkg -i erlang-solutions_1.0_all.deb 
sudo apt-get update 

Install the Erlang/OTP platform and all of its applications −
sudo apt-get install esl-erlang 

Install Elixir −
sudo apt-get install elixir

If you have any other Linux distribution, please visit this page to set up elixir on your local system.
To test the Elixir setup on your system, open your terminal and enter iex in it. It will open the interactive elixir shell like the following −
Erlang/OTP 19 [erts-8.0] [source-6dc93c1] [64-bit] 
[smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]  

Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) 
iex(1)>

Elixir is now successfully set up on your system.

    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
Check if a graph is strongly connected - Set 1 (Kosaraju using DFS) in C++

Suppose we have a graph. We have to check whether the graph is strongly connected or not using Kosaraju algorithm. A graph is said to be strongly connected, if any two vertices has path between them, then the graph is connected. An undirected graph is strongly connected graph.
Some undirected graph may be connected but not strongly connected. This is an example of strongly connected graph.
This is an example of connected, but not strongly connected graph.
Here we will see, how to check a graph is strongly connected or not using the following steps of Kosaraju algorithm.
Steps −
Mark all nodes as not visited
Mark all nodes as not visited
Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false.
Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false.
Reverse all edges of the graph
Reverse all edges of the graph
Set all vertices as not visited nodes again
Set all vertices as not visited nodes again
Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true.
Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true.
 Live Demo
#include <iostream>
#include <list>
#include <stack>
using namespace std;
class Graph {
   int V;
   list<int> *adj;
   void dfs(int v, bool visited[]);
   public:
   Graph(int V) {
      this->V = V;
      adj = new list<int>[V];
   }
   ~Graph() {
      delete [] adj;
   }
   void addEdge(int v, int w);
   bool isStronglyConnected();
   Graph reverseArc();
};
void Graph::dfs(int v, bool visited[]) {
   visited[v] = true;
   list<int>::iterator i;
   for (i = adj[v].begin(); i != adj[v].end(); ++i)
   if (!visited[*i])
      dfs(*i, visited);
}
Graph Graph::reverseArc() {
   Graph graph(V);
   for (int v = 0; v < V; v++) {
      list<int>::iterator i;
      for(i = adj[v].begin(); i != adj[v].end(); ++i)
      graph.adj[*i].push_back(v);
   }
   return graph;
}
void Graph::addEdge(int u, int v) {
   adj[u].push_back(v);
}
bool Graph::isStronglyConnected() {
   bool visited[V];
   for (int i = 0; i < V; i++)
   visited[i] = false;
   dfs(0, visited);
   for (int i = 0; i < V; i++)
   if (visited[i] == false)
      return false;
   Graph graph = reverseArc();
   for(int i = 0; i < V; i++)
   visited[i] = false;
   graph.dfs(0, visited);
   for (int i = 0; i < V; i++)
   if (visited[i] == false)
      return false;
   return true;
}
int main() {
   Graph graph(5);
   graph.addEdge(0, 1);
   graph.addEdge(1, 2);
   graph.addEdge(2, 3);
   graph.addEdge(3, 0);
   graph.addEdge(2, 4);
   graph.addEdge(4, 2);
   graph.isStronglyConnected()? cout << "This is strongly connected" : cout << "This is not strongly connected";
}
This is strongly connected
ML | Models Score and Error - GeeksforGeeks

02 Aug, 2019
In Machine Learning one of the main task is to model the data and predict the output using various Classification and Regression Algorithms. But since there are so many Algorithms, it is really difficult to choose the one for predicting the final data. So we need to compare our models and choose the one with the highest accuracy.
Using the sklearn library we can find out the scores of our ML Model and thus choose the algorithm with a higher score to predict our output. Another good way is to calculate errors such as mean absolute error and mean squared error and try to minimize them to better our models.
Mean Absolute Error(MAE): It is the mean of all absolute error
Mean Squared Error (MSE) It is the mean of square of all errors.
Here, we are using Titanic dataset as our input for Classification problem and modelling our data with Logistic Regression and KNN only. Although, you can also model with other algorithms. You can find the dataset here
# importing librariesimport numpy as npimport sklearnfrom sklearn import metricsimport pandas as pd  from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifier    data = pd.read_csv("gfg_data")  x = data[['Pclass', 'Sex', 'Age', 'Parch', 'Embarked', 'Fare',               'Has_Cabin', 'FamilySize', 'title', 'IsAlone']]  y = data[['Survived']]  X_train, X_test, Y_train, Y_test = train_test_split(x, y,test_size = 0.3, random_state = None)  # logistic Regressionlr = LogisticRegression()lr.fit(X_train, Y_train)  Y_pred = lr.predict(X_test)  LogReg = round(lr.score(X_test, Y_test), 2)  mae_lr = round(metrics.mean_absolute_error(Y_test, Y_pred), 4)mse_lr = round(metrics.mean_squared_error(Y_test, Y_pred), 4)  # KNNknn = KNeighborsClassifier(n_neighbors = 2)knn.fit(X_train, Y_train)  Y_pred = knn.predict(X_test)  KNN = round(knn.score(X_test, Y_test), 2)  mae_knn = metrics.mean_absolute_error(Y_test, Y_pred)mse_knn = metrics.mean_squared_error(Y_test, Y_pred)    compare_models = pd.DataFrame(    {  'Model' : ['LogReg', 'KNN'],       'Score' : [LogReg, KNN],        'MAE'  : [mae_lr, mae_knn],        'MSE'  : [mse_lr, mse_knn]    })  print(compare_models)
Output:
We can now see the score and error of our models and compare them. Score of Logistic Regression is greater then KNN and error is also less. Thus, Logistic Regression will be the right choice for our model.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Intuition of Adam Optimizer
Introduction to Recurrent Neural Network
Singular Value Decomposition (SVD)
k-nearest neighbor algorithm in Python
CNN | Introduction to Pooling Layer
Python | Decision Tree Regression using sklearn
Bagging vs Boosting in Machine Learning
Python | Stemming words with NLTK
DBSCAN Clustering in ML | Density based clustering
CSS | @import rule - GeeksforGeeks

07 Jan, 2019
The @import rule is used to import one style sheet into another style sheet. This rule also support media queries so that the user can import the media-dependent style sheet. The @import rule must be declared at the top of the document after any @charset declaration.
Syntax:
@import url|string list-of-mediaqueries;

Property Values:
url|string: A url or a string represents the location of the resource to be imported. The url may be relative or absolute
list-of-mediaqueries: The list of media queries condition the application of the CSS rules defined in the linked URL
Example: Consider the two CSS files as shown below.
icss.css@import url("i1css.css");
h1 {
    color: #00ff00;
}

@import url("i1css.css");
h1 {
    color: #00ff00;
}

i1css.cssh1 {
   text-decoration: underline;
   font-size:60px;
}

p {
   padding-left: 20px;
   font-size: 60px;
}

h1 {
   text-decoration: underline;
   font-size:60px;
}

p {
   padding-left: 20px;
   font-size: 60px;
}

Link the first CSS file icss.css in the below HTML file and see the output.
<!DOCTYPE html><html><head>    <title>WebPage</title>    <link href="icss.css" rel="stylesheet"></head>  <body>    <h1>GeeksforGeeks</h1>    <p>A computer science portal for geeks</p></body></html>                    
Output:
Supported Browsers:The browsers supported by @import rule are listed below:
Google Chrome
Internet Explorer 5.5
Firefox
Safari
Opera
CSS-Basics
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Java fall through switch statements

Following rules govern the fall through the behavior of switch statement.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Live Demo
public class Test {

   public static void main(String args[]) {
      // char grade = args[0].charAt(0);
      char grade = 'C';

      switch(grade) {
         case 'A' :
            System.out.println("Excellent!");
            break;
         case 'B' :
         case 'C' :
            System.out.println("Well done");
            break;
         case 'D' :
            System.out.println("You passed");
         case 'F' :
            System.out.println("Better try again");
            break;
         default :
            System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}
Compile and run the above program using various command line arguments. This will produce the following result −
Well done
Your grade is C
Console.SetBufferSize() Method in C# - GeeksforGeeks

14 Mar, 2019
Console.SetBufferSize(Int32, Int32) Method is used to set the height and width of the screen buffer area to the specified values.
Syntax: public static void SetBufferSize(int width, int height);
Parameters:width: It sets the width of the buffer area measured in the form of columns.height: It sets the height of the buffer area measured in the form of rows.
Return value: The new size of the buffer screen.
Exceptions:
ArgumentOutOfRangeException: If the height or width is less than or equal to zero Or height or width is greater than or equal to MaxValue. Also, if the width is less than WindowLeft + WindowWidth or height is less than WindowTop + WindowHeight then we will get the same exception.
IOException: If an I/O error occurred.
Note: As you will see via the horizontal and the vertical scrollbars in the below examples, as we give different dimensions, we get differently sized windows.
Example 1:
// C# program to demonstrate// the  SetBufferSize Methodusing System;using System.Text;using System.IO;  class GFG {      // Main Method    public static void Main()    {          // using the method        Console.SetBufferSize(800, 800);        Console.WriteLine("Start");        while (true)         {            Console.WriteLine("Great Geek's Example!!!");        }    } // end Main}
Output:
Example 2:
// C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO;  class GFG {      // Main Method    public static void Main()    {        Console.SetBufferSize(0, 80);        Console.WriteLine("Great Geek's Example!!!");        Console.WriteLine("The Width's value is too less!");    } // end Main}
Example 3:
// C# program to demonstrate// the SetBufferSize Methodusing System;using System.Text;using System.IO;  class GFG {      // Main Method    public static void Main()    {        Console.SetBufferSize(8000, -80);        Console.WriteLine("Great Geek's Example!!!");        Console.WriteLine("The negativity of this height is unbearable!");    } // end Main}
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.setbuffersize?view=netframework-4.7.2
CSharp-Console-Class
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Lambda Expressions in C#
Linked List Implementation in C#
Convert String to Character Array in C#
Erlang - Logical Operators

Following are the logical operators available in Erlang.
The following code snippet shows how the various operators can be used.
-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~w~n",[true or false]),  
   io:fwrite("~w~n",[true and false]), 
   io:fwrite("~w~n",[true xor false]), 
   io:fwrite("~w~n",[not false]).
The output of the above program will be −
true
false
true
true

 Print
 Add Notes
 Bookmark this page
Frequency Modulation (FM) using MATLAB - GeeksforGeeks

02 Sep, 2020
Frequency modulation is the encoding of data in a carrier wave by changing the immediate frequency of the wave. In other words in frequency modulation, the frequency, as opposed to the amplitude of the carrier wave, is made to change in relation to the differing amplitude of the modulating signal.
We will be using the fmmod() function to get Frequency Modulation of a signal.
Syntax: a = fmmod(x, fc, fs, fdev)
Parameters:
x is input sinusoidal message signal
fc is carrier frequency
fc is carrier frequency,
fdev is frequency deviation
Spectrum:
Code:
% Sampling Frequencyfs = 400;    % Carrier Frequencyfc = 200;    % Time Durationtime = (0:1/fs:0.2)';    % Create two sinusoidal signal with frequencies 30 Hz and 60 Hzx = sin(2*pi*30*time)+2*sin(2*pi*60*time);    % Frequency Deviation fDev = 50;    % Frequency modulate xy = fmmod(x,fc,fs,fDev);   % plottingplot(time,x,'c',time,y,'b--')xlabel('Time (s)')ylabel('Amplitude')legend('Original Signal','Modulated Signal')
Output:
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Decision Tree Introduction with example
Reinforcement learning
ML | Underfitting and Overfitting
Clustering in Machine Learning
How to Run a Python Script using Docker?
How to convert std::string to LPCWSTR in C++?

In this section we will see how to convert C++ wide string (std::wstring) to LPCWSTR. The LPCWSTR is the (Long Pointer to Constant Wide STRing). It is basically the string with wide characters. So by converting wide string to wide character array we can get LPCWSTR. This LPCWSTR is Microsoft defined. So to use them we have to include Windows.h header file into our program.
To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string.
#include<iostream>
#include<Windows.h>
using namespace std;
main(){
   wstring my_str = L"Hello World";
   LPCWSTR wide_string ; //define an array with size of my_str + 1
   wide_string = my_str.c_str();
   wcout << "my_str is : " << my_str <<endl;
   wcout << "Wide String is : " << wide_string <<endl;
}
my_str is : Hello World
Wide String is : Hello World
GATE-CS-2014-(Set-1) - GeeksforGeeks

10 Nov, 2021
A says that strategies are now available for eliminating psychiatric illnesses but it is mentioned in the very first line that the geneticists are very close but the strategy is not available till now. So, A is incorrect.
The given data says that the geneticists are working on the genetic roots of psychiatric illnesses such as depression and schizophrenia, which implies that these two diseases have genetic basis. Thus, B is the correct option.
C says that all human diseases can be traced back to genes and how they are expressed, but the data given in the question talks about psychiatric illnesses such as depression and schizophrenia only. So, C is also incorrect.
D says that in future, genetics will be the only relevant field for identifying psychiatric illnesses, which cannot be inferred from the given data. So, D is also incorrect.
One way single person fare is 100. Therefore 2 way
is 200.

For 5 persons it is 200 x 5 = 1000

Now 1st discount is of 10 % on total fare, which is
100( 10 % of 1000). And as the group is of more than 4, 
an additional discount of 5 % on total fare, which is 
50( 5 % of 1000).

Hence total discount is equal to 100 + 50 = 150.

Therefore tickets are charged at Rs 1000 - 150 = 850. 
No. of respondents do not own scooter = 
                        No. of persons who have car alone + 
                        No. of persons who don't have both.
In men, 40 + 20 = 60 and
In women 34 + 50 = 84.
Total 60 + 84 = 144 .
Now the percentage is, (144/300) *100 = 48
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Python Data Structures and Algorithms
Different ways to iterate over a set in C++
How to display NA frequency for a ggplot2 graph using color brewer in R?

To display NA frequency for a ggplot2 graph using color brewer in R, we can follow the below steps −
First of all, create a data frame.
Then, create the chart with default colors.
After that, use scale_colour_brewer function to create the bar chart and set the color of NA values bar with na.value.
Let's create a data frame as shown below −
 Live Demo
Group<-c("A","B","C",NA)
Count<-c(24,21,27,25)
df<-data.frame(Group,Count)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
   Group Count
1   A    24
2   B    21
3   C    27
4 <NA>   25
Loading ggplot2 package and creating the bar for the data in df −
Group<-c("A","B","C",NA)
Count<-c(24,21,27,25)
df<-data.frame(Group,Count)
library(ggplot2)
ggplot(df,aes(Group,Count,fill=Group))+geom_bar(stat="identity")
Use scale_colour_brewer function of ggplot2 package to create the bar chart and set the color of NA values bar to red with na.value as shown below −
Group<-c("A","B","C",NA)
Count<-c(24,21,27,25)
df<-data.frame(Group,Count)
library(ggplot2)
ggplot(df,aes(Group,Count,fill=Group))+geom_bar(stat="identity")+scale_fill_brewer(pa
lette="Accent",na.value="red")
C# program to iterate over a string array with for loop

Create a string array −
string[] str = new string[] {
   "Videos",
   "Tutorials",
   "Tools",
   "InterviewQA"
};
Loop until the length of the array −
for (int i = 0; i < str.Length; i++) {
   string res = str[i];
   Console.WriteLine(res);
}
Here is the complete code −
 Live Demo
using System;

public class Demo {
   public static void Main() {
      string[] str = new string[] {
         "Videos",
         "Tutorials",
         "Tools",
         "InterviewQA"
      };
   
      Console.WriteLine("String Array...");
      for (int i = 0; i < str.Length; i++) {
         string res = str[i];
         Console.WriteLine(res);
      }
   }
}
String Array...
Videos
Tutorials
Tools
InterviewQA
Subsets in Python

Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. So if the set is like [1,2,3], then the power set will be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
Let us see the steps −
We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes the set of numbers (nums), temporary set (temp), res and index
The solve() function will work like below −
if index = length of nums, then create a list same as temp, and insert into res and return
temp[index] := 0
solve(nums, temp, res, index + 1)
temp[index] := 1
solve(nums, temp, res, index + 1)
The main function will be like below −
res := an empty list
create temp list of size same as the nums, and fill this with 0
call solve(nums, temp, res, 0)
main_res := an empty list
for all lists in temp_restemp := empty listfor i := 0 to length of listsif lists[i] = 1, then insert nums[i] into tempinsert temp into main_res
temp := empty list
for i := 0 to length of listsif lists[i] = 1, then insert nums[i] into temp
if lists[i] = 1, then insert nums[i] into temp
insert temp into main_res
return main res
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def subsets(self, nums):
      temp_result = []
      self.subsets_util(nums,[0 for i in range(len(nums))],temp_result,0)
      main_result = []
      for lists in temp_result:
         temp = []
         for i in range(len(lists)):
            if lists[i] == 1:
               temp.append(nums[i])
         main_result.append(temp)
      return main_result
   def subsets_util(self,nums,temp,result,index):
      if index == len(nums):
         result.append([i for i in temp])
         #print(temp)
         return
      temp[index] = 0
      self.subsets_util(nums,temp,result,index+1)
      temp[index] = 1
      self.subsets_util(nums, temp, result,index + 1)
ob1 = Solution()
print(ob1.subsets([1,2,3,4]))
[1,2,3,4]
[[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], 
[1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]
Swift - Characters

A character in Swift is a single character String literal, addressed by the data type Character. Take a look at the following example. It uses two Character constants −
let char1: Character = "A"
let char2: Character = "B"

print("Value of char1 \(char1)")
print("Value of char2 \(char2)")
When the above code is compiled and executed, it produces the following result −
Value of char1 A
Value of char2 B

If you try to store more than one character in a Character type variable or constant, then Swift 4 will not allow that. Try to type the following example in Swift 4 Playground and you will get an error even before compilation.
// Following is wrong in Swift 4
let char: Character = "AB"

print("Value of char \(char)")
It is not possible to create an empty Character variable or constant which will have an empty value. The following syntax is not possible −
// Following is wrong in Swift 4
let char1: Character = ""
var char2: Character = ""

print("Value of char1 \(char1)")
print("Value of char2 \(char2)")
As explained while discussing Swift 4's Strings, String represents a collection of Character values in a specified order. So we can access individual characters from the given String by iterating over that string with a for-in loop −
for ch in "Hello" {
   print(ch)
}
When the above code is compiled and executed, it produces the following result −
H
e
l
l
o

The following example demonstrates how a Swift 4's Character can be concatenated with Swift 4's String.
var varA:String = "Hello "
let varB:Character = "G"

varA.append( varB )

print("Value of varC = \(varA)")
When the above code is compiled and executed, it produces the following result −
Value of varC = Hello G


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
C++ program to implement ASCII lookup table

In this tutorial, we will be discussing a program to implement ASCII lookup table.
ASCII lookup table is a tabular representation that provides with the octal, hexadecimal, decimal and HTML values of a given character.
The character for the ASCII lookup table includes alphabets, digits, separators and special symbols.
#include <iostream>
#include <string>
using namespace std;
//converting decimal value to octal
int Octal(int decimal){
   int octal = 0;
   string temp = "";
   while (decimal > 0) {
      int remainder = decimal % 8;
      temp = to_string(remainder) + temp;
      decimal /= 8;
   }
   for (int i = 0; i < temp.length(); i++)
      octal = (octal * 10) + (temp[i] - '0');
   return octal;
}
//converting decimal value to hexadecimal
string Hexadecimal(int decimal){
   string hex = "";
   while (decimal > 0) {
      int remainder = decimal % 16;
      if (remainder >= 0 && remainder <= 9)
         hex = to_string(remainder) + hex;
      else
         hex = (char)('A' + remainder % 10) + hex;
      decimal /= 16;
   }
   return hex;
}
//converting decimal value to HTML
string HTML(int decimal){
   string html = to_string(decimal);
   html = "&#" + html + ";";
   return html;
}
//calculating the ASCII lookup table
void ASCIIlookuptable(char ch){
   int decimal = ch;
   cout << "Octal value: " << Octal(decimal) << endl;
   cout << "Decimal value: " << decimal << endl;
   cout << "Hexadecimal value: " << Hexadecimal(decimal) <<
   endl;
   cout << "HTML value: " << HTML(decimal);
}
int main(){
   char ch = 'a';
   ASCIIlookuptable(ch);
   return 0;
}
Octal value: 141
Decimal value: 97
Hexadecimal value: 61
HTML value: a
JavaScript Array keys() Method - GeeksforGeeks

23 Jun, 2020
Below is the example of the Array keys() method.
Example:<script>     // Taking input as an array A    // containing some elements.   var A = [ 5, 6, 10 ];     // array.keys() method is called   var iterator = A.keys();     // printing index array using the iterator   for (let key of iterator) {    document.write(key + ' ');   }</script>
<script>     // Taking input as an array A    // containing some elements.   var A = [ 5, 6, 10 ];     // array.keys() method is called   var iterator = A.keys();     // printing index array using the iterator   for (let key of iterator) {    document.write(key + ' ');   }</script>
Output:0 1 2
0 1 2
The array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array.
Syntax:
array.keys()
Parameters: This method does not accept any parameters.
Return Values: It returns a new array iterator.
Below example illustrate the Array keys() method in JavaScript:
Example:var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];
var iterator = A.keys(document.write(key + ' '));Output:0 1 2 3
var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];
var iterator = A.keys(document.write(key + ' '));
Output:
0 1 2 3
Code for the above method is provided below:Program 1:
<script>     // Taking input as an array A    // containing some elements.   var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];     // array.keys() method is called   var iterator = A.keys();     // printing index array using the iterator   for (let key of iterator) {    document.write(key + ' ');   }</script>
Output:
0 1 2 3 
Program 2:
<script>    // Taking input as an array A  // containing some elements  var A = [ 'gfg', 'geeks', 'cse', 'geekpro', '', 1, 2 ];    // array.keys() method is called  var iterator = A.keys();    // Printing index array using the iterator  for (let key of iterator) {    document.write(key + ' ');  }</script>
Output:
0 1 2 3 4 5 6 
Supported Browsers: The browsers supported by JavaScript Array keys() method are listed below:
Google Chrome 38.0
Microsoft Edge 12.0
Mozilla Firefox 28.0
Safari 8.0
Opera 25.0
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using 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 increment a field in MongoDB?

To increment a field in MongoDB, you can use $inc operator. Let us first create a collection with documents −
> db.incrementDemo.insertOne({"PlayerScore":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e")
}
> db.incrementDemo.insertOne({"PlayerScore":290});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc81ce28f9e6ff3eb0ce44f")
}
> db.incrementDemo.insertOne({"PlayerScore":560});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc81ce68f9e6ff3eb0ce450")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 }
{ "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 290 }
{ "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }
Following is the query to increment a field in MongoDB −
> db.incrementDemo.update({ _id:ObjectId("5cc81ce28f9e6ff3eb0ce44f") },{ $inc: {"PlayerScore":10 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
In the above query, I have incremented the value 290 with value 10 −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 }
{ "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 300 }
{ "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }
How MySQL WHILE loop statement can be used in stored procedure?

As we know that MySQL provides us loop statements that allow us to execute a block of SQL code repeatedly based on a condition. WHILE loop statement is one of such kind of loop statements. Its syntax is as follows −
WHILE expression DO
statements
END WHILE
Actually, the WHILE loop checks the expression at the starting of every iteration. If the expression evaluates to true, MySQL will execute statements between WHILE and END WHILE until the expression evaluates to false. The WHILE loop checks the expression before the statements execute, that is why it is also called the pretest loop.
To demonstrate the use of WHILE loop with stored procedures, the following is an example −
mysql> Delimiter //
mysql> CREATE PROCEDURE While_Loop()
  -> BEGIN
-> DECLARE A INT;
-> DECLARE XYZ Varchar(50);
-> SET A = 1;
-> SET XYZ = '';
-> WHILE A <=10 DO
-> SET XYZ = CONCAT(XYZ,A,',');
-> SET A = A + 1;
-> END WHILE;
-> SELECT XYZ;
-> END //
Query OK, 0 rows affected (0.31 sec)
Now, we can see the result below when we invoke this procedure −
mysql> DELIMITER ;
mysql> call While_Loop();
+-----------------------+
| XYZ |
+-----------------------+
| 1,2,3,4,5,6,7,8,9,10, |
+-----------------------+
1 row in set (0.03 sec)