code-rag-bench/online-tutorials huggingface dataset:
How to replace a word inside a string in PHP ? - GeeksforGeeks

31 May, 2020
Given a string containing some words and the task is to replace all the occurrences of a word within the given string str in PHP. In order to do this task, we have the following methods in PHP:
Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str.
Syntax:
str_replace( $searchVal, $replaceVal, $subjectVal, $count )

Example:
PHP
<?php// PHP program to replace all occurence// of a word inside a string    // Given string$str = "geeks for Geeks";   // Word to be replaced$w1 = "geeks";  //  Replaced by$w2 = "GEEKS";    // Using str_replace() function // to replace the word $str = str_replace($w1, $w2, $str);  // Printing the resultecho $str; ?>
GEEKS for Geeks
Method 2: Using str_ireplace() Method: The str_ireplace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str. The difference between str_replace() and str_ireplace() is that str_ireplace() is a case-insensitive.
Syntax:
str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )

Example:
PHP
<?php// PHP program to replace // a word inside a string    // Given string$str = "geeks for Geeks";   // Word to be replaced$w1 = "geeks";  //  Replaced by$w2 = "GEEKS";    // Using str_ireplace() function // replace the word $str = str_ireplace($w1, $w2, $str);  // Printing the resultecho $str; ?>
GEEKS for GEEKS
Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )

Example:
PHP
<?php// PHP program to replace // a word inside a string    // Given string$str = "geeks for Geeks";   // Word to be replaced$w1 = "geeks";  //  Replaced by$w2 = "GEEKS";    // Using preg_replace() function // to replace the word   $str = preg_replace('/bgeeksb/',$w2, $str);  // Printing the resultecho $str; ?>
geeks for Geeks
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
How to create admin login page using PHP?
Create a drop-down list that options fetched from a MySQL database in PHP
How to pass form variables from one page to other page in PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
How to calculate the difference between two dates in PHP ?
How to pass form variables from one page to other page in PHP ?
Java Math random() method with Examples

08 Jun, 2022
The java.lang.Math.random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. . When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random. 
Syntax:
public static double random()
Return Type: This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.
Example 1:To show the working of java.lang.Math.random() method. 
java
// Java program to demonstrate working// of java.lang.Math.random() methodimport java.lang.Math; class Gfg1 {     // driver code    public static void main(String args[])    {        // Generate random number        double rand = Math.random();         // Output is different everytime this code is executed        System.out.println("Random Number:" + rand);    }}
Output:
0.5568515217910215
Example 2:To show the working of java.lang.Math.random() method. 
Now to get random integer numbers from a given fixed range, we take a min and max variable to define the range for our random numbers, both min and max are inclusive in the range.
java
// Java program to demonstrate working// of java.lang.Math.random() methodimport java.lang.Math; class Gfg2 {     // driver code    public static void main(String args[])    {        // define the range        int max = 10;        int min = 1;        int range = max - min + 1;         // generate random numbers within 1 to 10        for (int i = 0; i < 10; i++) {            int rand = (int)(Math.random() * range) + min;             // Output is different everytime this code is executed            System.out.println(rand);        }    }}
Output:
6
8
10
10
5
3
6
10
4
2
ashutosh44
Java-lang package
java-math
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
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
CSS | linear-gradient() Function

01 Jul, 2022
The linear-gradient() function is an inbuilt function in CSS which is used to set the linear gradient as the background image.Syntax:  
background-image: linear-gradient( direction, color1, color2, ... )
Parameters: This function accepts one direction parameter and many color parameters which are listed below:  
direction: This parameter is used to define the starting point and direction along with the gradient effect.
color1, color2, ...: This parameter is used to hold the color value followed by its optional stop position.
Below examples illustrate the linear-gradient() function in CSS: Example 1:  
html
<!DOCTYPE html><html>    <head>        <title>linear-gradient function</title>        <style>        .gradient {            height: 100px;            background-image: linear-gradient(green, yellow, blue);            Text-align:center;            padding-top:40px;            font-size:40px;            color:white;            font-weight:bold;        }        h2 {            text-align:center;        }        </style>    </head>    <body>        <h2>linear-gradient: Top to Bottom property</h1>        <div class="gradient">GeeksforGeeks</div>    </body></html>
Output:  
Example 2:  
html
<!DOCTYPE html><html>    <head>        <title>linear-gradient function</title>        <style>        .gradient {            height: 100px;            background-image: linear-gradient(to left, green, yellow, blue);            Text-align:center;            padding-top:40px;            font-size:40px;            color:white;            font-weight:bold;        }        h2 {            text-align:center;        }        </style>    </head>    <body>        <h2>linear-gradient: Right to Left property</h1>        <div class="gradient">GeeksforGeeks</div>    </body></html>
Output:  
Supported Browser:
Google Chrome 26
Edge 12
Internet Explorer 10
Firefox 16
Opera 12.1
Safari 7 
ysachin2314
geeksr3ap
CSS-Functions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructor Overloading in C++

28 Jun, 2021
Prerequisites: Constructors in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.This concept is known as Constructor Overloading and is quite similar to function overloading.  
Overloaded constructors essentially have the same name (exact name of the class) and differ by number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.  
 
CPP
// C++ program to illustrate// Constructor overloading#include <iostream>using namespace std; class construct{ public:    float area;         // Constructor with no parameters    construct()    {        area = 0;    }         // Constructor with two parameters    construct(int a, int b)    {        area = a * b;    }         void disp()    {        cout<< area<< endl;    }}; int main(){    // Constructor Overloading    // with two different constructors    // of class name    construct o;    construct o2( 10, 20);         o.disp();    o2.disp();    return 1;}
Output: 
0
200
 
Related Articles :  
Destructors in C++
quiz on constructors in C++
Output of C++ programs | Set 26 (Constructors)
Output of C++ programs | Set 27(Constructors and Destructors)
This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
utkarshgupta04092003
cpp-constructor
cpp-overloading
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Templates in C++ with Examples
C++ Program to Check the Connectivity of Directed Graph Using DFS

To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have only outward edge but no inward edge, so that node will be unvisited from any other starting node.
In this case the traversal algorithm is recursive DFS traversal.
Input: Adjacency matrix of a graph
Output: The Graph is connected.
Input: The start node u and the visited node to mark which node is visited.
Output: Traverse all connected vertices.
Begin
   mark u as visited
   for all vertex v, if it is adjacent with u, do
      if v is not visited, then
         traverse(v, visited)
   done
End
Input: The graph.
Output: True if the graph is connected.
Begin
   define visited array
   for all vertices u in the graph, do
      make all nodes unvisited
      traverse(u, visited)
      if any unvisited node is still remaining, then
         return false
   done
   return true
End
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 0, 0, 0},
   {0, 0, 1, 0, 0},
   {0, 0, 0, 1, 1},
   {1, 0, 0, 0, 0},
   {0, 1, 0, 0, 0}};
void traverse(int u, bool visited[]) {
   visited[u] = true;      //mark v as visited
   for(int v = 0; v<NODE; v++) {
      if(graph[u][v]) {
         if(!visited[v])
            traverse(v, visited);
      }
   }
}
bool isConnected() {
   bool *vis = new bool[NODE];
   //for all vertex u as start point, check whether all nodes are visible or not
   for(int u; u < NODE; u++) {
      for(int i = 0; i<NODE; i++)
         vis[i] = false;    //initialize as no node is visited
         traverse(u, vis);
         for(int i = 0; i<NODE; i++) {
            if(!vis[i])         //if there is a node, not visited by traversal, graph is not connected
               return false;
         }
   }
   return true;
}
int main() {
   if(isConnected())
      cout << "The Graph is connected.";
   else
      cout << "The Graph is not connected.";
}
The Graph is connected.
jQuery - contents( ) Method

The contents( ) method finds all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
Here is the simple syntax to use this method −
selector.contents( )

Here is the description of all the parameters used by this method −
NA
NA
Consider you have an html file index.htm which we would use in an iframe.
Try the following example which shows how you can access the objects in an iframe from a parent window. This operation has become possible just because of contents() method.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script>
         $(document).ready(function(){
            var $content = $("iframe").contents();
            $content.find("body").append("I'm in an iframe!");
         });
      </script>
   </head>
	
   <body>
      <iframe src = "/jquery/index.htm" width = "300" height = "100"></iframe>
   </body>
</html>
This will produce following result −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
How to use ArrayAdapter in android to create a simple listview in Kotlin?

This example demonstrates how to use ArrayAdapter in android to create a simple listview in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/simpleListView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:divider="#000"
      android:dividerHeight="4dp" />
</RelativeLayout>
Step 3 − Add the following code to MainActivity.kt
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val arrayAdapter: ArrayAdapter<*>
      val list = arrayOf(
         "Cristiano Ronaldo",
         "Messi",
         "Neymar",
         "Isco",
         "Hazard",
         "Mbappe",
         "Hazard",
         "Ziyech",
         "Suarez"
      )
      // access the listView from xml file
      val listView = findViewById<ListView>(R.id.listView)
      arrayAdapter = ArrayAdapter(
         this,
         android.R.layout.simple_list_item_1, list
      )
      listView.adapter = arrayAdapter
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.q36">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
How to Transpose a DataFrame in R? - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss how to transpose dataframe in R Programming Language. Transposing means converting rows to columns and columns to rows
R
# create a dataframedata = data.frame(col1=c(1:5),                  col2=c(6:10),                  col3=c(11:15),                  col4=c(16:20))  # assign row names to dataframerow.names(data) = c("r1","r2","r3","r4","r5")  # displaydata
Output:
   col1 col2 col3 col4
r1    1    6   11   16
r2    2    7   12   17
r3    3    8   13   18
r4    4    9   14   19
r5    5   10   15   20
Here we are using t() function which stands for transpose to transpose a dataframe
Syntax: t(dataframe)
where dataframe is the input dataframe
Example:
R
# create a dataframedata = data.frame(col1 = c(1:5),                   col2 = c(6:10),                  col3 = c(11:15),                  col4 = c(16:20))  # assign row names to dataframerow.names(data) = c("r1","r2","r3",                    "r4","r5")  # display transposed dataframet(data)
Output:
    r1 r2 r3 r4 r5
col1  1  2  3  4  5
col2  6  7  8  9 10
col3 11 12 13 14 15
col4 16 17 18 19 20
Here we are using data.table data structure to transpose the dataframe, we are using transpose() method to do this
Syntax: transpose(dataframe)
Example:
R
# load modulelibrary(data.table)  # create a dataframedata = data.frame(col1=c(1:5),                  col2=c(6:10),                  col3=c(11:15),                  col4=c(16:20))  # assign row names to dataframerow.names(data) = c("r1","r2","r3","r4","r5")  # display transposed dataframe# using data.tabletranspose(data)
Output:
 V1 V2 V3 V4 V5
1  1  2  3  4  5
2  6  7  8  9 10
3 11 12 13 14 15
4 16 17 18 19 20
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
HTML - Phrase Elements

Phrase elements add structural information to text fragments. The usual meanings of phrase elements are following −
NONE
<abbr>pvt. or inc.</abbr><br />
<acronym>HTML</acronym><br />
<cite>Citation</cite><br />
<em>Emphasized text</em><br />
<strong>Strong text</strong><br />
<dfn>Definition term</dfn><br />
<code>Computer code text</code><br />
<samp>Sample computer code text</samp><br />
<kbd>Keyboard text</kbd><br />
<var>Variable</var><br />
This will produce following result −
Document wide identifier
Specifies the direction of the text
Document wide identifier
Specifies a title to associate with the element.
Helps to include inline casecadubf style sheet.
Sets the language code.
Script runs when a mouse click
Script runs when a mouse double-click
Script runs when mouse button is pressed
Script runs when mouse button is released
Script runs when mouse pointer moves over an element
Script runs when mouse pointer moves
Script runs when mouse pointer moves out of an element
Script runs when key is pressed and released
Script runs when key is pressed
Script runs when key is released

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to change background color of TableView items on iOS?

Changing the background color of table view items is different from changing the background color of the table view. New programmers may often confuse between these two things, In this post, we will be seeing how to change the background color of TableView items i.e. cells.
So let’s get started.
For changing the background color of the table view cell, you should change the contentView.backgroundColor property of the cell.
Add the below code in your cellForRowAt indexPath method,
cell.contentView.backgroundColor = UIColor.cyan
Your method should look like something below,
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
   cell.contentView.backgroundColor = UIColor.cyan
   return cell
}
Now run the project to see the effect.
What is NaN in JavaScript?

NaN is a JavaScript property, which is "Not-a-Number" value. This shows it is not a legal number.
Here’s the syntax −
Number.NaN
To find out whether value is NaN, use the Number.isNaN() or isNan() method. Here’s an example to check −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button onclick="display()">Check</button>
      <p id="test"></p>
      <script>
         function display() {
            var a = "";
            a = a + isNaN(6234) + ": 6234<br>";
            a = a + isNaN(-52.1) + ": -52.1<br>";
            a = a + isNaN('Hello') + ": 'Hello'<br>";
            a = a + isNaN(NaN) + ": NaN<br>";
            a = a + isNaN('') + ": ''<br>";
            a = a + isNaN(0) + ": 0<br>";
            a = a + isNaN(false) + ": false<br>";
            document.getElementById("test").innerHTML = a;
         }
      </script>
   </body>
</html>
Python os.fstat() Method

Python method fstat() returns information about a file associated with the fd. Here is the structure returned by fstat method −
st_dev − ID of device containing file
st_dev − ID of device containing file
st_ino − inode number
st_ino − inode number
st_mode − protection
st_mode − protection
st_nlink − number of hard links
st_nlink − number of hard links
st_uid − user ID of owner
st_uid − user ID of owner
st_gid − group ID of owner
st_gid − group ID of owner
st_rdev − device ID (if special file)
st_rdev − device ID (if special file)
st_size − total size, in bytes
st_size − total size, in bytes
st_blksize − blocksize for filesystem I/O
st_blksize − blocksize for filesystem I/O
st_blocks − number of blocks allocated
st_blocks − number of blocks allocated
st_atime − time of last access
st_atime − time of last access
st_mtime − time of last modification
st_mtime − time of last modification
st_ctime − time of last status change
st_ctime − time of last status change
Following is the syntax for fstat() method −
os.fstat(fd)

fd − This is the file descriptor for which system information is to be returned.
fd − This is the file descriptor for which system information is to be returned.
This method returns information about a file associated with the fd.
The following example shows the usage of chdir() method.
#!/usr/bin/python

import os, sys

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

# Now get  the touple
info = os.fstat(fd)

print "File Info :", info

# Now get uid of the file
print "UID of the file :%d" % info.st_uid

# Now get gid of the file
print "GID of the file :%d" % info.st_gid

# Close opened file
os.close( fd)
When we run above program, it produces following result −
File Info : (33261, 3753776L, 103L, 1, 0, 0, 
            102L, 1238783197, 1238786767, 1238786767)
UID of the file :0
GID of the file :0


    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 pass Text Area Data to Python CGI script?

TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
The result of this code is the following form −
Type your text here...
 Submit
Below is textarea.cgi script to handle input given by web browser −
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('textcontent'):
   text_content = form.getvalue('textcontent')
else:
   text_content = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"
Python Program to Find Element Occurring Odd Number of Times in a List

When it is required to find an element that occurs odd number of times in a list, a method can be defined. This method iterates through the list and checks to see if the elements in the nested loops match. If they do, the counter is incremented. If that count is not divisible by 2, the specific element of the list is returned as the result. Otherwise, -1 is returned as the result.
Below is a demonstration of the same −
 Live Demo
def odd_occurence(my_list, list_size):

   for i in range(0, list_size):
      count = 0
      for j in range(0, list_size):
         if my_list[i] == my_list[j]:
            count+= 1

      if (count % 2 != 0):
         return my_list[i]

   return -1
my_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56 ]
print("The list is :")
print(my_list)
n = len(my_list)
print("The length is :")
print(n)
print("The method to find the element that occurs odd number of times is called ")
print("The element that occurs odd number of times is :")
print(odd_occurence(my_list, n))
The list is :
[34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
The length is :
17
The method to find the element that occurs odd number of times is called
The element that occurs odd number of times is :
34
A method named ‘odd_occurence’ is defined, which takes the list and its size as parameters.
A method named ‘odd_occurence’ is defined, which takes the list and its size as parameters.
The listed size is taken as the range and the list is iterated over.
The listed size is taken as the range and the list is iterated over.
Two nested loops are iterated, and if the element in the list matches the first and second loop iterations, the ‘count’ variable is incremented.
Two nested loops are iterated, and if the element in the list matches the first and second loop iterations, the ‘count’ variable is incremented.
If the ‘count’ variable is an odd number, the specific element in the list is returned.
If the ‘count’ variable is an odd number, the specific element in the list is returned.
A list of integers is defined and is displayed on the console.
A list of integers is defined and is displayed on the console.
The length of the list is stored in a variable.
The length of the list is stored in a variable.
The method is called by passing relevant parameters.
The method is called by passing relevant parameters.
The output is displayed on the console.
The output is displayed on the console.
C++ Library - <wostringstream>

It is an output stream class to operate on strings of wide characters.
Below is definition of std::wostringstream.
typedef basic_ostringstream<wchar_t> wostringstream;
charT − Character type.
charT − Character type.
traits − Character traits class that defines essential properties of the characters used by stream objects.
traits − Character traits class that defines essential properties of the characters used by stream objects.
 Print
 Add Notes
 Bookmark this page
House Robber II in C++

Consider, you are a professional robber. And you are planning to rob houses along a street. Each house has a certain amount of money stored. All houses are arranged in a circle. That means the first house is the neighbor of the last house. We have to keep in mind that the adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. So if we have a list of integers representing the amount of money of each house, determine the maximum amount of money you can rob in one night without alerting the police. So if the array is [1,2,3,1], then the output will be 4.
To solve this, we will follow these steps −
We are using one module called solve(), that will take the array, start and end, that will act like below −
ans := nums[start]
create one table for dynamic programming, that’s name is dp, and size is same as nums size.
dp[start] := nums[start]
for i := start + 1 to endlast := dp[i – 1]lastToLast := 0 when i – 2, otherwise dp[i – 2]dp[i] := maximum of nums[i] + lastToLast and lastans := max of dp[i] and ans
last := dp[i – 1]
lastToLast := 0 when i – 2, otherwise dp[i – 2]
dp[i] := maximum of nums[i] + lastToLast and last
ans := max of dp[i] and ans
return ans
Robbing is done like below −
n := size of nums
if n is zero, then return 0
if n = 1, then return nums[0]
return maximum of solve(nums, 0, n - 2), solve(nums, 1, n – 1)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector <int>& nums, int start, int end){
      int ans = nums[start];
      vector <int> dp(nums.size());
      dp[start] = nums[start];
      for(int i = start + 1; i <= end; i++){
         int last = dp[i - 1];
         int lastToLast = i - 2 < start? 0 : dp[i - 2];
         dp[i] = max(nums[i] + lastToLast, last);
         ans = max(dp[i], ans);
      }
      return ans;
   }
   int rob(vector<int>& nums) {
      int n = nums.size();
      if(!n)return 0;
      if(n == 1)return nums[0];
      return max(solve(nums, 0, n - 2), solve(nums, 1, n - 1));
   }
};
main(){
   vector<int> v = {1,2,3,5};
   Solution ob;
   cout << ob.rob(v);
}
[1,2,3,5]
7
How to add a Submit button after the end of the tableview using Swift?

To add a submit button at the end of a table view, we can make use of table view footers. Let’s see this with help of an example where we’ll add a footer view to our table, and inside the table, we will add code for adding button at the bottom of the table view.
Create a new project first, then inside the view controller add the following code which will initialize the table, add a section and a few rows to the table.
func initTableView() {
   let tableView = UITableView()
   tableView.frame = self.view.frame
   tableView.dataSource = self
   tableView.delegate = self
   tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
   tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
   self.view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
   cell?.layer.backgroundColor = colorLiteral(red: 0.2392156869, green:
   0.6745098233, blue: 0.9686274529, alpha: 1)
   cell?.textLabel?.text = "cell at \(indexPath.row)"
   return cell!
}
Now, call the first function, initTableView() inside the view did a load or viewDidAppear method of your view controller.
Now add the following code which will tell the table to give some height to its rows and footer.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return 60
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
   return 100
}
Make sure you have confirmed your class to UITableViewDataSource and UITableViewDelegate, otherwise these methods above will appear as an error.
Now, let’s add a footer view and a button to the footer view.
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
   let footerView = UIView()
   footerView.backgroundColor = colorLiteral(red: 0.9686274529, green:
   0.78039217, blue: 0.3450980484, alpha: 1)
   footerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height:
   100)
   let button = UIButton()
   button.frame = CGRect(x: 20, y: 10, width: 300, height: 50)
   button.setTitle("CustomButton", for: .normal)
   button.setTitleColor( colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
   button.backgroundColor = colorLiteral(red: 0.721568644, green:
   0.8862745166, blue: 0.5921568871, alpha: 1)
   footerView.addSubview(button)
   return footerView
}
When we run the above code on our device, below is the result that’s produced. You can add a custom action to the button and customize it according to requirement.
Java Program for Longest Common Subsequence

Following is the Java program for Longest Common Subsequence −
 Live Demo
public class Demo{
   int subseq(char[] a, char[] b, int a_len, int b_len){
      int my_arr[][] = new int[a_len + 1][b_len + 1];
      for (int i = 0; i <= a_len; i++){
         for (int j = 0; j <= b_len; j++){
            if (i == 0 || j == 0)
            my_arr[i][j] = 0;
            else if (a[i - 1] == b[j - 1])
            my_arr[i][j] = my_arr[i - 1][j - 1] + 1;
            else
            my_arr[i][j] = max_val(my_arr[i - 1][j], my_arr[i][j - 1]);
         }
      }
      return my_arr[a_len][b_len];
   }
   int max_val(int val_1, int val_2){
      return (val_1 > val_2) ? val_1 : val_2;
   }
   public static void main(String[] args){
      Demo my_inst = new Demo();
      String my_str_1 = "MNSQR";
      String my_str_2 = "PSQR";
      char[] a = my_str_1.toCharArray();
      char[] b = my_str_2.toCharArray();
      int a_len = a.length;
      int b_len = b.length;
      System.out.println("The length of the longest common subsequence is"+ " " + my_inst.subseq(a, b, a_len,       b_len));
   }
}
The length of the longest common subsequence is 3
A class named Demo contains a function called "subseq" which returns the longest common subsequence for the given strings i.e str_1[0 to len(str_1-1) , str_2(0 to len(str_2-1) //2 'for' loops are iterated over the length of both the strings and if both 'i' and 'j' are 0, then, the array's specific indices are assigned to 0. Otherwise, my_arr[length of first string +1][length of second string +1] is built.
The main function defines a new instance of the Demo class and defines two strings my_str_1 and my_str_2. Both the strings are converted to arrays and their lengths are stored in separate variables. The function is called on these values.
This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array.
Python dictionary copy() Method

Python dictionary  method copy() returns a shallow copy of the dictionary.
Following is the syntax for copy() method −
dict.copy()

NA
NA
This method returns a shallow copy of the dictionary.
The following example shows the usage of copy() method.
#!/usr/bin/python

dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print "New Dictionary : %s" %  str(dict2)
When we run above program, it produces following result −
New Dictionary : {'Age': 7, 'Name': 'Zara'}


    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
C++ Program to Check Whether a Given Tree is Binary Search Tree

Binary Search Tree is a binary tree data structure in which we have 3 properties
The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key.
The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key.
The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key.
The left and right trees of a subtree each must also be a binary search tree.
The left and right trees of a subtree each must also be a binary search tree.
Begin
   function BSTUtill()
      If node is equals to NULL then
         Returns 1.
      If data of node is less than minimum or greater than
      maximum data then
         Return 0.
      Traverse left and right sub-trees recursively. 
End.
 Live Demo
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct n {
   int d;
   n* l;
   n* r;
};
int BSTUtil(n* node, int min, int max);
int isBST(n* node) {
   return(BSTUtil(node, INT_MIN, INT_MAX));
}
int BSTUtil(struct n* node, int min, int max) {
   if (node==NULL)
      return 1;
   if (node->d < min || node->d > max)
      return 0;
      return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max);
}
n* newN(int d) {
   n* nod = new n;
   nod->d = d;
   nod->l = NULL;
   nod->r = NULL;
   return nod;
}
int main() {
   n *root = newN(7);
   root->l = newN(6);
   root->r = newN(10);
   root->l->l = newN(2);
   root->l->r = newN(4);
   if (isBST(root))
      cout<<"The Given Tree is a BST"<<endl;
   else
      cout<<"The Given Tree is not a BST"<<endl;
      n *root1 = newN(10);
      root1->l = newN(6);
      root1->r = newN(11);
      root1->l->l = newN(2);
      root1->l->r = newN(7);
   if (isBST(root1))
      cout<<"The Given Tree is a BST"<<endl;
   else
      cout<<"The Given Tree is not a BST"<<endl;
      return 0;
}
The Given Tree is not a BST
The Given Tree is a BST
jQuery - ajaxError( callback ) Method

The ajaxError( callback ) method attaches a function to be executed whenever an AJAX request fails. This is an Ajax Event.
Here is the simple syntax to use this method −
$(document).ajaxError( callback )

Here is the description of all the parameters used by this method −
callback − The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function. A third argument, an exception object, is passed if an exception occured while processing the request.
callback − The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function. A third argument, an exception object, is passed if an exception occured while processing the request.
Following is a simple example a simple showing the usage of this method.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
			
            $("#driver").click(function(event){
               /* Assume result.text does not exist. */
               $('#stage1').load('/jquery/result.text');
            });

            $(document).ajaxError(function(event, request, settings ){
               $("#stage2").html("<h1>Error in loading page.</h1>");
            });
				
         });
      </script>
   </head>

   <body>
      <p>Click on the button to load result.text file:</p>
		
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
		
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
		
      <input type = "button" id = "driver" value = "Load Data" />
   </body>
</html>
This will produce following result −
Click on the button to load result.text file −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Character streams in Java

Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.
The Reader and Writer classes (abstract) are the super classes of all the character stream classes: classes that are used to read/write character streams. Following are the character array stream classes provided by Java −
The following Java program reads data from a particular file using FileReader and writes it to another, using FileWriter.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOStreamsExample {
   public static void main(String args[]) throws IOException {
      //Creating FileReader object
      File file = new File("D:/myFile.txt");
      FileReader reader = new FileReader(file);
      char chars[] = new char[(int) file.length()];
      //Reading data from the file
      reader.read(chars);
      //Writing data to another file
      File out = new File("D:/CopyOfmyFile.txt");
      FileWriter writer = new FileWriter(out);
      //Writing data to the file
      writer.write(chars);
      writer.flush();
      System.out.println("Data successfully written in the specified file");
   }
}
Data successfully written in the specified file
How to get the next auto-increment id in MySQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record.
To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.
Creating a table, with “id” as auto-increment.
mysql> create table NextIdDemo
   -> (
   -> id int auto_increment,
   -> primary key(id)
   -> );
Query OK, 0 rows affected (1.31 sec)
Inserting records into the table.
mysql> insert into NextIdDemo values(1);
Query OK, 1 row affected (0.22 sec)

mysql>  insert into NextIdDemo values(2);
Query OK, 1 row affected (0.20 sec)

mysql>  insert into NextIdDemo values(3);
Query OK, 1 row affected (0.14 sec)
To display all the records.
mysql> select *from NextIdDemo;
The following is the output.
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.04 sec)

We have inserted 3 records above. Therefore, the next id must be 4.
The following is the syntax to know the next id.
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "yourDatabaseName"
AND TABLE_NAME = "yourTableName"
The following is the query.
mysql> SELECT AUTO_INCREMENT
    -> FROM information_schema.TABLES
    -> WHERE TABLE_SCHEMA = "business"
    -> AND TABLE_NAME = "NextIdDemo";
Here is the output that displays the next auto-increment.
+----------------+
| AUTO_INCREMENT |
+----------------+
|              4 |
+----------------+
1 row in set (0.25 sec)
Change data type of given numpy array in Python

We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array.
We can check the type of numpy array using the dtype class. Let's check the data type of sample numpy array.
# importing numpy library
import numpy as np
# creating numpy array
array = np.array([1, 2, 3, 4, 5])
# printing the data type of the numpy array
print(array.dtype)
If you run the above code, you will get the following results.
int32
Let's see how to change the data type of a numpy array from float64 to &int32.
# importing numpy library
import numpy as np
# creating numpy array of type float64
array = np.array([1.5, 2.6, 3.7, 4.8, 5.9])
# type of array before changing
print(f'Before changing {array.dtype}')
# changing the data type of numpy array using astype() method
array = array.astype(np.int32)
# type of array after changing
print(f'\nAfter changing {array.dtype}')
If you run the above program, you will get the following results.
Before changing float64
After changing int32
We can use any data type present in the numpy module or general data types of Python. You can find the list of data types present in numpy here.
I hope you have learned the conversion of data types for numpy array. If you are facing any problems related to the tutorial, mention them in the comment section.
Python Blockchain - Developing Client

A client is somebody who holds TPCoins and transacts those for goods/services from other vendors on the network including his own. We should define a Client class for this purpose. To create a globally unique identification for the client, we use PKI (Public Key Infrastructure). In this chapter, let us talk about this in detail.
The client should be able to send money from his wallet to another known person. Similarly, the client should be able to accept money from a third party. For spending money, the client would create a transaction specifying the sender’s name and the amount to be paid. For receiving money, the client will provide his identity to the third party − essentially a sender of the money. We do not store the balance amount of money the client holds in his wallet. During a transaction, we will compute the actual balance to ensure that the client has sufficient balance to make the payment.
To develop the Client class and for the rest of the code in the project, we will need to import many Python libraries. These are listed below −
# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections

In addition to the above standard libraries, we are going to sign our transactions, create hash of the objects, etc. For this, you will need to import the following libraries −
# following imports are required by PKI
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5

In the next chapter, let us talk about client class.

    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 make colorbar orientation horizontal in Python using Matplotlib?

To make colorbar orientation horizontal in Python, we can use orientation="horizontal" in the argument.
Set the figure size and adjust the padding between and around the subplots.
Create random x, y and z data points using numpy.
Create a figure and a set of subplots.
Use scatter() method to plot x, y and z data points.
Create a colorbar for a ScalarMappable instance, with horizontal orientation.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

x, y, z = np.random.rand(3, 50)
f, ax = plt.subplots()

points = ax.scatter(x, y, c=z, s=50, cmap="plasma")
f.colorbar(points, orientation="horizontal")

plt.show()