code-rag-bench/online-tutorials huggingface dataset:
StringCharacterIterator setText() method in Java with Examples

29 Jul, 2019
The setText() method of java.text.StringCharacterIterator class in Java is used to set the current text that is to be read by this StringCharacterIterator. This method takes the text to be set as a parameter and sets the text of this StringCharacterIterator at that text.
Syntax:
public void setText(String text)

Parameter: This method takes the text to be set as a parameter and sets the text of this StringCharacterIterator.
Return Value: This method do not return anything.
Exception: This method do not throw any Exception.
Program:
// Java program to demonstrate// the above method  import java.text.*;import java.util.*;  public class StringCharacterIteratorDemo {    public static void main(String[] args)    {          String text = "GeeksForGeeks";          StringCharacterIterator            stringCharacterIterator            = new StringCharacterIterator(text);          System.out.println("Current Text: "                           + text);          text = "Geeks for Geeks";          stringCharacterIterator.setText(text);          System.out.println("New text: "                           + text);    }}
Current Text: GeeksForGeeks
New text: Geeks for Geeks

Reference: https://docs.oracle.com/javase/9/docs/api/java/text/StringCharacterIterator.html#setText-java.lang.String-
Java-Functions
Java-StringCharacterIterator
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
GATE | GATE-CS-2007 | Question 61

30 Sep, 2020
Consider the table employee(empId, name, department, salary) and the two queries Q1 ,Q2 below. Assuming that department 5 has more than one employee, and we want to find the employees who get higher salary than anyone in the department 5, which one of the statements is TRUE for any arbitrary employee table?
Q1 : Select e.empId
     From employee e
     Where not exists
        (Select * From employee s where s.department = “5” and 
                                        s.salary >=e.salary)
Q2 : Select e.empId
     From employee e
     Where e.salary > Any
    (Select distinct salary From employee s Where s.department = “5”)

(A) Q1 is the correct query(B) Q2 is the correct query(C) Both Q1 and Q2 produce the same answer.(D) Neither Q1 nor Q2 is the correct queryAnswer: (A)Explanation: First note that they asked for Anyone (= All) not for Any. Here, Everyone means all of the group. Anyone means all or any part of the group. 
Let the employee(empId, name, department, salary) have the following instance. 
empId name department salary ———————————-
e1 ------- A-------- 1---------10000
e2 -------B ------- 5 ---------5000
e3 -------C ------- 5----------7000
e4 -------D ------- 2----------2000
e5 -------E ------- 3----------6000

Now the actual result should contain empId : e1 , e3 and e5 ( because they have salary greater than anyone employee in the department ‘5’) 
——————————————————– Now Q1 : 
Note : EXISTS(empty set) gives FALSE, and NOT EXISTS(empty set) gives TRUE.  
Select e.empId
From employee e
Where not exists
(Select * From employee s where s.department = “5” and
s.salary >=e.salary)


Q1 will result only empId e1. ——————————————————— whereas Q2 :  
Select e.empId
From employee e
Where e.salary > Any
(Select distinct salary From employee s Where s.department = “5”)


Q2 will result empId e1, e3 and e5. ——————————————————– Hence Q1 is the correct query. 
Note that if we use ALL in place of Any in second query then this will be correct. 
Option (A) is correct.Quiz of this Question
m_never_dies
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
Python | Pandas dataframe.rename_axis()

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
dataframe.rename_axis() is used to rename the axes of the index or columns in dataframe.
Syntax: DataFrame.rename_axis(mapper, axis=0, copy=True, inplace=False)
Parameters:mapper : [scalar, list-like, optional] Value to set the axis name attribute.axis : int or string, default 0copy : [iboolean, default True] Also copy underlying datainplace :boolean, default False
Returns: renamed : type of caller or None if inplace=True
For link to CSV file Used in Code, click here
Example #1: Replace team “Boston Celtics” with “Omega Warrior” in the nba.csv file
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # Printing the first 10 rows of the # dataframe for visualizationdf[:10]
Output:
We are going to change the row indexes and increase the value by twice.
# this will Increase the row index value by twicedf.rename_axis(lambda x:x * 2, axis ="index")
Output: 
Example #2: Changing the column name
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # this will add '_X' at the end of each column namedf.rename_axis(lambda x:x+"_X", axis ="columns")
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
How do you directly overlay a scatter plot on top of a jpg image in Matplotlib?

To directly overlay a scatter plot on top of a jpg image, we can take the following steps −
Load an image "bird.jpg", using imread() method, Read an image from a file into an array.
Load an image "bird.jpg", using imread() method, Read an image from a file into an array.
Now display data as an image.
Now display data as an image.
To plot scatter points on the image make lists for x_points and y_points.
To plot scatter points on the image make lists for x_points and y_points.
Generate random numbers for x and y and append in lists.
Generate random numbers for x and y and append in lists.
Using scatter method, plot x and y points.
Using scatter method, plot x and y points.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = plt.imread("logo2.jpg")
im = plt.imshow(data)
x_points = []
y_points = []
for i in range(10):
   x_points.append(np.random.randint(0, 700))
   y_points.append(np.random.randint(0, 700))
plt.scatter(x_points, y_points, c=x_points)
plt.show()
Python os.dup() Method

Python method dup() returns a duplicate of file descriptor fd which can be used in place of original descriptor.
Following is the syntax for dup() method −
os.dup(fd);

fd − This is the original file descriptor.
fd − This is the original file descriptor.
This method returns a duplicate of file descriptor.
The following example shows the usage of dup() method −
#!/usr/bin/python

import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Get one duplicate file descriptor
d_fd = os.dup( fd )

# Write one string using duplicate fd
os.write(d_fd, "This is test")

# Close a single opened file
os.closerange( fd, d_fd)

print "Closed all the files successfully!!"
When we run above program, it produces following result −
Closed all the files successfully!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Designing Deterministic Finite Automata (Set 5) - GeeksforGeeks

08 Jun, 2020
Prerequisite: Designing finite automataIn this article, we will see some designing of Deterministic Finite Automata (DFA).
Problem-1: Construction of a minimal DFA accepting set of strings over {a, b} in which every ‘a’ is followed by a ‘bb’.Explanation: The desired language will be like:
L1 = {ε, abb, abbabb, bbbbabb, abbabbabbabbabbbb, ..............}
Here as we can see that each string of the language containing ‘a’ is just followed by ‘bb’ but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘a’ just followed by ‘bb’.
L2 = {ba, baab, bbaba, ..............}
The state transition diagram of the language containing ‘a’ just followed by ‘bb’ will be like:In the above DFA, state ‘v’ is the initial and final state too which on getting ‘b’ as the input it remains in the state of itself and on getting ‘a’ as the input it transit to a normal state ‘W’ which on getting ‘a’ as the input it transit to the dead state ‘Z’ and getting ‘b’ as the input it transit to the normal state ‘X’ which on getting ‘b’ as input it transit to the final state ‘V’ and on getting ‘a’ as the input it transit to the same dead state ‘Z’. The state ‘Z’ is called dead state because on getting any input it can not transit to any of the final states ever.
Problem-2: Construction of a minimal DFA accepting set of strings over {a, b} in which every ‘a’ is never be followed by ‘bb’.Explanation: The desired language will be like:
L1 = {ε, a, aa, aabaa, b, bb, bbbbba, ..............}
Here as we can see that each string of the language containing ‘a’ is never be followed by ‘bb’ but the below language is not accepted by this DFA because some of the string of the below language containing ‘a’ is followed by ‘bb’.
L2 = {abb, babbabb, bbaba, ..............}
The state transition diagram of the language containing ‘a’ never be followed by ‘bb’ will be like:In the above DFA, the state ‘W’ is the initial and final state too which on getting ‘b’ as the input it remains in the state of itself and on getting ‘a’ as the input it transit to the final state ‘X’ which on getting ‘a’ as the input it remains in the state of ‘X’ and getting ‘b’ as the input it transit to the final state ‘Y’ which on getting ‘a’ as the input it transit to another final state ‘X’ and the final state ‘Y’ on getting ‘b’ as the input it transit to the dead state ‘Z’. The state ‘Z’ is called dead state because on getting any input it can not go to any of the final state ever.
rajatnagarr
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Semaphores in Process Synchronization
Inter Process Communication (IPC)
Introduction of Operating System - Set 1
Turing Machine in TOC
Introduction of Pushdown Automata
Difference between DFA and NFA
Construct Pushdown Automata for given languages
Recursive and Recursive Enumerable Languages in TOC
Comparing two ValueTuple<T1, T2> in C# - GeeksforGeeks

29 Dec, 2019
ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in .NET Framework 4.7 or higher version. It allows you to store a data set that contains multiple values that may or may not be related to each other.You can also compare the instance of two value tuples with each other by using CompareTo(ValueTuple<T1, T2>) method. Or in other words, with the help of CompareTo method you are allowed to compare the current ValueTuple<T1, T2> instance to a specified ValueTuple<T1, T2> instance. This method also compares nested value tuples with each other.
Syntax:
public int CompareTo (ValueTuple<T1, T2> other);

Return Type: The return type of this method is System.Int32. And it always returns a signed integer that indicates the relative position of this instance and other in the sort order as shown in the below list:
Negative integer for the instance precedes another.
Zero for the instance and others have the same position in the sort order.
Positive integer for the instance follows another.
Example 1:
// C# program to illustrate the // use of CompareTo methodusing System;  namespace exampleofvaluetuple {  class GFG {      // Main Method    static void Main(string[] args)    {        // 2-ValueTuple        var t1 = (43, 34);        var t2 = (78, 98);        Console.WriteLine("Result 1: {0}", t1.CompareTo(t2));          // 2-ValueTuple        var p1 = (86, 99);        var p2 = (44, 22);        Console.WriteLine("Result 2: {0}", p1.CompareTo(p2));          // 2-ValueTuple        var q1 = (10, 20);        var q2 = (10, 20);        Console.WriteLine("Result 3: {0}", q1.CompareTo(q2));    }}}
Result 1: -1
Result 2: 1
Result 3: 0

Example 2:
// C# program to illustrate the // use of CompareTo methodusing System;  namespace exampleofvaluetuple {  class GFG {      // Main Method    static void Main(string[] args)    {        // 2-ValueTuple        var t1 = (44, 34);        var t2 = (44, 45);          // Using CompareTo Method        if (t1.CompareTo(t2) == 0) {              Console.WriteLine("Value tuples are equal!!");        }        else {              Console.WriteLine("Value tuples are not equal!!");        }    }}}
Value tuples are not equal!!

CSharp-ValueTuple
CSharp-ValueTuple-Methods
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
PyQt5 - How to make text center align for non-editable ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can center align the text of combo box and combo box should remain non-editable. By default the combo box text is left align and combo box don’t have any alignment method of its own.
In order to center align the text we have to do the following –
1. Create a combo box2. Make line edit object from combo box3. Center align the line edit4. Make the line edit on editable
Note : Because of the line edit object combo box will become editable therefore there is a need to make it non editable
Syntax :
# getting the line edit of combo box
line_edit = self.combo_box.lineEdit()

# setting line edit alignment to the center
line_edit.setAlignment(Qt.AlignCenter)

# setting line edit to read only
line_edit.setReadOnly(True)

Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # geek list        geek_list = ["Sayian", "Super Saiyan", "Super Sayian 2", "Super Sayian B"]          # making it editable        self.combo_box.setEditable(True)          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # getting the line edit of combo box        line_edit = self.combo_box.lineEdit()          # setting line edit alignment to the center        line_edit.setAlignment(Qt.AlignCenter)          # setting line edit to read only        line_edit.setReadOnly(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Matplotlib.axes.Axes.set_clip_on() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_clip_on() function in axes module of matplotlib library is used to set whether the artist uses clipping.
Syntax: Axes.set_clip_on(self, b)
Parameters: This method accepts only one parameters.
b: This parameter contains the boolean value.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.set_clip_on() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Ellipse  delta = 45.0  angles = np.arange(0, 360 + delta, delta)ells = [Ellipse((2, 2), 5, 2, a) for a in angles]  fig, ax = plt.subplots()  for e in ells:    e.set_alpha(0.1)    ax.add_artist(e)      ax.set_xlim(-1, 5)ax.set_ylim(-1, 5)ax.set_clip_on(False)    fig.suptitle('matplotlib.axes.Axes.set_clip_on()\ function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.patches as mpatchesimport matplotlib.transforms as mtransforms    x0 = -0.1  arrow_style ="simple, head_length = 15,\ head_width = 30, tail_width = 10"rect_style ="simple, tail_width = 25"line_style ="simple, tail_width = 1"  fig, ax = plt.subplots()  trans = mtransforms.blended_transform_factory(ax.transAxes, ax.transData)  y_tail = 5y_head = 15arrow1 = mpatches.FancyArrowPatch((x0, y_tail),                                   (x0, y_head),                                   arrowstyle = arrow_style,                                   transform = trans)arrow1.set_clip_on(False)ax.add_patch(arrow1)  ax.set_xlim(0, 30)ax.set_ylim(0, 80)    fig.suptitle('matplotlib.axes.Axes.set_clip_on() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to print Dataframe in Python without Index? - GeeksforGeeks

13 Sep, 2021
Prerequisites: Pandas
When printing a dataframe, by default, index appears with the output but this can be removed if required. To print the dataframe without indices index parameter in to_string() must be set to False.
Syntax: 
df.to_string(index = False)
Approach:
Import module
Create a simple dataframe .
Set index to false in to_string()
Print result
Implementation using this approach is given below
Example 1: 
Python3
import pandas as pd df = pd.DataFrame({"Name": ["sachin", "sujay", "Amara", "shivam",                            "Manoj"],                    "Stream": ["Humanities", "Science", "Science",                              "Commerce", "Humanities"]},                   index=["A", "B", "C", "D", "E"]) print("THIS IS THE ORIGINAL DATAFRAME:")display(df)print() print("THIS IS THE DATAFRAME  WITHOUT INDEX VAL")print(df.to_string(index=False))
Output:
Example 2:   
Python3
import pandas as pd df = pd.DataFrame(["Geeks", "for", "geek"],                   index=["A", "B", "C"]) print("THIS IS THE ORIGINAL DATAFRAME:")display(df)print() print("THIS IS THE DATAFRAME  WITHOUT INDEX VAL")print(df.to_string(index=False))
Output:
sweetyty
rajeev0719singh
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Strict equality vs Loose equality in JavaScript.

The loose equality operator ‘==’ allows us to compare two or more operands by converting their value to a common type first and then checking for the equality between them.
strict equality operator ‘===’ allows us to compare two or more operands by checking the equality between the values as well as their types . It returns true only if the values and the type both match with the other operand.
Following is the code for loose equality vs strict equality in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Strict equality vs Loose equality</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button see some comparisons using loose equality and strict equality</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "According to loose equality <br>";
      if (1 == "1") {
         resEle.innerHTML += "1 is equal to '1'<br>";
      }
      if (undefined == null) {
         resEle.innerHTML += "undefined is equal to null <br>";
      }
      resEle.innerHTML += "<br>According to strict equality <br>";
      if (1 === "1") {
         resEle.innerHTML += "1 is equal to '1'<br>";
      } else {
         resEle.innerHTML += "1 is not equal to '1'<br>";
      }
      if (undefined === null) {
         resEle.innerHTML += "undefined is equal to null <br>";
      } else {
         resEle.innerHTML += "undefined is not equal to null <br>";
      }
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
How to sort an Array using STL in C++?

Here we will see how to sort an array using STL functions in C++. So if the array is like A = [52, 14, 85, 63, 99, 54, 21], then the output will be [14 21 52 54 63 85 99]. To sort we have one function called sort() present in the header file <algorithm>. The code is like below −
 Live Demo
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
   int arr[] = {52, 14, 85, 63, 99, 54, 21};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Array before sorting: ";
   for (int i = 0; i < n; i++)
      cout << arr[i] << " ";
   sort(arr, arr + n);
   cout << "\nArray after sorting: ";
   for (int i = 0; i < n; i++)
      cout << arr[i] << " ";
}
Array before sorting: 52 14 85 63 99 54 21
Array after sorting: 14 21 52 54 63 85 99
If elseif else or ternary operator to compare numbers PHP?

You can use any of them, but a more professional approach is using the ternary operator (?). Performance of both if-else and ternary operator is the same.
Let’s say we have the following two variable values −
$value1=10;
$value2=0;
We need to compare the above 2 variable values.
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$value1=10;
$value2=0;
$data=550000;
$output=$value1 ? $value2 : $value2 ? : $data;
echo "The value is=",$output;
?>
</body>
</html>
This will produce the following output
The value is=550000
VB.Net - Nested If Statements

It is always legal in VB.Net to nest If-Then-Else statements, which means you can use one If or ElseIf statement inside another If ElseIf statement(s).
The syntax for a nested If statement is as follows −
If( boolean_expression 1)Then
   'Executes when the boolean expression 1 is true 
   If(boolean_expression 2)Then
         'Executes when the boolean expression 2 is true 
   End If
End If

You can nest ElseIf...Else in the similar way as you have nested If statement.
Module decisions
   Sub Main()
      'local variable definition
      Dim a As Integer = 100
      Dim b As Integer = 200
      ' check the boolean condition 
      
      If (a = 100) Then
         ' if condition is true then check the following 
         If (b = 200) Then
            ' if condition is true then print the following 
            Console.WriteLine("Value of a is 100 and b is 200")
         End If
      End If
      Console.WriteLine("Exact value of a is : {0}", a)
      Console.WriteLine("Exact value of b is : {0}", b)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200


    63 Lectures 
     4 hours 

 Frahaan Hussain

    103 Lectures 
     12 hours 

 Arnold Higuit

    60 Lectures 
     9.5 hours 

 Arnold Higuit

    97 Lectures 
     9 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Explain VirtualizedList component usage in ReactNative?

The VirtualizedList component is best when your list is massively big in size.VirtualizedList helps in better performance and memory usage.As user scrolls, the data is shown to the user.
The basic component of VirtualizedList is as follows &minuns;
<VirtualizedList data={DATA} initialNumToRender={4} renderItem={renderItem} keyExtractor={keyExtractor} getItemCount={getItemCount} getItem={getItem} />
Here is a working example of VirtualizedList.
To work with VirtualizedList import it first as follows −
import { SafeAreaView, View, VirtualizedList, StyleSheet, Text } from 'react-native';
The code for VirtualizedList is as follows −
<SafeAreaView>
   <VirtualizedList
      data={DATA}
      initialNumToRender={4}
      renderItem={({ item }) => <Item title={item.title} />}
      keyExtractor={item => item.id}
      getItemCount={getItemCount}
      getItem={getItem}
   />
</SafeAreaView>
The initial items that we want to display to render is 4. The renderItem property is used to display the item on the screen. It makes use of custom Item component defined as shown below −
const Item = ({ title })=> {
   return (
      <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
      </View>
   );
}
The keyExtractor defines the unique key for each item.
keyExtractor={item => item.id}
The props getItemCount gets the total count of items that will be displayed to the user. Right now it calls the function getItemCount that is defined as follows.
const getItemCount = (data) => {
   return 100;
}
getItemCount={getItemCount}
The getITem props is meant to get the data to be displayed.It calls the method getItem and it is defined as follows −
const getItem = (data, index) => {
   return {
      id: index,
      title: 'test'
   }
}
getItem={getItem}
The complete code to display VirtualizedList is as follows −
import React from 'react';
import { SafeAreaView, View, VirtualizedList, StyleSheet, Text } from 'react-native';
const DATA = [];
const getItem = (data, index) => {
   return {
      id: index,
      title: 'test'
   }
}
const getItemCount = (data) => {
   return 100;
}
const Item = ({ title })=> {
   return (
      <View style={styles.item}>
         <Text style={styles.title}>{title}</Text>
         </View>
      );
   }
   const VirtualizedListExample = () => {
      return (
         <SafeAreaView>
            <VirtualizedList
               data={DATA}
               initialNumToRender={4}
               renderItem={({ item }) => <Item title={item.title} />}
               keyExtractor={item => item.id}
               getItemCount={getItemCount}
               getItem={getItem}
         />
         </SafeAreaView>
      );
   }
   const styles = StyleSheet.create({
   item: {
      backgroundColor: '#ccc',
      height: 100,
      justifyContent: 'center',
      marginVertical: 8,
      marginHorizontal: 16,
      padding: 20,
   },
   title: {
      fontSize: 32,
   },
});
export default VirtualizedListExample;
PHP & MySQL - Update Records Example

PHP uses mysqli query() or mysql_query() function to update records in a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)

$sql
Required - SQL query to update records in a MySQL table.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to update a record in a table −
Copy and paste the following example as mysql_example.php −
<html>
   <head>
      <title>Updating MySQL Table</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
		 
         if ($mysqli->query('UPDATE tutorials_tbl set tutorial_title = "Learning Java" where tutorial_id = 4')) {
            printf("Table tutorials_tbl updated successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not update table: %s<br />", $mysqli->error);
         }
   
         $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
		 
         $result = $mysqli->query($sql);
           
         if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
               printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", 
                  $row["tutorial_id"], 
                  $row["tutorial_title"], 
                  $row["tutorial_author"],
                  $row["submission_date"]);               
            }
         } else {
            printf('No record found.<br />');
         }
         mysqli_free_result($result);
         $mysqli->close();
      ?>
   </body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script.
Connected successfully.
Table tutorials_tbl updated successfully.
Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
Id: 4, Title: Learning Java, Author: Mahesh, Date: 2021
Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML Computer Code
Tryit: HTML kbd element
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

function Car(props) {
  return <h2>I am a { props.brand }!</h2>;
}

function Garage() {
  const carName = "Ford";
  return (
    <>
	    <h1>Who lives in my garage?</h1>
	    <Car brand={ carName } />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
Longest Substring with At Most K Distinct Characters in C++

Suppose we have a string; we have to calculate the length of the longest substring T that contains at most k distinct characters.
So, if the input is like s = "eceba", k = 2, then the output will be 3 as T is "ece" which its length is 3.
To solve this, we will follow these steps −
ans := 0
ans := 0
Define one map m
Define one map m
n := size of s
n := size of s
x := 0
x := 0
for initialize j := 0, i := 0, when j < n, update (increase j by 1), do −(increase m[s[j]] by 1)if m[s[j]] is same as 1, then −(increase x by 1)while (x > k and i <= j), do −(decrease m[s[i]] by 1)if m[s[i]] is same as 0, then −(decrease x by 1)(increase i by 1)ans := maximum of ans and (j - i + 1)
for initialize j := 0, i := 0, when j < n, update (increase j by 1), do −
(increase m[s[j]] by 1)
(increase m[s[j]] by 1)
if m[s[j]] is same as 1, then −(increase x by 1)
if m[s[j]] is same as 1, then −
(increase x by 1)
(increase x by 1)
while (x > k and i <= j), do −(decrease m[s[i]] by 1)if m[s[i]] is same as 0, then −(decrease x by 1)(increase i by 1)
while (x > k and i <= j), do −
(decrease m[s[i]] by 1)
(decrease m[s[i]] by 1)
if m[s[i]] is same as 0, then −(decrease x by 1)
if m[s[i]] is same as 0, then −
(decrease x by 1)
(decrease x by 1)
(increase i by 1)
(increase i by 1)
ans := maximum of ans and (j - i + 1)
ans := maximum of ans and (j - i + 1)
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int lengthOfLongestSubstringKDistinct(string s, int k) {
      int ans = 0;
      unordered_map<char, int> m;
      int n = s.size();
      int x = 0;
      for (int j = 0, i = 0; j < n; j++) {
         m[s[j]]++;
         if (m[s[j]] == 1)
            x++;
         while (x > k && i <= j) {
            m[s[i]]--;
            if (m[s[i]] == 0)
               x--;
            i++;
         }
         ans = max(ans, j - i + 1);
      }
      return ans;
   }
};
main() {
   Solution ob;
   cout << (ob.lengthOfLongestSubstringKDistinct("eceba", 2));
}
"eceba", 2
3
Change the size of Bootstrap input groups

Change the size of the input groups, by adding the relative form sizing classes like .input-group-lg, input-group-sm, input-group-xs to the .input-group itself.
You can try to run the following code to change the size of input groups in Bootstrap:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div style = "padding: 100px 100px 10px;">
         <form class = "bs-example bs-example-form" role = "form">
            <div class = "input-group input-group-lg">
            <span class = "input-group-addon">@</span>
            <input type = "text" class = "form-control" placeholder = "Twitterhandle">
         </div>
         <br>
         <div class = "input-group">
            <span class = "input-group-addon">@</span>
            <input type = "text" class = "form-control" placeholder = "Twitterhandle">
         </div>
         <br>
         <div class = "input-group input-group-sm">
            <span class = "input-group-addon">@</span>
            <input type = "text" class = "form-control" placeholder = "Twitterhandle">
         </div>
      </form>
   </body>
</html>
IsNullOrWhiteSpace() Method in C#

This method returns true if the entered string has only whitespace characters or is null.
Let say you checked for null value −
bool val1 = string.IsNullOrWhiteSpace(null);
The above returns True, since the string is “null”. In the same way, check it for whitespace character.
Here is the entire example that checks for null and whitespace.
 Live Demo
using System;
using System.IO;
public class Demo {
   public static void Main() {
      bool val1 = string.IsNullOrWhiteSpace(null);
      bool val2 = string.IsNullOrWhiteSpace(" ");
      bool val3 = string.IsNullOrWhiteSpace("5");
      Console.WriteLine(val1);
      Console.WriteLine(val2);
      Console.WriteLine(val3);
   }
}
True
True
False
What does buffer flush means in C++ ?

The buffer flush is used to transfer of computer data from one temporary storage area to computers permanent memory. If we change anything in some file, the changes we see on the screen are stored temporarily in a buffer.
In C++, we can explicitly have flushed to force the buffer to be written. If we use std::endl, it adds one new line character, and also flush it. If this is not used, we can explicitly use flush. In the following program at first no flush is used. Here we are trying to print the numbers, and wait for one seconds. For the first, we cannot see any output until all of the numbers are stored into the buffer, then the numbers will be displayed in one shot.
In the second example, each number will be printed, then wait for some time then print the next one again. So for using the flush, it sends the output to the display.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
   for (int x = 1; x <= 5; ++x) {
      cout >> x >> " ";
      this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
   }
   cout >> endl;
}
1 2 3 4 5
output will be printed at once after waiting 5 seconds
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
   for (int x = 1; x <= 5; ++x) {
      cout >> x >> " " >> flush;
      this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
   }
   cout >> endl;
}
1 2 3 4 5
Printing each character and wait for one second
Decrypt String from Alphabet to Integer Mapping in Python

Suppose we have a string s that is formed by digits ('0' - '9') and '#'. We have to map s to one English lowercase characters as follows −
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
We have to find the string formed after mapping. We are taking one assumption that a unique mapping will always exist. So if the input is like “10#11#12”, then it will be “jkab”. As 10# is j, 11# is k, 1 is a and 2 is b.
To solve this, we will follow these steps −
create one map to hold all characters and their corresponding ASCII values
create one map to hold all characters and their corresponding ASCII values
ans := 0, and map[‘’] := ‘’, ad i := length of string – 1
ans := 0, and map[‘’] := ‘’, ad i := length of string – 1
while i > 0if s[i] is #, thentemp := “”for j := i – 2 to i, temp := temp + s[j]ans := map[temp] + ansdecrease i by 3otherwise ans := map[s[i]] + ans, and decrease i by 1
while i > 0
if s[i] is #, thentemp := “”for j := i – 2 to i, temp := temp + s[j]ans := map[temp] + ansdecrease i by 3
if s[i] is #, then
temp := “”
temp := “”
for j := i – 2 to i, temp := temp + s[j]
for j := i – 2 to i, temp := temp + s[j]
ans := map[temp] + ans
ans := map[temp] + ans
decrease i by 3
decrease i by 3
otherwise ans := map[s[i]] + ans, and decrease i by 1
otherwise ans := map[s[i]] + ans, and decrease i by 1
return ans
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def freqAlphabets(self, s):
      m = {}
      x = 'a'
      for i in range(1, 27):
         m[str(i)] = x
         x = chr(ord(x) + 1)
      ans = ""
      m['']=''
      i = len(s) - 1
      while i >= 0:
         if s[i] == "#":
            temp = ""
            for j in range(i - 2, i):
               temp += s[j]
            ans = m[str(temp)] + ans
            i -= 3
         else:
            ans = m[s[i]] + ans
            i -= 1
      return ans
ob1 = Solution()
print(ob1.freqAlphabets("17#123#5621#"))
"17#123#5621#"
qawefu
Python Tuple cmp() Method

Python tuple method cmp() compares elements of two tuples.
Following is the syntax for cmp() method −
cmp(tuple1, tuple2)

tuple1 − This is the first tuple to be compared
tuple1 − This is the first tuple to be compared
tuple2 − This is the second tuple to be compared
tuple2 − This is the second tuple to be compared
If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers.
If numbers, perform numeric coercion if necessary and compare.
If numbers, perform numeric coercion if necessary and compare.
If either element is a number, then the other element is "larger" (numbers are "smallest").
If either element is a number, then the other element is "larger" (numbers are "smallest").
Otherwise, types are sorted alphabetically by name.
Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both tuples and share the same data, the result is a tie, meaning that 0 is returned.
The following example shows the usage of cmp() method.
#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz'), (456, 'abc')
print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)
tuple3 = tuple2 + (786,);
print cmp(tuple2, tuple3)
When we run above program, it produces following result −
-1
1
-1


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to remove grid lines from an image in Python Matplotlib?

To remove grid lines from an image, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Load an image from a file.
Convert the image from one color space to another.
To remove grid lines, use ax.grid(False).
Display the data as an image, i.e., on a 2D regular raster.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import cv2

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

img = cv2.imread('bird.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

plt.grid(False)
plt.imshow(img)

plt.show()
Clicking on elements within an SVG using XPath (Selenium WebDriver).

We can click on elements with an SVG using XPath in Selenium. The SVG element has the tag name svg. It has attributes like width, height, viewBox, and so on.
To click the element with svg, we should identify the element then utilize the Actions class. We shall first move to that element with the moveToElement method and then apply the click method on it.
Finally, to actually perform the action, we have to use the build and execute methods. To identify the svg element with xpath, there is the local-name() function available.
Let us look at the html code of a svg element.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class SVGElement{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element, enter text
      WebElement m= driver.findElement(By.xpath ("//*[local-name()='svg' and @data-icon='home']/*[localname()='path']"));
      // Action class to move and click element
      Actions a = new Actions(driver);
      a.moveToElement(m).
      click().build().perform();
   }
}
IPC through shared memory

Shared memory is a memory shared between two or more processes. However, why do we need to share memory or some other means of communication?
To reiterate, each process has its own address space, if any process wants to communicate with some information from its own address space to other processes, then it is only possible with IPC (inter process communication) techniques. As we are already aware, communication can be between related or unrelated processes.
Usually, inter-related process communication is performed using Pipes or Named Pipes. Unrelated processes (say one process running in one terminal and another process in another terminal) communication can be performed using Named Pipes or through popular IPC techniques of Shared Memory and Message Queues.
We have seen the IPC techniques of Pipes and Named pipes and now it is time to know the remaining IPC techniques viz., Shared Memory, Message Queues, Semaphores, Signals, and Memory Mapping.
We know that to communicate between two or more processes, we use shared memory but before using the shared memory what needs to be done with the system calls, let us see this −
Create the shared memory segment or use an already created shared memory segment (shmget())
Create the shared memory segment or use an already created shared memory segment (shmget())
Attach the process to the already created shared memory segment (shmat())
Attach the process to the already created shared memory segment (shmat())
Detach the process from the already attached shared memory segment (shmdt())
Detach the process from the already attached shared memory segment (shmdt())
Control operations on the shared memory segment (shmctl())
Control operations on the shared memory segment (shmctl())
Here we will create two processes. One can write and another can read. Let us see how the reader and writer processes are working using shared memory.
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
main() {
   key_t my_key = ftok("shmfile",65); // ftok function is used to generate unique key
   int shmid = shmget(my_key,1024,0666|IPC_CREAT); // shmget returns an ide in shmid
   char *str = (char*) shmat(shmid,(void*)0,0); // shmat to join to shared memory
   cout<<"Write Data : ";
   fgets(str, 50, stdin);
   printf("Data written in memory: %s\n",str);
   //detach from shared memory
   shmdt(str);
}
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
main() {
   key_t my_key = ftok("shmfile",65); // ftok function is used to generate unique key
   int shmid = shmget(my_key,1024,0666|IPC_CREAT); // shmget returns an ide in shmid
   char *str = (char*) shmat(shmid,(void*)0,0); // shmat to join to shared memory
   printf("Data read from memory: %s\n",str);
   shmdt(str);
   shmctl(shmid,IPC_RMID,NULL); // destroy the shared memory
}