code-rag-bench/online-tutorials huggingface dataset:
Solidity - Events

Event is an inheritable member of a contract. An event is emitted, it stores the arguments passed in transaction logs. These logs are stored on blockchain and are accessible using address of the contract till the contract is present on the blockchain. An event generated is not accessible from within contracts, not even the one which have created and emitted them.
An event can be declared using event keyword.
//Declare an Event
event Deposit(address indexed _from, bytes32 indexed _id, uint _value);

//Emit an event
emit Deposit(msg.sender, _id, msg.value);
Try the following code to understand how an event works in Solidity.
First Create a contract and emit an event.
pragma solidity ^0.5.0;

contract Test {
   event Deposit(address indexed _from, bytes32 indexed _id, uint _value);
   function deposit(bytes32 _id) public payable {      
      emit Deposit(msg.sender, _id, msg.value);
   }
}
Then access the contract's event in JavaScript code.
var abi = /* abi as generated using compiler */;
var ClientReceipt = web3.eth.contract(abi);
var clientReceiptContract = ClientReceipt.at("0x1234...ab67" /* address */);

var event = clientReceiptContract.Deposit(function(error, result) {
   if (!error)console.log(result);
});
It should print details similar to as following −
{
   "returnValues": {
      "_from": "0x1111...FFFFCCCC",
      "_id": "0x50...sd5adb20",
      "_value": "0x420042"
   },
   "raw": {
      "data": "0x7f...91385",
      "topics": ["0xfd4...b4ead7", "0x7f...1a91385"]
   }
}


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Spring Boot - Build Systems

In Spring Boot, choosing a build system is an important task. We recommend Maven or Gradle as they provide a good support for dependency management. Spring does not support well other build systems.
Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release. You do not need to provide a version for dependencies in the build configuration file. Spring Boot automatically configures the dependencies version based on the release. Remember that when you upgrade the Spring Boot version, dependencies also will upgrade automatically.
Note − If you want to specify the version for dependency, you can specify it in your configuration file. However, the Spring Boot team highly recommends that it is not needed to specify the version for dependency.
For Maven configuration, we should inherit the Spring Boot Starter parent project to manage the Spring Boot Starters dependencies. For this, simply we can inherit the starter parent in our pom.xml file as shown below.
<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.8.RELEASE</version>
</parent>
We should specify the version number for Spring Boot Parent Starter dependency. Then for other starter dependencies, we do not need to specify the Spring Boot version number. Observe the code given below −
<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>
We can import the Spring Boot Starters dependencies directly into build.gradle file. We do not need Spring Boot start Parent dependency like Maven for Gradle. Observe the code given below −
buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot automatically configures the dependency based on the version.
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
}

    102 Lectures 
     8 hours 

 Karthikeya T

    39 Lectures 
     5 hours 

 Chaand Sheikh

    73 Lectures 
     5.5 hours 

 Senol Atac

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac

    69 Lectures 
     5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
ustat() - Unix, Linux System Call

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

#include <unistd.h>    /* libc[45] */ 

#include <ustat.h>     /* glibc2 */ 

int ustat(dev_t dev, struct ustat *ubuf); 


int ustat(dev_t dev, struct ustat *ubuf); 

ustat() returns information about a mounted file system.
dev is a device number identifying a device containing
a mounted file system.
ubuf is a pointer to a ustat structure that contains the following
members:
daddr_t f_tfree;                /* Total free blocks */
ino_t   f_tinode;               /* Number of free inodes */
char    f_fname[6];             /* Filsys name */
char    f_fpack[6];             /* Filsys pack name */

The last two fields, f_fname and f_fpack, are not implemented and will
always be filled with null bytes (’\0’).
On success, zero is returned and the ustat structure pointed to by
ubuf will be filled in.  On error, -1 is returned, and
errno is set appropriately.
SVr4. 
ustat() is deprecated and has only been provided for compatibility.
All new programs should use
statfs(2)
instead.
The HP-UX version of the
ustat structure has an additional field,
f_blksize, that is unknown elsewhere. 
HP-UX warns:
For some file systems, the number of free inodes does not change.
Such file systems will return -1 in the field
f_tinode. For some file systems, inodes are dynamically allocated.
Such file systems will return the current number of free inodes.
stat (2)
stat (2)
statfs (2)
statfs (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Matplotlib.figure.Figure.get_figheight() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The get_figheight() method figure module of matplotlib library is used to get the figure height as a float.
Syntax: get_figheight(self)
Parameters: This method does not accept any parameters.
Returns: This method return the figure height as a float.
Below examples illustrate the matplotlib.figure.Figure.get_figheight() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np     fig = plt.figure()       ax = Subplot(fig, 111) fig.add_subplot(ax)    w = fig.get_figheight()ax.text(0.2, 0.5,        "Value Return by get_figheight() : "        + str(w),        fontweight ="bold")    fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_figheight()\function Example', fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np    fig = plt.figure(edgecolor = "red", figsize =(7, 6))        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])     xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))    w = fig.get_figheight()ax.text(1.5, 0,        "Value Return by get_figheight() : "        + str(w),        fontweight ="bold")     fig.canvas.draw()  fig.suptitle('matplotlib.figure.Figure.get_figheight()\function Example', fontweight ="bold")   plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Floyd Warshall Algorithm

Floyd-Warshall algorithm is used to find all pair shortest path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the minimum distance from any node to all other nodes in the graph.
At first, the output matrix is the same as the given cost matrix of the graph. After that, the output matrix will be updated with all vertices k as the intermediate vertex.
The time complexity of this algorithm is O(V^3), where V is the number of vertices in the graph.
Input: The cost matrix of the graph.
0 3 6 ∞ ∞ ∞ ∞
3 0 2 1 ∞ ∞ ∞
6 2 0 1 4 2 ∞
∞ 1 1 0 2 ∞ 4
∞ ∞ 4 2 0 2 1
∞ ∞ 2 ∞ 2 0 1
∞ ∞ ∞ 4 1 1 0

Output:
Matrix of all pair shortest path.
0 3 4 5 6 7 7
3 0 2 1 3 4 4
4 2 0 1 3 2 3
5 1 1 0 2 3 3
6 3 3 2 0 2 1
7 4 2 3 2 0 1
7 4 3 3 1 1 0
floydWarshal(cost)
Input − The cost matrix of given Graph.
Output: Matrix to for shortest path between any vertex to any vertex.
Begin
   for k := 0 to n, do
      for i := 0 to n, do
         for j := 0 to n, do
            if cost[i,k] + cost[k,j] < cost[i,j], then
               cost[i,j] := cost[i,k] + cost[k,j]
         done
      done
   done
   display the current cost matrix
End
#include<iostream>
#include<iomanip>
#define NODE 7
#define INF 999
using namespace std;

//Cost matrix of the graph
int costMat[NODE][NODE] = {
   {0, 3, 6, INF, INF, INF, INF},
   {3, 0, 2, 1, INF, INF, INF},
   {6, 2, 0, 1, 4, 2, INF},
   {INF, 1, 1, 0, 2, INF, 4},
   {INF, INF, 4, 2, 0, 2, 1},
   {INF, INF, 2, INF, 2, 0, 1},
   {INF, INF, INF, 4, 1, 1, 0}
};

void floydWarshal() {
   int cost[NODE][NODE];    //defind to store shortest distance from any node to any node
   for(int i = 0; i<NODE; i++)
      for(int j = 0; j<NODE; j++)
         cost[i][j] = costMat[i][j];     //copy costMatrix to new matrix

   for(int k = 0; k<NODE; k++) {
      for(int i = 0; i<NODE; i++)
         for(int j = 0; j<NODE; j++)
            if(cost[i][k]+cost[k][j] < cost[i][j])
               cost[i][j] = cost[i][k]+cost[k][j];
   }

   cout << "The matrix:" << endl;
   for(int i = 0; i<NODE; i++) {
      for(int j = 0; j<NODE; j++)
         cout << setw(3) << cost[i][j];
      cout << endl;
   }
}

int main() {
   floydWarshal();
}
The matrix:
0  3  5  4  6  7  7
3  0  2  1  3  4  4
5  2  0  1  3  2  3
4  1  1  0  2  3  3
6  3  3  2  0  2  1
7  4  2  3  2  0  1
7  4  3  3  1  1  0
array::operator[ ] in C++ STL - GeeksforGeeks

28 Sep, 2021
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays.
This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of array, while this operator causes undefined behavior.
Syntax : 
arrayname[position]
Parameters :
Position of the element to be fetched.
Returns :
Direct reference to the element at the given position.
Examples: 
Input :  myarray = {1, 2, 3, 4, 5}
         myarray[2]
Output : 3

Input :  myarray = {1, 2, 3, 4, 5}
         myarray[4]
Output : 5
Errors and Exceptions1. If the position is not present in the array, it shows undefined behavior. 2. It has a no exception throw guarantee otherwise.
C++
// CPP program to illustrate// Implementation of [] operator#include <iostream>#include <array>using namespace std; int main(){    array<int,5> myarray{ 1, 2, 3, 4, 5 };    cout << myarray[4];    return 0;}
Output: 
5
Application Given an array of integers, print all the integers present at even positions. 
Input  :1, 2, 3, 4, 5
Output :1 3 5
Explanation - 1, 3 and 5 are at position 0,2,4 which are even
Algorithm 1. Run a loop till the size of the array. 2. Check if the position is divisible by 2, if yes, print the element at that position.
C++
// CPP program to illustrate// Application of [] operator#include <iostream>#include <array>using namespace std; int main(){    array<int,5> myarray{ 1, 2, 3, 4, 5 };    for(int i=0; i<myarray.size(); ++i)    {        if(i%2==0){            cout<<myarray[i];            cout<<" ";        }    }    return 0;}
Output: 
1 3 5
 
chhabradhanvi
cpp-array
cpp-operator
STL
C++
cpp-operator
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
Destructors in C++
new and delete operators in C++ for dynamic memory
Check whether given floating point number is even or odd in Python

Suppose we have a floating point number; we have to check whether the number is odd or even. In general, for integer it is easy by dividing the last digit by 2. But for floating point number it is not straight forward like that. We cannot divide last digit by 2 to check if it is odd or even.
So, if the input is like n = 200.290, then the output will be Odd though the last digit is divisible by 2.
To solve this, we will follow these steps −
s := convert number as string
flag := False
for i in range size of s - 1 to 0, decrease by 1, doif s[i] is '0' and flag is False, thengo for next iterationif s[i] is same as '.', thenflag := Truego for next iterationif s[i] is even, thenreturn "Even"return "Odd"
if s[i] is '0' and flag is False, thengo for next iteration
go for next iteration
if s[i] is same as '.', thenflag := Truego for next iteration
flag := True
go for next iteration
if s[i] is even, thenreturn "Even"
return "Even"
return "Odd"
Let us see the following implementation to get better understanding −
Live Demo
def solve(n) :
   s = str(n)

   flag = False
   for i in range(len(s) - 1, -1, -1) :
      if s[i] == '0' and flag == False :
         continue
  
      if s[i] == '.':
         flag = True
         continue
        
      if int(s[i]) % 2 == 0 :
         return "Even"
           
      return "Odd"    

n = 200.290
print(solve(n))
200.290

Odd
How to split a data frame in R with conditional row values?

The splitting of data frame is mainly done to compare different parts of that data frame but this splitting is based on some condition and this condition can be row values as well. For example, if we have a data frame df where a column represents categorical data then the splitting based on the categories can be done by using subset function as shown in the below examples.
Consider the below data frame:
Live Demo
> Country<-rep(c("India","China","Russia","Sudan"),5)
> Ratings<-sample(1:5,20,replace=TRUE)
> df1<-data.frame(Country,Ratings)
> df1
 Country Ratings
1 India   1
2 China   2
3 Russia  5
4 Sudan   3
5 India   5
6 China   5
7 Russia  5
8 Sudan   5
9 India   2
10 China  1
11 Russia 5
12 Sudan  4
13 India  3
14 China  1
15 Russia 1
16 Sudan  2
17 India  3
18 China  4
19 Russia 5
20 Sudan  2
Splitting df1 for groups (India-China, Russia, and Sudan):
> C1<-subset(df1,Country %in% c("India","China"))
> C1
  Country Ratings
1 India    1
2 China    2
5 India    5
6 China    5
9 India    2
10 China   1
13 India   3
14 China   1
17 India   3
18 China   4
> C2<-subset(df1,Country %in% c("Russia"))
> C2
  Country Ratings
3 Russia    5
7 Russia    5
11 Russia   5
15 Russia   1
19 Russia   5
> C3<-subset(df1,Country %in% c("Sudan"))
> C3
 Country Ratings
4 Sudan    3
8 Sudan    5
12 Sudan   4
16 Sudan   2
20 Sudan   2
Consider the below data frame:
Live Demo
> Season<-sample(c("Summer","Spring","Winter"),20,replace=TRUE)
> Rain<-sample(c("Yes","No"),20,replace=TRUE)
> df2<-data.frame(Season,Rain)
> df2
  Season Rain
1 Spring  Yes
2 Winter  Yes
3 Spring  Yes
4 Spring   No
5 Winter   No
6 Summer   No
7 Summer   No
8 Winter  Yes
9 Winter  Yes
10 Winter Yes
11 Summer Yes
12 Summer Yes
13 Summer Yes
14 Summer  No
15 Winter  No
16 Spring  No
17 Summer Yes
18 Spring Yes
19 Winter  No
20 Winter  No
Splitting df2 for Winter, Summer, and Spring separately:
> S1<-subset(df2,Season %in% c("Winter"))
> S1
  Season Rain
2 Winter  Yes
5 Winter   No
8 Winter  Yes
9 Winter  Yes
10 Winter Yes
15 Winter  No
19 Winter  No
20 Winter  No
> S2<-subset(df2,Season %in% c("Summer"))
> S2
  Season  Rain
6 Summer   No
7 Summer   No
11 Summer Yes
12 Summer Yes
13 Summer Yes
14 Summer  No
17 Summer Yes
> S3<-subset(df2,Season %in% c("Spring"))
> S3
  Season  Rain
1 Spring  Yes
3 Spring  Yes
4 Spring   No
16 Spring  No
18 Spring Yes
How to Create Subplots in Seaborn? - GeeksforGeeks

19 Dec, 2021

Prerequisites: Matplotlib, Seaborn
In this article, we will explore how to create a subplot or multi-dimensional plot in seaborn, It is a useful approach to draw subplot instances of the same plot on different subsets of your dataset. It allows a viewer to quickly extract a large amount of data about complex information. 
Example 1: Here, we are Initializing the grid without arguments returns a Figure and a single Axes.
Python3
 

 
 










import seaborn as sns 
import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
  
figure, axes = plt.subplots() 
figure.suptitle('Geeksforgeeks - one axes with no data')






Output:
Example 2: In this example we create a plot with 1 row and 2 columns, still no data passed i.e. nrows and ncols. If given in this order, we don’t need to type the arg names, just its values. 
figsize set the total dimension of our figure.
sharex and sharey are used to share one or both axes between the charts.
Python3
 

 
 










figure, axes = plt.subplots(1, 2, sharex=True, 
                            figsize=(10, 5)) 
figure.suptitle('Geeksforgeeks') 
axes[0].set_title('first chart with no data') 
axes[1].set_title('second chart with no data') 






Output:
Example 3: Creating subpolt with many levels 
Python3
 

 
 










figure, axes = plt.subplots(3, 4, sharex=True, 
                            figsize=(16, 8)) 
figure.suptitle('Geeksforgeeks - 3 x 4 axes with no data') 






Output:
Example 4: A gridspec() is for a grid of rows and columns with some specified width and height space. The plt.GridSpec object does not create a plot by itself but it is simply a convenient interface that is recognized by the subplot() command.
Python3
 

 
 










import matplotlib.pyplot as plt 
  
Grid_plot = plt.GridSpec(2, 3, wspace = 0.8, 
                        hspace = 0.6) 
  
plt.subplot(Grid_plot[0, 0]) 
plt.subplot(Grid_plot[0, 1:]) 
plt.subplot(Grid_plot[1, :2]) 
plt.subplot(Grid_plot[1, 2]) 






Output:
Example 4: Here we’ll create a 3×4 grid of subplot using subplots(), where all axes in the same row share their y-axis scale, and all axes in the same column share their x-axis scale
Python3
 

 
 










import matplotlib.pyplot as plt 
  
figure, axes = plt.subplots(3, 4, 
                            figsize=(15, 10)) 
  
figure.suptitle('Geeksforgeeks - 2 x 3 axes\ 
grid plot using subplots') 






Output:

Picked


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How can I draw a scatter trend line using Matplotlib?

To draw a scatter trend line using matplotlib, we can use polyfit() and poly1d() methods to get the trend line points.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
Plot x and y data points using numpy.
Plot x and y data points using numpy.
Find the trend line data points using polyfit() and poly1d() method.
Find the trend line data points using polyfit() and poly1d() method.
Plot x and p(x) data points using plot() method.
Plot x and p(x) data points using plot() method.
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.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.random.rand(100)
y = np.random.rand(100)
fig, ax = plt.subplots()
_ = ax.scatter(x, y, c=x, cmap='plasma')
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x, p(x), "r-o")

plt.show()
How to use #error and #warning directives in C#?

The #error directive allows generating an error from a specific location in your code.
Let us see an example −
 Live Demo
using System;

namespace Demo {
   class Program {
      public static void Main(string[] args) {
         #if (!ONE)
         #error ONE is undefined
         #endif
         Console.WriteLine("Generating a user-defined error!");
      }
   }
}
After running the above program, a user-defined error generates −
Compilation failed: 1 error(s), 0 warnings
error CS1029: #error: 'ONE is undefined'
The #warning directive allows generating a level one warning from a specific location in your code.
Let us see an example −
 Live Demo
using System;

namespace Demo {
   class Program {
      public static void Main(string[] args) {
         #if (!TWO)
         #warning TWO is undefined
         #endif
         Console.WriteLine("Generates a warning!");
      }
   }
}
After running the above program, warning generates and the output is visible −
warning CS1030: #warning: `TWO is undefined'
Generates a warning!
Structure Sorting in C++

Here we will see how to sort using some condition on some member variables of the structure in C++. In this example we will take a structure called book. The book will hold name, number of pages, and price. We will sort them based in the price.
For comparing two structures, we have to define a function. This function will compare them with these parameters. This comparison function is used inside the sort function to sort the values.
#include <iostream>
#include<algorithm>
using namespace std;
struct book {
   string title;
   int pages;
   float price;
};
bool compareBook(book b1, book b2) {
   if(b1.price < b2.price) {
      return true;
   } return false;
}
main() {
   book book_arr[5];
   book_arr[0].title = "C Programming";
   book_arr[0].pages = 260;
   book_arr[0].price = 450;
   book_arr[1].title = "DBMS Guide";
   book_arr[1].pages = 850;
   book_arr[1].price = 775;
   book_arr[2].title = "Learn C++";
   book_arr[2].pages = 350;
   book_arr[2].price = 520;
   book_arr[3].title = "Data Structures";
   book_arr[3].pages = 380;
   book_arr[3].price = 430;
   book_arr[4].title = "Learn Python";
   book_arr[4].pages = 500;
   book_arr[4].price = 300;
   sort(book_arr, book_arr + 5, compareBook);
   for(int i = 0; i<5; i++) {
      cout << book_arr[i].title << "\t\t" << book_arr[i].pages << "\t\t" <<
         book_arr[i].price << endl;
   }
}
Learn Python 500 300
Data Structures 380 430
C Programming 260 450
Learn C++ 350 520
DBMS Guide 850 775
Find specific records which has whitespace on the second place in MySQL

For this, use SUBSTR() as in the below syntax −
select * from yourTableName
where substr(yourColumnName, 2, 1 ) = ' ';
Let us first create a table −
mysql> create table DemoTable1365
    -> (
    -> Value varchar(20)
    -> );
Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1365 values('9756757474');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1365 values('3 45322333');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1365 values('8974646363');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1365 values('9 566363622');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1365;
This will produce the following output −
+-------------+
| Value       |
+-------------+
| 9756757474  |
| 3 45322333  |
| 8974646363  |
| 9 566363622 |
+-------------+
4 rows in set (0.00 sec)
Here is the query to find the specific records in the table which has white space only on the second place like “3 4532” −
mysql> select * from DemoTable1365
    -> where substr(Value, 2, 1 ) = ' ';
This will produce the following output −
+-------------+
| Value       |
+-------------+
| 3 45322333  |
| 9 566363622 |
+-------------+
2 rows in set (0.00 sec)
TestNG - Plug with Eclipse

To set up TestNG with Eclipse, follow the steps given below −
Download the latest version of TestNG jar file from http://www.testng.org
We assume you have copied the above JAR file in /work/testng folder.
Open eclipse → right click on the project and go to property → Build Path → Configure Build Path and add the testng-7.4.jar in the libraries using Add External Jar button.
Open eclipse → right click on the project and go to property → Build Path → Configure Build Path and add the testng-7.4.jar in the libraries using Add External Jar button.
We assume that your Eclipse has inbuilt TestNG plug-in; if it is not available, then please get the latest version using the update site.

In your Eclipse IDE, select Help / Eclipse Marketplace.
Search for Testng. You will get the TestNG in the list. Click on Install as shown below:



We assume that your Eclipse has inbuilt TestNG plug-in; if it is not available, then please get the latest version using the update site.
In your Eclipse IDE, select Help / Eclipse Marketplace.
In your Eclipse IDE, select Help / Eclipse Marketplace.
Search for Testng. You will get the TestNG in the list. Click on Install as shown below:

Search for Testng. You will get the TestNG in the list. Click on Install as shown below:
Now, your Eclipse is ready for the development of TestNG test cases.
Create a project TestNGProject in Eclipse at any location.
Create a project TestNGProject in Eclipse at any location.
Create a class MessageUtil to test in the project.
Create a class MessageUtil to test in the project.
/*
* This class prints the given message on console.
*/

public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message) {
      this.message = message;
   }

   // prints the message
   public String printMessage() {
      System.out.println(message);
      return message;
   }
}
Create a test class TestNGExample in the project.
Create a test class TestNGExample in the project.
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestNGExample {
   String message = "Hello World";
   MessageUtil messageUtil = new MessageUtil(message);

   @Test
   public void testPrintMessage() {
      Assert.assertEquals(message,messageUtil.printMessage());
   }
}
The project structure should be as follows −
Finally, verify the output of the program by right-clicking on the program and running as TestNG.
Verify the result.

    38 Lectures 
     4.5 hours 

 Lets Kode It

    15 Lectures 
     1.5 hours 

 Quaatso Learning

    28 Lectures 
     3 hours 

 Dezlearn Education
 Print
 Add Notes
 Bookmark this page
D3.js selection.attr() Function - GeeksforGeeks

19 Aug, 2020
The selection.attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.
Syntax:
selection.attr(name[, value]);

Parameters: This function takes two parameters as shown above and described below:
name: It is the name of the attribute.
value: It is the value of the attribute.
Return Values: This function does not return any value.
Example 1:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0">              <title>D3.js selection.attr() Function</title>      <script src=        "https://d3js.org/d3.v4.min.js">    </script>      <style>        p {            line-height: 5px;        }    </style></head>  <body>    <div>        <p>GeeksforGeeks</p>    </div>      <script>        var div = d3.select("p")            .attr("name", "This is from name attribute");        var divselect = document.querySelector("p");        console.log(divselect.getAttribute("name"));    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0">      <title>D3.js selection.attr() Function</title>      <script src=        "https://d3js.org/d3.v4.min.js">    </script>      <style>        p {            line-height: 5px;        }    </style></head>  <body>    <div>        <a>GeeksforGeeks</a>    </div>          <script>        var a = d3.select("a").attr("href",             "https://www.geeksforgeeks.org");          var divselect = document.querySelector("a");                  console.log("This is from a attr href: ",                 divselect.getAttribute("href"));    </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
List lastIndexOf() Method in Java with Examples - GeeksforGeeks

02 Jan, 2019
This method returns the last index of the occurrence of the specified element in this list, or -1 if this list does not contain the element.
Syntax:
int lastIndexOf(Object o)
Parameters: This function has a single parameter, i.e, the element to be searched in the list.
Returns: This method returns the last index of occurrence of the given element in the list and returns “-1” if element is not in the list.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// lastIndexOf method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(1);        l.add(3);        l.add(5);        l.add(7);        l.add(3);        System.out.println(l);        System.out.println(l.lastIndexOf(3));    }}
[1, 3, 5, 7, 3]
4

Program 2: Below is the code to show implementation of list.lastIndexOf() using Linkedlist.
// Java code to show the implementation of// lastIndexOf method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<String> l = new LinkedList<>();        l.add("10");        l.add("30");        l.add("50");        l.add("70");        l.add("30");        System.out.println(l);        System.out.println(l.lastIndexOf("30"));    }}
[10, 30, 50, 70, 30]
4

Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Collections in Java
Set in Java
Overriding in Java
Finding Mod of Given Number in Golang - GeeksforGeeks

13 Apr, 2020
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find a mod or floating-point remainder of specified a/b with the help of Mod() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Mod() function.
Syntax:
func Min(a, b float64) float64
In this function, the magnitude of the result is less than b and its sign agrees with that of a.
If you pass -Inf or +Inf in this function like Mod(-Inf, b) or Mod(+Inf, b), then this function will return NaN.
If you pass NaN in this function like Mod(NaN, b), then this function will return NaN.
If you pass b=0 in this function like Mod(a, 0), then this function will return NaN.
If you pass -Inf or +Inf in this function like Mod(a, -Inf) or Mod(b, +Inf), then this function will return a.
If you pass NaN in this function like Mod(a, NaN), then this function will return NaN.
Example 1:
// Golang program to illustrate how to// find mod of the specified numbers  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Finding mod of the given numbers    // Using Mod() function    res_1 := math.Mod(60, 5)    res_2 := math.Mod(-100, 100)    res_3 := math.Mod(45.6, 8.9)    res_4 := math.Mod(math.NaN(), 67)    res_5 := math.Mod(math.Inf(1), 67)      // Displaying the result    fmt.Printf("Result 1: %.1f", res_1)    fmt.Printf("\nResult 2: %.1f", res_2)    fmt.Printf("\nResult 3: %.1f", res_3)    fmt.Printf("\nResult 4: %.1f", res_4)    fmt.Printf("\nResult 5: %.1f", res_5)  }
Output:
Result 1: 0.0
Result 2: -0.0
Result 3: 1.1
Result 4: NaN
Result 5: NaN

Example 2:
// Golang program to illustrate how to// find mod of the specified numbers  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Finding mod of     // the given numbers    // Using Mod() function    nvalue_1 := math.Mod(34, 6)    nvalue_2 := math.Mod(56.7, 3.4)      // Finding sum of the given mod    res := nvalue_1 + nvalue_2    fmt.Printf("%.2f + %.2f = %.2f",             nvalue_1, nvalue_2, res)  }
Output:
4.00 + 2.30 = 6.30
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
How to print duplicate characters in a String using C#?

Set maximum value for char.
static int maxCHARS = 256;
Now display the duplicate characters in the string.
String s = "Welcometomywebsite!";

int []cal = new int[maxCHARS];
calculate(s, cal);

for (int i = 0; i < maxCHARS; i++)
if(cal[i] > 1) {
   Console.WriteLine("Character "+(char)i);
   Console.WriteLine("Occurrence = " + cal[i] + " times");
}
Above, we have calculated the frequency of characters. The same is shown below in the complete example −
using System;
class Demo {
   static int maxCHARS = 256;
   static void calculate(String s, int[] cal) {

      for (int i = 0; i < s.Length; i++)
      cal[s[i]]++;
   }

   public static void Main() {
      String s = "Welcometomywebsite!";

      int []cal = new int[maxCHARS];
      calculate(s, cal);

      for (int i = 0; i < maxCHARS; i++)
      if(cal[i] > 1) {
         Console.WriteLine("Character "+(char)i);
         Console.WriteLine("Occurrence = " + cal[i] + " times");
      }
   }
}
How did I write an own OCR program using Keras and TensorFlow in Python | by Anh T. Dang | Towards Data Science

Optical Character Recognition (or optical character reader, aka OCR) is a technology that used for the last two decades to identify and digitize alphabetical and numerical characters presented in images. In the industry, this technology can help us to avoid entering data manually by a human.
In this post, I’d like to take you through the steps required to understand how deep learning technique is applied to OCR technology to classify handwriting.
Prepare the 0–9 and A-Z letters dataset for training the OCR model.
Load those datasets for letters from the disk.
Successfully train a Keras and TensorFlow model on the dataset.
Plot the results of the training and visualize the output of the validation data.
Predict the text present in some images.
We use the following two datasets to train our Keras and TensorFlow model.
0–9: MNIST
A-Z: Kaggle
This dataset1 was constructed from NIST’s Special Database 3 and Special Database 1 which contain binary images of handwritten digits.
It is built into popular deep learning frameworks, including Keras, TensorFlow, PyTorch, etc. The MNIST dataset will allow us to recognize the digits 0–9.Each of these digits is contained in a 28 x 28 grayscale image.
Kaggle user Sachin Patel has released a simple comma-separated values (CSV) file2.
This dataset takes the capital letters A–Z from NIST Special Database 19.Kaggle also rescales them from 28 x 28 grayscale pixels to the same format as our MNIST data.
Since we have two separate datasets, first we must load both two datasets and combine them into a single dataset.
Load the Kaggle A-Z letters.
Load the MNIST 0–9 digits.
Combine them into one.
I trained my model using Keras, TensorFlow, and ResNet architecture.
This model takes ~30–45 minutes to train using the below command.
python train_model.py --az dataset/a_z_handwritten_data.csv --model trained_ocr.model[INFO] loading datasets...[INFO] compiling model...[INFO] training network...Epoch 1/50 34/437 [=>............................] — ETA: 7:40 — loss: 2.5050 — accuracy: 0.2989...
We will plot a visualization so that we can ensure it is working properly.
Once the model is trained. We can make predictions with it.
python prediction.py — model trained_ocr.model — image images/hello_world.png[INFO] H - 92.48%[INFO] W - 54.50%[INFO] E - 94.93%[INFO] L - 97.58%[INFO] 2 - 65.73%[INFO] L - 96.56%[INFO] R - 97.31%[INFO] 0 - 37.92%[INFO] L - 97.13%[INFO] D - 97.83%
The full source code can be seen here: https://github.com/housecricket/how-to-train-OCR-with-Keras-and-TensorFlow
├── __init__.py├── dataset│   └── a_z_handwritten_data.csv├── images│   ├── hello_world.png│   └── vietnamxinchao.png├── models│   ├── __init__.py│   └── resnet.py├── prediction.py├── requirements.txt├── train_model.py├── trained_ocr.model└── utils.py
Finallly, concluding this article, we can say that it is easy to train an OCR model using Keras, TensorFlow and Python. In addition, we can improve the accuracy of this OCR model by using better datasets.
Any your thoughts...? Easy, right?
Sort Colors in Python

Suppose we have an array with n objects. These are colored red, white, or blue, sort them in place so that the objects of the same color are adjacent. So with the colors in the order red, white and blue. Here, we will use the numbers like 0, 1, and 2 to represent the color red, white, and blue respectively. So if the array is like [2,0,2,1,1,0], then the output will be [0,0,1,1,2,2]
To solve this, we will follow these steps −
set low := 0, mid := 0 and high := length of array – 1
while mid <= highif arr[mid] = 0, then swap arr[mid] and arr[low], and increase low and mid by 1otherwise when arr[mid] = 2, swap arr[high] and arr[mid], decrease high by 1else increase mid by 1
if arr[mid] = 0, then swap arr[mid] and arr[low], and increase low and mid by 1
otherwise when arr[mid] = 2, swap arr[high] and arr[mid], decrease high by 1
else increase mid by 1
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def sortColors(self, nums):
      low = 0
      mid = 0
      high = len(nums)-1
      while mid<=high:
         if nums[mid] == 0:
            nums[low],nums[mid] = nums[mid],nums[low]
            low+=1
            mid += 1
         elif nums[mid] == 2:
            nums[high], nums[mid] = nums[mid], nums[high]
            high-=1
         else:
            mid += 1
      return nums
ob1 = Solution()
print(ob1.sortColors([2,0,2,1,1,0]))
[2,0,2,1,1,0]
[0,0,1,1,2,2]
Check if a number is Primorial Prime or not in Python

Suppose we have a number n, we have to check whether n is a primorial prime or not. A number is said to be a primorial prime when it is a prime number of the form pN# + 1 or pN# – 1 , where pN# indicates the primorial of pN such that the product of first N prime numbers.
So, if the input is like 29, then the output will be True as 29 is Primorial prime of the form pN - 1 if N=3, Primorial is 2*3*5 = 30 and 30-1 = 29.
To solve this, we will follow these steps −
MAX := 100000
prime := A list of size MAX and fill with True
arr := a new list
Define a function SieveOfEratosthenes() . This will take
for pri in range 2 to int(square root of (MAX)) + 1, doif prime[pri] is same as True, thenfor i in range pri * 2 to MAX, update in each step by pri, doprime[i] := False
if prime[pri] is same as True, thenfor i in range pri * 2 to MAX, update in each step by pri, doprime[i] := False
for i in range pri * 2 to MAX, update in each step by pri, doprime[i] := False
prime[i] := False
for pri in range 2 to MAX, doif prime[pri] is non-zero, theninsert pri at the end of arr
if prime[pri] is non-zero, theninsert pri at the end of arr
insert pri at the end of arr
From the main method, do the following −
if prime[n] is zero, thenreturn False
return False
product := 1, i := 0
while product < n, doproduct := product * arr[i]if product + 1 is same as n or product - 1 is same as n, thenreturn Truei := i + 1
product := product * arr[i]
if product + 1 is same as n or product - 1 is same as n, thenreturn True
return True
i := i + 1
return False
Let us see the following implementation to get better understanding −
 Live Demo
from math import sqrt
MAX = 100000
prime = [True] * MAX
arr = []
def SieveOfEratosthenes() :
   for pri in range(2, int(sqrt(MAX)) + 1) :
      if prime[pri] == True :
         for i in range(pri * 2 , MAX, pri) :
            prime[i] = False
   for pri in range(2, MAX) :
      if prime[pri] :
         arr.append(pri)
def check_primorial_prime(n) :
   if not prime[n] :
      return False
   product, i = 1, 0
   while product < n :
      product *= arr[i]
      if product + 1 == n or product - 1 == n :
         return True
      i += 1
   return False
SieveOfEratosthenes()
n = 29
print(check_primorial_prime(n))
29
True
How to create an VBox using JavaFX?

Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package.
In the vbox layout, the nodes are arranged in a single vertical column. You can create an hbox in your application by instantiating the javafx.scene.layout.VBox class. You can set the padding around the hbox using the setPadding() method.
To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as −
getChildren().addAll();
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class VBoxExample extends Application {
   public void start(Stage stage) {
      //Creating the check boxes
      CheckBox checkBox1 = new CheckBox("Hindi");
      CheckBox checkBox2 = new CheckBox("Gujarathi");
      CheckBox checkBox3 = new CheckBox("Punjabi");
      CheckBox checkBox4 = new CheckBox("Telugu");
      CheckBox checkBox5 = new CheckBox("Tamil");
      CheckBox checkBox6= new CheckBox("Malayalam");
      //Creating a label
      Label label = new Label("Select known languages:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a separator
      Separator sep = new Separator();
      sep.setMaxWidth(80);
      sep.setHalignment(HPos.CENTER);
      //Adding the check boxes and separator to the pane
      VBox vBox = new VBox(5);
      vBox.setPadding(new Insets(5, 5, 5, 50));
      vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6);
      //Adding the separator after the 3rd check box
      vBox.getChildren().add(4, sep);
      //Setting the stage
      Scene scene = new Scene(vBox, 595, 200, Color.BEIGE);
      stage.setTitle("VBox Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
What is the best way to show data in a table in Tkinter?

Generally, we represent data in the form of tables. A table contains a set of rows and columns. Data gets stored sequentially in the form of rows and columns in a table.
Let us suppose that we are building a Tkinter application such that we have to store the Student’s data somewhere in a table. The table structure contains 3 columns to store the First Name, Last Name, and Roll Number of students. To display this type of information, Tkinter provides a Notebook widget where we can store our data in the form of a Table.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create an object of Style widget
style = ttk.Style()
style.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("FName", "LName", "Roll No"), show='headings', height=5)
tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="FName")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="LName")
tree.column("# 3", anchor=CENTER)
tree.heading("# 3", text="Roll No")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('Amit', 'Kumar', '17701'))
tree.insert('', 'end', text="1", values=('Ankush', 'Mathur', '17702'))
tree.insert('', 'end', text="1", values=('Manisha', 'Joshi', '17703'))
tree.insert('', 'end', text="1", values=('Shivam', 'Mehrotra', '17704'))

tree.pack()

win.mainloop()
If we run the above code, it will display a window that contains a table with some student data in it.