code-rag-bench/online-tutorials huggingface dataset:
How to convert a decimal number to roman using JavaScript?

To convert a decimal number to roman, try to run the following JavaScript code −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         // roman numeral
         var romanNum = new Array();
         romanNum = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
         // decimal number
         var dNum = new Array();
         dNum = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
         function decimalRoman(value) {
            if (value <= 0 || value >= 4000)
               return value;
               var romanNumeral = "";
            for (var i = 0; i<romanNum.length; i++) {
               while (value >= dNum[i]) {
                  value -= dNum[i];
                  romanNumeral += romanNum[i];
               }
            }
            return romanNumeral;
         }
         document.write(decimalRoman(39));
         document.write("<br>"+decimalRoman(145));
         document.write("<br>"+decimalRoman(520));
      </script>
   </body>
</html>
XXXIX
CXLV
DXX
Plotting at full resolution with matplotlib.pyplot, imshow() and savefig()

To plot at full resolution with matplotlib.pyplot, imshow() and savefig(), we can keep the dpi value from 600 to 1200.
Set the figure size and adjust the padding between and around the subplots.
Set random values in a given shape.
Display the data as an image, i.e., on a 2D regular raster
Save the figure with 1200 dpi.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.rand(5, 5)

plt.imshow(data, cmap="plasma")
plt.savefig("myimage.eps", dpi=1200)

plt.show()
Optimal Cost Binary Search Trees

A Binary Search Tree (BST) is a tree where the key values are stored in the internal nodes. The external nodes are null nodes. The keys are ordered lexicographically, i.e. for each internal node all the keys in the left sub-tree are less than the keys in the node, and all the keys in the right sub-tree are greater.
When we know the frequency of searching each one of the keys, it is quite easy to compute the expected cost of accessing each node in the tree. An optimal binary search tree is a BST, which has minimal expected cost of locating each node
Search time of an element in a BST is O(n), whereas in a Balanced-BST search time is O(log n). Again the search time can be improved in Optimal Cost Binary Search Tree, placing the most frequently used data in the root and closer to the root element, while placing the least frequently used data near leaves and in leaves.
Here, the Optimal Binary Search Tree Algorithm is presented. First, we build a BST from a set of provided n number of distinct keys < k1, k2, k3, ... kn >. Here we assume, the probability of accessing a key Ki is pi. Some dummy keys (d0, d1, d2, ... dn) are added as some searches may be performed for the values which are not present in the Key set K. We assume, for each dummy key di probability of access is qi.
Optimal-Binary-Search-Tree(p, q, n) 
e[1...n + 1, 0...n],  
w[1...n + 1, 0...n], 
root[1...n + 1, 0...n]  
for i = 1 to n + 1 do 
   e[i, i - 1] := qi - 1 
   w[i, i - 1] := qi - 1  
for l = 1 to n do 
   for i = 1 to n – l + 1 do 
      j = i + l – 1 e[i, j] := ∞ 
      w[i, i] := w[i, i -1] + pj + qj 
      for r = i to j do 
         t := e[i, r - 1] + e[r + 1, j] + w[i, j] 
         if t < e[i, j] 
            e[i, j] := t 
            root[i, j] := r 
return e and root 

The algorithm requires O (n3) time, since three nested for loops are used. Each of these loops takes on at most n values.
Considering the following tree, the cost is 2.80, though this is not an optimal result.
To get an optimal solution, using the algorithm discussed in this chapter, the following tables are generated.
In the following tables, column index is i and row index is j.
From these tables, the optimal tree can be formed.

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
How to apply a tag to the azure resource group using PowerShell?

Like Azure VM, we can apply the azure tags to the resource group or any other resources. The tagging works on the resource ID and in azure, all the resources come with the resource ID property.
To apply the tag to the azure resource group, we first need to use get the resource group details to use its resource ID. The below code shows that how we can apply the new tag to the azure resource group.
PS C:\> $rg = Get-AzResourceGroup -Name AnsibleTestRG
PS C:\> $tag = @{Owner='Chirag'; CostCenter='USFinance'}
PS C:\> New-AZTag -ResourceId $rg.ResourceId -Tag $tag -Verbose
close() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
close - close a file descriptor
#include <unistd.h> 

int close(int fd); 


int close(int fd); 

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).
 If fd is the last copy of a particular file descriptor the resources associated with it are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted.
close() returns zero on success. On error, -1 is returned, and errno is set appropriately.
SVr4, 4.3BSD, POSIX.1-2001. 
Not checking the return value of close() is a common but nevertheless serious programming error.  It is quite possible that errors on a  previous write(2)
operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data.  This can especially be observed with NFS
and with disk quota. 
A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a filesystem to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use
fsync(2). (It will depend on the disk hardware at this point.)
fcntl (2)
fcntl (2)
fsync (2)
fsync (2)
open (2)
open (2)
shutdown (2)
shutdown (2)
unlink (2)
unlink (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Program to find maximum product of contiguous subarray in Python

Suppose we have an array called nums, we have to find the product of elements of a contiguous subarray within an array (containing at least one number) which has the largest
product. So if the array is [1,9,2,0,2,5], the output will be 18, as contiguous subarray [1,9,2] has max product.
To solve this, we will follow these steps −
max_list := list of size nums, and fill with 0
min_list := list of size nums, and fill with 0
min_list := list of size nums, and fill with 0
for i in range 1 to length of numsmax_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]
max_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]
min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]
return the max of max_list
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def maxProduct(self, nums):
      max_list = [0] * len(nums)
      min_list = [0] * len(nums)
      max_list[0] = nums[0]
      min_list[0] = nums[0]
      for i in range(1,len(nums)):
         max_list[i] = max(max(max_list[i-1]*nums[i],min_list[i-1]*nums[i]),nums[i])
         min_list[i] = min(min(min_list[i-1]*nums[i],nums[i]),max_list[i-1]*nums[i])
      return max(max_list)
ob1 = Solution()
print(ob1.maxProduct([1,9,2,0,2,5]))
[1,9,2,0,2,5]
18
How a Preprocessor works in C/C++?

Here we will see how the preprocessors are working in C or C++. Let us see what are the preprocessors.
The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not C++ statements, so they do not end in a semicolon (;).
You already have seen a #include directive in all the examples. This macro is used to include a header file into the source file.
There are number of preprocessor directives supported by C++ like #include, #define, #if, #else, #line, etc. Let us see important directives −
The #define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is −
#define macro-name replacement-text
#include <iostream>
using namespace std;
#define PI 3.14159
int main () {
   cout << "Value of PI :" << PI << endl;
   return 0;
}
Value of PI :3.14159
There are several directives, which can be used to compile selective portions of your program's source code.This process is called conditional compilation.
The conditional preprocessor construct is much like the ‘if’ selection structure. Consider the following preprocessor code −
#ifndef NULL
#define NULL 0
#endif
You can compile a program for debugging purpose. You can also turn on or off the debugging using a single macro as follows −
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
This causes the cerr statement to be compiled in the program if the symbolic constant DEBUG has been defined before directive #ifdef DEBUG. You can use #if 0 statment to comment out a portion of the program as follows −
#if 0
code prevented from compiling
#endif
#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main () {
   int i, j;
   i = 100;
   j = 30;
   #ifdef DEBUG
   cerr <<"Trace: Inside main function" << endl;
   #endif
   #if 0
      /* This is commented part */
      cout << MKSTR(HELLO C++) << endl;
   #endif
   cout <<"The minimum is " << MIN(i, j) << endl;
   #ifdef DEBUG
      cerr <<"Trace: Coming out of main function" << endl;
   #endif
   return 0;
}
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function
How to remove specific characters from a string in Python?

The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:
>>> "Hello people".replace("e", "")
"Hllo popl"
If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:
import re
print (re.sub("e|l", " ", "Hello people"))
 OUTPUT
H   o p op
 Note: You can also use the [ ] to create group of characters to replace in regex.
How to use $ifNull with MongoDB aggregation?

The $ifNull evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value.
Let us first create a collection with documents −
> db.demo372.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e591aea2ae06a1609a00af6")
}
> db.demo372.insertOne({"FirstName":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e591aef2ae06a1609a00af7")
}
> db.demo372.insertOne({"FirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e591af42ae06a1609a00af8")
}
> db.demo372.insertOne({"FirstName":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e591afb2ae06a1609a00af9")
}
Display all documents from a collection with the help of find() method −
> db.demo372.find();
This will produce the following output −
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : null }
{ "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" }
{ "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : null }
Following is the query to use $ifNull with aggregation−
> db.demo372.aggregate(
...    [
...       {
...          $project: {
...
...             FirstName: { $ifNull: [ "$FirstName", "NOT PROVIDED" ] }
...          }
...       }
...    ]
... )
This will produce the following output −
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : "NOT PROVIDED" }
{ "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" }
{ "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : "NOT PROVIDED" }
How to convert a value to a string in JavaScript?

There are 5 ways to convert a value to a string. They are 
Concatenating empty strings
Concatenating empty strings
Template strings 
Template strings 
JSON. stringify 
JSON. stringify 
toString()
toString()
String()
String()
In the following example, all the above-mentioned methods were used to convert a value to a string and the final result was displayed as shown in the output.
Live Demo
<html>
<body>
<script>
   const value = 123;
   document.write((value + '') +" "+typeof (value + ''));
   document.write("</br>");
   document.write((`${value}`) +" "+typeof (`${value}`));
   document.write("</br>");
   document.write((JSON.stringify(value)) +" "+typeof (JSON.stringify(value)));
   document.write("</br>");
   document.write((value.toString()) +" "+typeof (value.toString()));
   document.write("</br>");
   document.write((String(value)) +" "+typeof(String(value)));
</script>
</body>
</html>
123 string
123 string
123 string
123 string
123 string
Validate Binary Search Tree in Python

Suppose we have a binary tree, determine to check whether it is a valid binary search tree (BST) or not. Assume a BST is defined as follows –
The left subtree of a node holds only nodes with keys smaller than the node's key.
The right subtree of a node holds only nodes with keys larger than the node's key.
Both the left and right subtrees must also be binary search trees.
So if the tree is like –
The output will be true.
To solve this, we will follow these steps –
Create one recursive function called solve(), this will take root, min and max, the method will be like
if root is null, then return true
if value of root <= min or value of root >= max, then return false
return the (solve(left of root, min, root value) AND solve(right of root, root value, max))
call the solve() method initially, by passing root, and – inf as min and inf as max.
Let us see the following implementation to get a better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
         else:
            temp.left = TreeNode(0)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         if data is not None:
            temp.right = TreeNode(data)
         else:
            temp.right = TreeNode(0)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def isValidBST(self, root):
      return self.solve(root,-1000000000000000000000,1000000000000000000000)
   def solve(self,root,min_val,max_val):
      if root == None or root.data == 0:
         return True
      if (root.data <= min_val or root.data >=max_val):
         return False
      return self.solve(root.left,min_val,root.data) and self.solve(root.right,root.data,max_val)
ob1 = Solution()
tree = make_tree([3,1,4,None,2,None,5])
print(ob1.isValidBST(tree))
tree = make_tree([5,1,4,None,None,3,6])
print(ob1.isValidBST(tree))
[3,1,4,null,2,null,5]
[5,1,4,null,null,3,6]
true
false
Angular Material 7 - DatePicker

The <mat-datepicker>, an Angular Directive, is used to create a datepicker control using which date can be selected from a calendar or can be input directly using input box.
In this chapter, we will showcase the configuration required to draw a datepicker control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatDatepickerModule, MatInputModule,MatNativeDateModule} from '@angular/material';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatDatepickerModule, MatInputModule,MatNativeDateModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<mat-form-field>
   <input matInput [matDatepicker] = "picker" placeholder = "Choose a date">
   <mat-datepicker-toggle matSuffix [for] = "picker"></mat-datepicker-toggle>
   <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Verify the result.
As first, we've created an input box and bind an datepicker named picker using [matDatepicker] attribute.
As first, we've created an input box and bind an datepicker named picker using [matDatepicker] attribute.
Then, we've created an datepicker named picker using mat-datepicker tag.
Then, we've created an datepicker named picker using mat-datepicker tag.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Difference between next() and hasNext() in java collections?

Java provides Iterator and ListIterator classes to retrieve the elements of the collection objects.
The hasNext() method of these interfaces returns true if the collection object has the next element else it returns false.
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class hasNextExample{
   public static void main(String[] args){
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      Iterator<String> it = list.iterator();
      System.out.println(it.hasNext());
      it.next();
      System.out.println(it.hasNext());
      it.next();
      System.out.println(it.hasNext());
   }
}
true
true
false
The next() methods of the Iterator and ListIterator returns the next element of the collection.
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class nextExample{
   public static void main(String[] args){
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
Contents of the array list (first to last):
JavaFX
Java
WebGL
OpenCV
OpenNLP
JOGL
Hadoop
HBase
Flume
Mahout
Impala
Can we have a return statement in the catch or, finally blocks in Java?

Yes, we can write a return statement of the method in catch and finally block.
There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
If we return a value in the catch block and we can return a value at the end of the method, the code will execute successfully.
If we return a value in the catch block and we can write a statement at the end of the method after return a value, the code will not execute so it became unreachable code as we know Java does not support unreachable codes.
If we return a value in the final block and no need of keeping a return value at the end of the method.
public class CatchReturn {
   int calc() {
      try {
         int x=12/0;
      } catch (Exception e) {
         return 1;
      }
      return 10;
   }
   public static void main(String[] args) {
      CatchReturn cr = new CatchReturn();
      System.out.println(cr.calc());
   }
}
1
public class FinallyReturn {
   int calc() {
      try {
         return 10;
      } catch(Exception e) {
         return 20;
      } finally {
         return 30;
      }
   }
   public static void main(String[] args) {
      FinallyReturn fr = new FinallyReturn();
      System.out.println(fr.calc());
   }
}
30
HTTP headers | Accept-Language

31 Oct, 2019
This HTTP Accept-Language header tells the server about all the languages that the client can understand. With the help of content negotiation, there will be a set of supported languages in the HTTP Accept-Language proposal then the server selects one of the proposals of those languages and place that in the content-language header. In a few cases users can change the languages manually otherwise server detects the supported language by the browser’s language. But remember one thing that it is recommended that the server never overrides an explicit decision. If the user is comfortable with a language that does not list on the server language then the server can not serve the matching language to the client in that case 406 Not Acceptable status code will be sent.
Syntax:
This is the specific language selection syntax.Accept-Language: <language>
Accept-Language: <language>
This syntax works as a wild card (selects all languages).Accept-Language: *
Accept-Language: *
Note: Multiple languages can be listed by using commas and the optional.Directives: This header accepts two directives as mentioned above and described below:
<language>: This consists of a 2-3 letter base language tag representing the language, followed by sub-tags separated by ‘-‘ . The extra information is the region and country variant (like ‘en-US’ or ‘fr-CA’)
*: It is used as a wildcard for any language present.
Note: The ;q= it defines the factor weighting, value placed in an order of preference expressed using a relative quality valueExamples:
In this example single value is on Accept-Language header that is English of US.accept-language: en-US
accept-language: en-US
In this example double value is on Accept-Language header that is English of US and French of Canada.Accept-Language: en-US,fr-CA
Accept-Language: en-US,fr-CA
In this example single value is on Accept-Language header that is English of US with the factor weighting.accept-language: en-US,en;q=0.9
accept-language: en-US,en;q=0.9
To check this Accept-Language in action go to Inspect Element -> Network check the request header for Accept-Language like below, Accept-Language is highlighted you can see.Supported Browsers: The browsers are compatible with HTTP Accept-Language header are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
Roadmap to Learn JavaScript For Beginners
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
How to update parent state in ReactJS ?

22 Dec, 2020
We can pass a function setting the state from the parent to the child component as a prop.
Creating React Application:
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
Project Structure: It will look like the following.
Project Structure
Filename: App.js
Javascript
import React, { Component } from "react";class App extends Component {    state = {    text: 'click me'  }    // Function to update state  handleUpdate = (newtext) => {    this.setState({ text: newtext })  }    render() {    return (      <div>        <Child          text={this.state.text}            // Passing a function to child          updateState={this.handleUpdate}>        </Child>      </div>    );  }}class Child extends Component {    render() {    return (      <button         // Using parent props to update parent state        onClick={() => this.props            .updateState('parent state changed')}>        {this.props.text}      </button>    )  }}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: You will see the following button on the screen:
Before Click
After clicking on the button, the following will be the output:
After Click
Picked
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get array structure with alert() in JavaScript?

06 Sep, 2019
Here is the code to see the array structure using alert() . Here below few techniquesare discussedApproach 1:
First take the values in a variable(lets arr).
Pass the array name in the alert() .
We can directly use the array name because arrayName automatically converted to arrayName.toString()
Example 1: This example follows the approach discussed above.
<!DOCTYPE HTML><html>  <head>    <title>        How to get array structure         with alert() in JavaScript?    </title></head>  <body style="text-align:center;" id="body">    <h1 style="color:green;">             GeeksForGeeks     </h1>        <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">    </p>        <button onclick="gfg_Run()">        Click here    </button>        <script>        var el_up = document.getElementById("GFG_UP");        var arr = [1, 2, 4, 6, 9];        el_up.innerHTML = "Click on the button to see the array structure using Alert().<br> Array is = "        + arr;          function gfg_Run() {            alert(arr);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
First take the values in a variable(lets arr).
Pass the array name in the alert() .
We can use .join() method for our simplicity to see the array elements each in a line.
Example 2: This example follows the approach discussed above.
<!DOCTYPE HTML><html>  <head>    <title>        How to get array structure        with alert() in JavaScript?    </title></head>  <body style="text-align:center;" id="body">    <h1 style="color:green;">             GeeksForGeeks         </h1>    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">    </p>    <button onclick="gfg_Run()">        Click here    </button>    <script>        var el_up = document.getElementById("GFG_UP");        var arr = [1, 2, 4, 6, 9];        el_up.innerHTML = "Click on the button to see the array structure using Alert().<br> Array is = "        + arr;          function gfg_Run() {            alert(arr.join('\n'));        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

11 Sep, 2019
Consider a uniprocessor system executing three tasks T1, T2 and T3, each of which is composed of an infinite sequence of jobs (or instances) which arrive periodically at intervals of 3, 7 and 20 milliseconds, respectively. The priority of each task is the inverse of its period and the available tasks are scheduled in order of priority, with the highest priority task scheduled first. Each instance of T1, T2 and T3 requires an execution time of 1, 2 and 4 milliseconds, respectively. Given that all tasks initially arrive at the beginning of the 1st milliseconds and task preemptions are allowed, the first instance of T3 completes its execution at the end of ______________ milliseconds.(A) 5(B) 10(C) 12(D) 15Answer: (C)Explanation: Periods of T1, T2 and T3 are 3ms, 7ms and 20ms.
Since priority is inverse of period, T1 is the highest priority task, then T2 and finally T3
Every instance of T1 requires 1ms, that of T2 requires 2ms and that of T3 requires 4ms
Initially all T1, T2 and T3 are ready to get processor, T1 is preferred
Second instances of T1, T2, and T3 shall arrive at 3, 7, and 20 respectively.
Third instance of T1, T2 and T3 shall arrive at 6, 14, and 40 respectively.
Time-Interval  Tasks   
 0-1            T1     
 1-2            T2      
 2-3            T2     
 3-4            T1  [Second Instance of T1 arrives] 
 4-5            T3     
 5-6            T3     
 6-7            T1  [Third Instance of T1 arrives]                        
                    [Therefore T3 is preempted] 
 7-8            T2  [Second instance of T2 arrives]                            
 8-9            T2
 9-10           T1  [Fourth Instance of T1 arrives]                          
10-11           T3
11-12           T3 [First Instance of T3 completed]
Quiz of this Question
Stranger1
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2012 | Question 40
C++ Program to count Vowels in a string using Pointer
Objective-C Typedef

The Objective-C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:.
BYTE  b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −
typedef unsigned char byte;
You can use typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
#import <Foundation/Foundation.h>

typedef struct Books {
   NSString *title;
   NSString *author;
   NSString *subject;
   int book_id;
} Book;
 
int main() {
   Book book;
   book.title = @"Objective-C Programming";
   book.author = @"TutorialsPoint";
   book.subject = @"Programming tutorial";
   book.book_id = 100;
   
   NSLog( @"Book title : %@\n", book.title);
   NSLog( @"Book author : %@\n", book.author);
   NSLog( @"Book subject : %@\n", book.subject);
   NSLog( @"Book Id : %d\n", book.book_id);

   return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-12 12:21:53.745 demo[31183] Book title : Objective-C Programming
2013-09-12 12:21:53.745 demo[31183] Book author : TutorialsPoint
2013-09-12 12:21:53.745 demo[31183] Book subject : Programming tutorial
2013-09-12 12:21:53.745 demo[31183] Book Id : 100

The #define is a Objective-C directive, which is also used to define the aliases for various data types similar to  typedef but with following differences −
The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc.
The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc.
The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.
The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.
Following is a simplest usage of #define −
#import <Foundation/Foundation.h>
 
#define TRUE  1
#define FALSE 0
 
int main( ) {
   NSLog( @"Value of TRUE : %d\n", TRUE);
   NSLog( @"Value of FALSE : %d\n", FALSE);

   return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-12 12:23:37.993 demo[5160] Value of TRUE : 1
2013-09-12 12:23:37.994 demo[5160] Value of FALSE : 0


    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
How to position text to center on an image with CSS

To positioned text to center an image, use the transform property in CSS. You can try to run the following code for centered text over an image
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .container {
            position: relative;
         }
         .topleft {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            font-size: 18px;
         }
         img {
            width: 100%;
            height: auto;
            opacity: 0.3;
         }
      </style>
   </head>
   <body>
      <h2>Image Text</h2>
      <p>Add some text to an image in the center of an image:</p>
      <div class = "container">
         <img src = "trolltunga.jpg" alt = "Norway" width = "1000" height = "300">
         <div class = "topleft">Center</div>
      </div>
   </body>
</html>
Can we use the result of a SUM() function in MySQL WHERE clause

We can use the HAVING clause rather than the WHERE in MySQL. Let us first create a table −
mysql> create table DemoTable
(
   Name varchar(50),
   Price int
);
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris',30);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',40);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris',10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Mike',44);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David',5);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------+
| Name  | Price |
+-------+-------+
| Chris | 30    |
| David | 40    |
| Chris | 10    |
| Mike  | 44    |
| David | 5     |
+-------+-------+
5 rows in set (0.00 sec)
Following is the query to use the result of SUM() function in HAVING clause −
mysql> select Name,SUM(Price) AS Total_Price from DemoTable group by Name having Total_Price > 40;
This will produce the following output −
+-------+-------------+
| Name  | Total_Price |
+-------+-------------+
| David | 45          |
| Mike  | 44          |
+-------+-------------+
2 rows in set (0.03 sec)
Python - Set Exercises

Now you have learned a lot about sets, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Check if "apple" is present in the fruits set.
fruits = {"apple", "banana", "cherry"}
if "apple"  fruits:
  print("Yes, apple is a fruit!")

Go to the Exercise section and test all of our Python Set Exercises:

Python Set Exercises

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.
find_elements_by_tag_name() driver method - Selenium Python - GeeksforGeeks

22 Nov, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_tag_name() is discussed in this article. This method returns a list with the type of elements specified. To grab a single first element, checkout – find_element_by_tag_name() driver method – Selenium PythonSyntax –  
driver.find_elements_by_tag_name("tag name")
Example – For instance, consider this page source:  
html
<html> <body>  <form id="loginForm">   <input name="1" type="text" />   <input name="1" type="password" />   <input name="1" type="submit" value="Login" />  </form> </body><html>
Now after you have created a driver, you can grab an element using –  
login_form = driver.find_elements_by_tag_name('form')
 
Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab the title of posts using the tag “h2”. Create a file called run.py to demonstrate find_elements_by_tag_name method –  
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementselements = driver.find_elements_by_tag_name("h2") # print complete elements listprint(element)
Now run using –  
Python run.py
First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output –  
Terminal Output –  
 
kumaripunam984122
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
deque max_size() function in C++ STL - GeeksforGeeks

30 Jul, 2018
The deque::max_size() is a built-in function in C++ STL which returns the maximum number of elements that a deque container can hold.
Syntax:
deque_name.max_size()
Parameters: The function does not accept any parameters.
Return Value: The function returns the maximum number of elements that a deque container can hold.
Below programs illustrate the above function:
Program 1:
// CPP program to demonstrate the// deque::max_size() function// when deque is non-empty#include <bits/stdc++.h>using namespace std;int main(){    deque<int> dq;      dq.push_back(1);    dq.push_back(10);    dq.push_back(100);    dq.push_back(50);    dq.push_back(40);    dq.push_back(23);    dq.push_back(6);      cout << "The deque elements: ";    for (auto it = dq.begin(); it != dq.end(); it++)        cout << *it << " ";      cout << "\nThe max-size of deque: " << dq.max_size();      return 0;}
The deque elements: 1 10 100 50 40 23 6 
The max-size of deque: 4611686018427387903

Program 2:
// CPP program to demonstrate the// deque::max_size() function// when deque is empty#include <bits/stdc++.h>using namespace std;int main(){    deque<int> dq;      cout << "The max-size of deque: " << dq.max_size();      return 0;}
The max-size of deque: 4611686018427387903

cpp-deque
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Operator Overloading in C++
Templates in C++ with Examples
Socket Programming in C/C++
Polymorphism in C++
Collections.UserList in Python - GeeksforGeeks

24 Jun, 2021
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Note: For more information, refer to Python List 
Python supports a List like a container called UserList present in the collections module. This class acts as a wrapper class around the List objects. This class is useful when one wants to create a list of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new behaviors for the list. This class takes a list instance as an argument and simulates a list that is kept in a regular list. The list is accessible by the data attribute of the this class.Syntax: 
collections.UserList([list])
Example 1: 
Python3
# Python program to demonstrate# userlist  from collections import UserList  L = [1, 2, 3, 4] # Creating a userlistuserL = UserList(L)print(userL.data)  # Creating empty userlistuserL = UserList()print(userL.data)
Output: 
[1, 2, 3, 4]
[]
Example 2: 
Python3
# Python program to demonstrate# userlist   from collections import UserList   # Creating a List where# deletion is not allowedclass MyList(UserList):         # Function to stop deletion    # from List    def remove(self, s = None):        raise RuntimeError("Deletion not allowed")             # Function to stop pop from    # List    def pop(self, s = None):        raise RuntimeError("Deletion not allowed")     # Driver's codeL = MyList([1, 2, 3, 4]) print("Original List") # Inserting to List"L.append(5)print("After Insertion")print(L) # Deleting From ListL.remove()
Output: 
Original List
After Insertion
[1, 2, 3, 4, 5]
 
Traceback (most recent call last):
  File "/home/9399c9e865a7493dce58e88571472d23.py", line 33, in 
    L.remove()
  File "/home/9399c9e865a7493dce58e88571472d23.py", line 15, in remove
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
 
sooda367
saurabh1990aror
Python collections-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace()
C++ Program to Implement Kadane’s Algorithm

Kadane’s algorithm is used to find out the maximum subarray sum from an array of integers. Here we shall discuss a C++ program to implement this algorithm.
Begin
Function kadanes(int array[], int length):
   Initialize
   highestMax = 0
   currentElementMax = 0
   for i = 0 to length-1
      currentElementMax = max(array[i],currentElementMax + array[i])
      highestMax = max(highestMax, currentElementMax)
   return highestMax
End
#include<iostream>
using namespace std;
int kadanes(int array[],int length) {
   int highestMax = 0;
   int currentElementMax = 0;
   for(int i = 0; i < length; i++){
      currentElementMax =max(array[i],currentElementMax + array[i]) ;
      highestMax = max(highestMax,currentElementMax);
   }
   return highestMax;
}
int main() {
   cout << "Enter the array length: ";
   int l;
   cin >> l;
   int arr[l];
   cout << "Enter the elements of array: ";
   for (int i = 0; i < l; i++) {
      cin >> arr[i];
   }
   cout << "The Maximum Sum is: "<<kadanes(arr,l) << endl;
   return 0;
}
Enter the array length: 7
Enter the elements of array:
-1
-2
-3
-4
-5
6
7
The Maximum Sum is: 13