code-rag-bench/online-tutorials huggingface dataset:
Custom Sort String in C++

Suppose we have S and T two strings these are composed of lowercase letters. In S, no letter occurs more than once. S was sorted in some custom order previously. We have to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x will occur before y in the returned string.
So if the S = “cba” and T = “abcd”, then the output will be “cbad”. Here "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". As "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.
To solve this, we will follow these steps −
set ret as empty string
set ret as empty string
define a map m, and store the frequency of each character present in T into m
define a map m, and store the frequency of each character present in T into m
for i in range 0 to size of S – 1x := S[i]for j in range 0 to m[x] – 1ret := ret + xm[x] := 0
for i in range 0 to size of S – 1
x := S[i]
x := S[i]
for j in range 0 to m[x] – 1ret := ret + x
for j in range 0 to m[x] – 1
ret := ret + x
ret := ret + x
m[x] := 0
m[x] := 0
for each pair it in m −if value of it is > 0, thenfor i in range 0 to value of it – 1ret := ret concatenate key of it
for each pair it in m −
if value of it is > 0, thenfor i in range 0 to value of it – 1ret := ret concatenate key of it
if value of it is > 0, then
for i in range 0 to value of it – 1ret := ret concatenate key of it
for i in range 0 to value of it – 1
ret := ret concatenate key of it
ret := ret concatenate key of it
return ret
return ret
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string customSortString(string S, string T) {
      string ret = "";
      unordered_map <char, int> m;
      for(int i = 0; i < T.size(); i++){
         m[T[i]]++;
      }
      for(int i = 0; i < S.size(); i++){
         char x = S[i];
         for(int j = 0; j < m[x]; j++){
            ret += x;
         }
         m[x] = 0;
      }
      unordered_map <char, int> :: iterator it = m.begin();
      while(it != m.end()){
         if(it->second > 0){
            for(int i = 0; i < it->second; i++)ret += it->first;
         }
         it++;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.customSortString("cba", "abcd"));
}
"cba"
"abcd"
cbad
CICS - Handle condition

Handle condition is used to transfer the control of the program to a paragraph or a procedure label. If the condition name specified in the exception block arises, the particular para will be given control and then we can handle that condition.
HANDLE CONDITION can handle only conditions related to CICS, not the ordinary program Abends like as data exceptions. It can handle conditions that are related only to CICS. It cannot handle the ordinary program Abends like as data exceptions. The syntax of Handle Condition is as follows −
EXEC CICS HANDLE CONDITION
   CONDITION(Label)
   CONDITION(Label)
   ERROR(LABEL)
END-EXEC.

Following is the example of Handle condition −
IDENTIFICATION DIVISION.                                         
PROGRAM-ID. HELLO.                                               
PROCEDURE DIVISION.

EXEC CICS HANDLE CONDITION
   DUPKEY(X0000-DUPKEY-ERR-PARA)
   NOTFND(X000-NOT-FOUND-PARA)
   ERROR(X0000-GEN-ERR-PARA)
END-EXEC.
X0000-DUPKEY-ERR-PARA.

DISPLAY 'Duplicate Key Found'.
X0000-NOT-FOUND-PARA.

DISPLAY 'Record Not Found'.
X0000-GEN-ERR-PARA.

DISPLAY 'General Error'.
 Print
 Add Notes
 Bookmark this page
How to apply an id attribute to a child element of a ReactJS component ? - GeeksforGeeks

07 Apr, 2021
We can get the ID attribute of a ReactJS component from the props of the ReactJS component. As we are inside a ReactJS component here we are going to use this.props instead of props. If the ID attribute has been passed as id to the ReactJS component then we can use the following to get the ID attribute passed:
this.props.id
Once we get the ID attribute we can easily pass it to any child element to which we wish to pass it as shown below.
<child_element_name id = {this.props.id}>
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import BodyComponent from './Bodycomponent.js';  function App() {    return (        <div>            <header>Hello and Welcome</header>            <BodyComponent id='childid' />        </div>    );}  export default App;
Bodycomponent.js
import React from 'react';  function BodyComponent(props) {    return (        <p id={props.id}>            This is the content with the ID 'childid'.            It has been supplied with the ID attribute of             the React component.        </p>      );}  export default BodyComponent;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
React-Questions
JavaScript
ReactJS
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 filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
How can I override the 'Home' button in my Android App?

This example demonstrates how do I in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:text="Press Home Button"
      android:textSize="16sp"
      android:textStyle="bold"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   @Override
   protected void onUserLeaveHint(){
      Toast.makeText(getApplicationContext(), "Home Button is Pressed", Toast.LENGTH_SHORT).show();
      super.onUserLeaveHint();
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
Replace part of string in MySQL table column?

To replace part of string in MySQL table column, you can use REPLACE(). Following is the syntax −
update yourTableName set yourColumnName = REPLACE(yourColumnName ,'yourOldValue','yourNewValue');
Let us first create a table −
mysql> create table replacePartOfStringDemo
   -> (
   -> WebsiteURL varchar(100)
   -> );
Query OK, 0 rows affected (0.47 sec)
Following is the query to insert records in the table using insert command −
mysql> insert into replacePartOfStringDemo(WebsiteURL) values('www.mysqlQuestion.com');
Query OK, 1 row affected (0.14 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from replacePartOfStringDemo;
This will produce the following output −
+-----------------------+
| WebsiteURL            |
+-----------------------+
| www.mysqlQuestion.com |
+-----------------------+
1 row in set (0.00 sec)
Let us now replace part of a string in MySQL table column. Here, “mysqlQuestion“ is replaced with “mysql” −
mysql> update replacePartOfStringDemo set
WebsiteURL=REPLACE(WebsiteURL,'www.mysqlQuestion.com','www.mysql.com');
Query OK, 1 row affected (0.20 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table record once again −
mysql> select * from replacePartOfStringDemo;
This will produce the following output −
+---------------+
| WebsiteURL    |
+---------------+
| www.mysql.com |
+---------------+
1 row in set (0.00 sec)
The return Statement in Python

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows −
 Live Demo
#!/usr/bin/python
Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2
   print "Inside the function : ", total
   return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
How to check Android Phone Model programmatically?

This example demonstrate about How to check Android Phone Model programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
   xmlns: tools = "http://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   android :layout_margin= "16dp"
   tools :context= ".MainActivity" >
   <TextView
      android :gravity= "center"
      android :id= "@+id/textView"
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :layout_centerInParent= "true"
      android :textSize= "18sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Build ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity {
   TextView textView ;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      textView = findViewById(R.id. textView ) ;
      textView .setText(getPhoneModel()) ;
   }
   private String getPhoneModel () {
      return Build. MODEL ;
   }
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <uses-permission android :name= "android.permission.CALL_PHONE" />
   <application
      android :allowBackup= "true"
      android :icon= "@mipmap/ic_launcher"
      android :label= "@string/app_name"
      android :roundIcon= "@mipmap/ic_launcher_round"
      android :supportsRtl= "true"
      android :theme= "@style/AppTheme" >
      <activity android :name= ".MainActivity" >
         <intent-filter>
            <action android :name= "android.intent.action.MAIN" />
            <category android :name= "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Scala - Logical Operators

Try the following example program to understand all the logical operators available in Scala Programming Language.
object Demo {
   def main(args: Array[String]) {
      var a = true;
      var b = false;

      println("a && b = " + (a&&b) );
      
      println("a || b = " + (a||b) );
      
      println("!(a && b) = " + !(a && b) );
   }
} 
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

a && b = false
a || b = true
!(a && b) = true


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Swift - Tuples

Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value.
The values in a tuple can be of any type, and do not need to be of same type.
For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command.
let ImplementationError = (501, "Not implemented") is an error when something on the server is not implemented, It returns two values. Error Code, and Description.
You can create tuples from as many values as you want and from any number of different data types.
Here’s the syntax of Tuple declaration −
var TupleName = (Value1, value2,... any number of values)

Here’s a Tuple declaration −
var error501 = (501, “Not implemented”)

You can access the values of tuple using the index numbers that start from 0.
Here’s an example of accessing tuple Values −
print(“The code is\(error501.0)”)
print(“The definition of error is\(error501.1)”)

You can name the variables of a tuple while declaring , and you can call them using their names
var error501 = (errorCode: 501, description: “Not Implemented”)
print(error501.errorCode)   // prints 501.

Tuples are helpful in returning multiple values from a function. Like, a web application might return a tuple of type ("String", Int) to show whether the loading was successful or failed.
By returning different values in a tuple we can make decisions depending on different tuple types.
Note − Tuples are useful for temporary values and are not suited for complex data.

    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
Rearrange An Array In Order – Smallest, Largest, 2nd Smallest, 2nd Largest,. Using C++

We are given an array; we need to arrange this array in an order that the first element should be a minimum element, the second element should be a maximum element, the third element should be 2nd minimum element, the fourth element should be the 2nd maximum element and so on for example −
Input : arr[ ] = { 13, 34, 30, 56, 78, 3 }
Output : { 3, 78, 13, 56, 34, 30 }
Explanation : array is rearranged in the order { 1st min, 1st max, 2nd min, 2nd max, 3rd min, 3rd max }

Input : arr [ ] = { 2, 4, 6, 8, 11, 13, 15 }
Output : { 2, 15, 4, 13, 6, 11, 8 }
This problem can be solved using two variables, 'x's and 'y' where they will point to the maximum and minimum element, But for that array should be sorted, so we need to sort the array first, Then create a new empty array of the same size to store the reordered array. Now iterate over the array and if the iterative element is at even index, then add arr[ x ] element to the empty array and increment x by 1. if the element is at an odd index, then add arr[ y ] element to the empty array and decrement y by 1. Do this until y becomes smaller than x.
#include <bits/stdc++.h>
using namespace std;
int main () {
   int arr[] = { 2, 4, 6, 8, 11, 13, 15 };
   int n = sizeof (arr) / sizeof (arr[0]);

   // creating a new array to store the rearranged array.
   int reordered_array[n];

   // sorting the original array
   sort(arr, arr + n);

   // pointing variables to minimum and maximum element index.
   int x = 0, y = n - 1;
   int i = 0;

   // iterating over the array until max is less than or equals to max.
   while (x <= y) {
   // if i is even then store max index element

      if (i % 2 == 0) {
         reordered_array[i] = arr[x];
         x++;
      }
      // store min index element
      else {
         reordered_array[i] = arr[y];
         y--;
      }
      i++;
   }
   // printing the reordered array.
   for (int i = 0; i < n; i++)
      cout << reordered_array[i] << " ";

   // or we can update the original array
   // for (int i = 0; i < n; i++)
   // arr[i] = reordered_array[i];
   return 0;
}
2 15 4 13 6 11 8
Variables are initialised as x=0 and y = array_length(n) - 1.
while( x<=y) traverse the array until x becomes greater than y.
If the count is even (x), the element is added to the final array, and variable x is incremented by 1.
If i is odd, then (y)the element is added in the final array, and variable y is decremented by 1.
Finally, the Reordered array is stored in the reordered_array[ ].
In this article, we discussed the solution to rearrange the given array in the smallest, largest form. We also write a C++ program for the same. Similarly, we can write this program in any other language like C, Java, Python, etc. We hope you find this article helpful.
Finding intersection of multiple arrays - JavaScript

We are required to write a JavaScript function that takes in any arbitrary number of arrays and returns an array of elements that are common to all arrays. If there are no common elements, then we should return an empty array.
Let’s say the following are our arrays −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
Following is the code −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
const intersection = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      if(!arr2.includes(arr1[i])){
         continue;
      };
      res.push(arr1[i]);
   };
   return res;
};
const intersectMany = (...arrs) => {
   let res = arrs[0].slice();
   for(let i = 1; i < arrs.length; i++){
      res = intersection(res, arrs[i]);
   };
   return res;
};
console.log(intersectMany(arr1, arr2, arr3));
This will produce the following output in console −
[2, 1, 3]
ALTER table by adding AUTOINCREMENT in MySQL?

To add AUTOINCREMENT in MySQL, you can use the ALTER command.
ALTER TABLE yourTableName change yourColumName yourColumnName dataType AUTO_INCREMENT PRIMARY KEY;
To understand the above concept, create a table with a column. Let us create a table −
mysql> create table AlterTableToAddAutoIncrement
   -> (
   -> StudentId int
   -> );
Query OK, 0 rows affected (0.57 sec)
Implement the above syntax to change “StudentId” with AUTOINCREMENT. The query is as follows −
mysql> alter table AlterTableToAddAutoIncrement change StudentId StudentId int AUTO_INCREMENT Primary  key;
Query OK, 0 rows affected (1.93 sec)
Records: 0 Duplicates: 0 Warnings: 0
We have added AUTO_INCREMENT to column name ‘StudentId’. Now you can verify whether autoincrement is working or not by inserting records without giving any value.
The query is as follows −
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.33 sec)
Now you can display all records which will be displayed in sequence of 1, 2, 3, 4, etc. The query is as follows −
mysql> select *from AlterTableToAddAutoIncrement;
The following is the output −
+-----------+
| StudentId |
+-----------+
|         1 |
|         2 |
|         3 |
+-----------+
3 rows in set (0.00 sec)
Linked List Cycle II in C++

Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node. The constraint is that we cannot modify the list
To solve this, we will follow these steps −
slow := head and fast := head
while slow, fast and next of fast is available, thenslow := next of slowfast := next of (next of fast)if slow = fast, then break
slow := next of slow
fast := next of (next of fast)
if slow = fast, then break
if fast is not empty or next of first is not empty, then return null
if slow = fast, thenslow := headwhile slow is not same as fastslow := next of slow and fast := next of fast
slow := head
while slow is not same as fastslow := next of slow and fast := next of fast
slow := next of slow and fast := next of fast
return slow
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
ListNode *get_node(ListNode *head, int pos){
   ListNode *ptr = head;
   if(pos != -1){
      int p = 0;
      while(p < pos){
         ptr = ptr->next;
            p++;
      }
      return ptr;
   }
   return NULL;
}
class Solution {
   public:
   ListNode *detectCycle(ListNode *head) {
      ListNode* slow = head;
      ListNode* fast = head;
      while(slow && fast && fast->next){
         slow = slow->next;
         fast = fast->next->next;
         if(slow == fast)break;
      }
      if(!fast || !fast->next)return NULL;
      if(slow == fast){
         slow = head;
         while(slow!=fast){
            slow = slow->next;
            fast = fast->next;
         }
      }
      return slow;
   }
};
main(){
   Solution ob;
   vector<int> v = {5,3,2,0,-4,7};
   ListNode *head = make_list(v);
   int pos = 1;
   ListNode *lastNode = get_node(head, v.size() - 1);
   lastNode->next = get_node(head, pos);
   cout << "Tail is connected to the node with value:" <<ob.detectCycle(head)->val;
}
[5,3,2,0,-4,7]
1
Tail is connected to the node with value:3
Machine learning for anomaly detection: Elliptic Envelope | by Mahbubul Alam | Towards Data Science

Welcome back to anomaly detection; this is 6th in a series of “bite-sized” data science focusing on outlier detection. Today I am writing about a machine learning algorithm called EllipticEnvelope , which is yet another tool in data scientists’ toolbox for fraud/anomaly/outlier detection.
In case you have missed my previous articles or you are interested in learning more about the topic, find the links below:
Local Outlier Factor (LOF)
Z-score
Boxplot
Statistical techniques
Time series anomaly detection
So what is elliptic envelope and what’s the intuition behind the algorithm?
If you have taken geometry classes you are probably familiar with ellipse — a geometric configuration that takes an oval shape on a two-dimensional plane.
The green area in the above diagram is an ellipse. So the algorithm — Elliptical Envelope— creates an imaginary elliptical area around a given dataset. Values that fall inside the envelope are considered normal data and anything outside the envelope is returned as outliers. So, naturally, the red data points in the above diagram should be identified as outliers by this algorithm. As evident from this figure, the algorithm works best if data has a Gaussian distribution.
sklearn is the Swiss army knife of machine learning algorithms. So not surprisingly it has a module for anomaly detection using the elliptical envelope as well. Below I am demonstrating an implementation using imaginary data points in 5 simple steps.
# import librariesimport pandas as pdimport numpy as npfrom sklearn.covariance import EllipticEnvelopeimport matplotlib.pyplot as plt
# create a dataframedf = pd.DataFrame(np.array([[0,1], [1,1], [1,2], [2,2], [5,6]]), columns = ["x", "y"], index = [0,1,2,3,4])# show data in a scatterplotplt.scatter(df["x"], df["y"], color = "r")plt.grid()
# convert dataframe to arraysdata = df[['x', 'y']].values
The most important parameter in defining the model is to set the “contamination” parameter, which basically defines the proportion of values that will be identified as outliers. The parameter value ranges between 0 and 0.5
# instantiate modelmodel1 = EllipticEnvelope(contamination = 0.1) # fit modelmodel1.fit(data)
# new data for prediction (data needs to be in arrays)new_data = np.array([[10,10], [1,1], [1,1], [1,1]])# predict on new data pred1 = model1.predict(new_data)print(pred1)
The purpose of this article was to introduce Elliptic Envelope — a machine learning algorithm for anomaly detection — and implementing the algorithm using the Scikit-Learn library. If you now have the key concepts clear, go ahead and try implementing it on a real dataset, for example, the Iris dataset available online. You should be able to use the same 5 steps above on this dataset, just need to make sure that you’ve selected the right columns for the algorithm to work.
Difference between body.onload() and document.ready() function - GeeksforGeeks

01 Jul, 2021
The body.onload() event will be called once the DOM and all associated resources like images got loaded. Basically, onload() will be called when the page has been fully loaded with entire images, iframes and stylesheets, etc.
For example, if our page contains a larger size image, so onload() event will wait till the image is fully loaded. 
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <!-- using jquery library -->    <script        src="https://code.jquery.com/jquery-git.js">    </script>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport"           content="width=device-width, initial-scale=1.0">     </head>  <body onload="loadBody()">    <h2>GeeksForGeeks</h2>      <script>       function loadBody(){           alert("page loaded");       }    </script></body>  </html>
Output:
body onload
 
The document.ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded.
We can have multiple document.ready() function in our code but only one body.onload() is allowed.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <!-- Using jquery library -->    <script src="https://code.jquery.com/jquery-git.js"></script>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport"           content="width=device-width, initial-scale=1.0">     </head>  <body onload="loadBody()">    <h2>GeeksForGeeks</h2>      <script>       $(document).ready(function(){           alert("ready - page loaded")       })    </script></body>  </html>
Output:
DOM is ready
Difference between body.onload and document.ready:
JavaScript-Events
JavaScript-Questions
Picked
Difference Between
JQuery
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 Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Generate Fibonacci Series

The Fibonacci sequence is like this,
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,......
In this sequence, the nth term is the sum of (n-1)'th and (n-2)'th terms.
To generate we can use the recursive approach, but in dynamic programming, the procedure is simpler. It can store all Fibonacci numbers in a table, by using that table it can easily generate the next terms in this sequence.
Input:
Take the term number as an input. Say it is 10
Output:
Enter number of terms: 10
10th fibinacci Terms: 55
genFiboSeries(n)
Input: max number of terms.
Output − The nth Fibonacci term.
Begin
   define array named fibo of size n+2
   fibo[0] := 0
   fibo[1] := 1

   for i := 2 to n, do
      fibo[i] := fibo[i-1] + fibo[i-2]
   done
   return fibo[n]
End
#include<iostream>
using namespace std;

int genFibonacci(int n) {
   int fibo[n+2];          //array to store fibonacci values

   // 0th and 1st number of the series are 0 and 1
   fibo[0] = 0;
   fibo[1] = 1;

   for (int i = 2; i <= n; i++) {
      fibo[i] = fibo[i-1] + fibo[i-2];    //generate ith term using previous two terms
   }
   return fibo[n];
}

int main () {
   int n;
   cout << "Enter number of terms: "; cin >>n;
   cout << n<<" th Fibonacci Terms: "<<genFibonacci(n)<<endl;
}
Enter number of terms: 10
10th Fibonacci Terms: 55
How can I get the output of a Matplotlib plot as an SVG?

Just using the savefig method of the pyplot package and mentioning the file format, we can save the output as a SVG format.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create xpoints and ypoints using np.array(0, 5).
Create xpoints and ypoints using np.array(0, 5).
Plot lines using xpoints and ypoints.
Plot lines using xpoints and ypoints.
Set the X-axis label using plt.xlabel() method.
Set the X-axis label using plt.xlabel() method.
Set the Y-axis label using plt.ylabel() method.
Set the Y-axis label using plt.ylabel() method.
To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format="svg".
To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format="svg".
To show the image, use plt.show() method.
To show the image, use plt.show() method.
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
xpoints = np.array([0, 5])
ypoints = np.array([0, 5])
plt.plot(xpoints, ypoints)

plt.ylabel("Y-axis ")
plt.xlabel("X-axis ")

image_format = 'svg' # e.g .png, .svg, etc.
image_name = 'myimage.svg'

fig.savefig(image_name, format=image_format, dpi=1200)
Program to find smallest intersecting element of each row in a matrix in Python

Suppose we have a 2D matrix where each row is sorted in ascending order. We have to find the smallest number that exists in every row. If there's no such result, then return −1.
So, if the input is like
then the output will be 5
To solve this, we will follow these steps −
if matrix is empty, thenreturn −1
if matrix is empty, then
return −1
return −1
first := a new set from first row of matrix
first := a new set from first row of matrix
for each row in matrix, dofirst := Intersect first a set of elements of rowif first is empty, thenreturn −1
for each row in matrix, do
first := Intersect first a set of elements of row
first := Intersect first a set of elements of row
if first is empty, thenreturn −1
if first is empty, then
return −1
return −1
return minimum of first
return minimum of first
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, matrix):
      if not matrix:
         return -1
      first = set(matrix[0])
      for row in matrix:
         first &= set(row)
         if not first:
            return -1
      return min(first)
ob1 = Solution()
matrix = [
   [2, 3, 5],
   [5, 10, 10],
   [1, 3, 5]
]
print(ob1.solve(matrix))
matrix = [
[2, 3, 5],
[5, 10, 10],
[1, 3, 5] ]
5
Time Series - Walk Forward Validation

In time series modelling, the predictions over time become less and less accurate and hence it is a more realistic approach to re-train the model with actual data as it gets available for further predictions. Since training of statistical models are not time consuming, walk-forward validation is the most preferred solution to get most accurate results.
Let us apply one step walk forward validation on our data and compare it with the results we got earlier.
In [333]:
prediction = []
data = train.values
for t In test.values:
   model = (ExponentialSmoothing(data).fit())
   y = model.predict()
   prediction.append(y[0])
   data = numpy.append(data, t)

In [335]:
test_ = pandas.DataFrame(test)
test_['predictionswf'] = prediction

In [341]:
plt.plot(test_['T'])
plt.plot(test_.predictionswf, '--')
plt.show()

In [340]:
error = sqrt(metrics.mean_squared_error(test.values,prediction))
print ('Test RMSE for Triple Exponential Smoothing with Walk-Forward Validation: ', error)
Test RMSE for Triple Exponential Smoothing with Walk-Forward Validation:  11.787532205759442

We can see that our model performs significantly better now. In fact, the trend is followed so closely that on the plot predictions are overlapping with the actual values. You can try applying walk-forward validation on ARIMA models too.

    16 Lectures 
     2 hours 

 Malhar Lathkar

    21 Lectures 
     2.5 hours 

 Sasha Miller

    19 Lectures 
     1 hours 

 Sasha Miller

    94 Lectures 
     13 hours 

 Abhishek And Pukhraj

    12 Lectures 
     2 hours 

 Prof. Paul Cline, Ed.D

    11 Lectures 
     1 hours 

 Prof. Paul Cline, Ed.D
 Print
 Add Notes
 Bookmark this page
Does HTML5 Canvas support Double Buffering?

For double buffering on the canvas, create a 2nd canvas element and draw to it. After that draw the image to the first canvas using the drawImage() method,
// canvas element
var canvas1 = document.getElementById('canvas');
var context1 = canvas1.getContext('2d');

// buffer canvas
var canvas2 = document.createElement('canvas');
canvas2.width = 250;
canvas2.height =250;
var context2 = canvas2.getContext('2d');

// create on the canvas
context2.beginPath();
context2.moveTo(10,10);
context2.lineTo(10,30);
context2.stroke();

//render the buffered canvas
context1.drawImage(canvas2, 0, 0);
Elo Rating Algorithm in C++

Elo Rating Algorithm is a rating algorithm used to rank players in competitive games. The ranking of player of the competition is based on ranting which changes based on the performance of the player as follows,
For a game between two players of different ratings. Let’s say there are two players competing against each other−
Rating of player1 is greater than player2.
If player1 wins the game some player will be transferred from player1 to player2 and vice versa if player2 wins.
But the amount of rating to be transferred for victory is not constant. Instead it is dependent on the person winning the game,
If player1 wins the game, points transferred is less.If player2 wins the game, points transferred is more. 
The amount of points transferred is dependent on the formula,
For player1,
New rating = old Rating + ratingConstant * (successProb - P1)
For player2,
New rating = old Rating + ratingConstant * (successProb - P2)
Here,
ratingConstant is a constant, it is decided by the gaming community.
P1, probability of player1 winning.P2, probability of player2 winning.
Rating1 is the rating of player1.Rating2 is the rating of player2.
If a player wins the successProb is 1 otherwise its 0.
Input: rating1 = 782, rating2 = 1432,ratingConstant = 100, player1 wins the game.
Output: rating1 = 780, rating2 = 1434
Explanation −
Player1 wins,
For player1,
successProb = 1
New rating = 782 + 100*(1 - 0.98) = 782 + 100*(0.02) = 782 + 2 = 784
For player2,
successProb = 0
New rating = 1432 + 100*(0 - 0.02) = 1432 - 2 = 1430
Live Demo
#include <bits/stdc++.h>
using namespace std;

void updateRatingUsingELoRating(float rating1, float rating2, int ratingConstant, bool player1SuccessProb) {

   float P1, P2;
   if(rating1 > rating2){
      P1 = (1.0 / (1.0 + pow(10.0, ((rating1 - rating2) / 400.0)) ) );
      P2 = 1 - P1;
   }
   else {
      P2 = (1.0 / (1.0 + pow(10.0, ((rating2 - rating1) / 400.0)) ) );
      P1 = 1 - P2;
   }

   if (player1SuccessProb == 1) {
      rating1 = rating1 + ratingConstant * (1 - P1);
      rating2 = rating2 + ratingConstant * (0 - P2);
   }
   else {
      rating1 = rating1 + ratingConstant * (0 - P1);
      rating1 = rating1 + ratingConstant * (1 - P2);
   }

   cout<<"Ratings After the game\n";
   cout<<"Player 1 : "<<rating1<<"\t Player 2 : "<<rating2;
}

int main()
{
   float rating1 = 782, rating2 = 1432;
   int ratingConstant = 100;
   bool player1SuccessProb = 1;
   cout<<"Ratings before the game: \n";
   cout<<"Player 1 : "<<rating1<<"\t Player 2 : "<<rating2<<endl;
   if(player1SuccessProb)
      cout<<"Player 1 wins the game!\n";
   else
      cout<<"Player 2 wins the game!\n";
   updateRatingUsingELoRating(rating1, rating2, ratingConstant, player1SuccessProb);

   return 0;
}
Ratings before the game:
Player 1 : 782       Player 2 : 1432
Player 1 wins the game!
Ratings After the game
Player 1 : 784.316 Player 2 : 1429.68
string.whitespace in Python

In this tutorial, we are going to learn about the string.whitespace.
The string whitespace is pre-defined in the string module of Python3. If contains space, tab,
linefeed, return, formfeed, and vertical tab.
 Live Demo
# importing the string module
import string
# printing a string
print("Hello")
# whitespace printing
print(string.whitespace)
# printing a string
print('tutorialspoint')
If you run the above code, then you will get the following result.
Hello

tutorialspoint
If you have any doubts in the tutorial, mention them in the comment section.
How to avoid a new line with tag? - GeeksforGeeks

25 Jun, 2021
The p tag in HTML represents a paragraph. It is a block-level element which means that the text which is present inside the paragraph tag is considered as a block and it takes up the full width available. By default, the browser applies a line break before and after the p tag to separate the paragraphs. We can achieve this by adding the following style definition:  
p {
   display:inline;
}
Example 1: In this code, we have used the display attribute and set it to inline which will change the default behavior of paragraph tag and make it behave like an inline element. By using the inline property we can avoid the new line.  
html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>     <style>         p {            padding:5px;            border:1px solid black;            color:green;            font-size:24px;           }         #p2{             display:inline;          }      </style></head><body>    Random Text1    <p id="p1">Geeks for Geeks</p>     Random Text2    <p id="p2">Geeks for Geeks </p>     Random Text3 </body><script>      </script></html>
Output:  
Example 2: In this code, we have used the inline styling to avoid the new line with paragraphs. The approach is the same as above  
html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>     <style>         p {            padding:5px;            border:1px solid black;            color:green;            font-size:24px;           }      </style></head><body>    Random Text1    <p id="p2" style="display:inline">Text without new line </p>     Random Text3 </body><script>      </script></html>
Output:  
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ysachin2314
HTML-Misc
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to search a word by capital or small letter in MySQL?

You can use BINARY along with the LIKE operator. Let us first create a table −
mysql> create table DemoTable
   (
   Header text
   );
Query OK, 0 rows affected (1.09 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('Programming tutorials on MySQL');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('programming in Java language');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Program in C language');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('pRograMMing in Python language');
Query OK, 1 row affected (0.41 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+--------------------------------+
| Header                         |
+--------------------------------+
| Programming tutorials on MySQL |
| programming in Java language   |
| Program in C language          |
| pRograMMing in Python language |
+--------------------------------+
4 rows in set (0.00 sec)
Following is the query to search a word by the small letter −
mysql> select * from DemoTable where binary Header like '%programming%';
This will produce the following output −
+------------------------------+
| Header                       |
+------------------------------+
| programming in Java language |
+------------------------------+
1 row in set (0.05 sec)
NOTE: If you want to search a word by a capital letter, you need to put the word in LIKE operator.
Find missing number in a sequence in C#

Set a list.
List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
Now, get the first and last elements −
int a = myList.OrderBy(x => x).First();
int b = myList.OrderBy(x => x).Last();
In a new list, get all the elements and use the Except to get the missing numbers −
List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();
List<int> remaining = myList2.Except(myList).ToList();
Let us see the complete code −
 Live Demo
using System.Collections.Generic;
using System;
using System.Linq;

public class Program {
   public static void Main() {
      List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
      Console.WriteLine("Numbers... ");
      foreach(int val in myList) {
         Console.WriteLine(val);
      }
      int a = myList.OrderBy(x => x).First();
      int b = myList.OrderBy(x => x).Last();
      List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();
      List<int> remaining = myList2.Except(myList).ToList();
      Console.WriteLine("Remaining numbers... ");
      foreach (int res in remaining) {
         Console.WriteLine(res);
      }
   }
}
Numbers...
1
2
3
5
8
9
Remaining numbers...
4
6
7
C library function - memset()

The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.
Following is the declaration for memset() function.
void *memset(void *str, int c, size_t n)
str − This is a pointer to the block of memory to fill.
str − This is a pointer to the block of memory to fill.
c − This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
c − This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
n − This is the number of bytes to be set to the value.
n − This is the number of bytes to be set to the value.
This function returns a pointer to the memory area str.
The following example shows the usage of memset() function.
#include <stdio.h>
#include <string.h>

int main () {
   char str[50];

   strcpy(str,"This is string.h library function");
   puts(str);

   memset(str,'$',7);
   puts(str);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
This is string.h library function
$$$$$$$ string.h library function


    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