title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
How to Install SQL Workbench For MySQL on Linux? | 06 Dec, 2021
MySQL Workbench is a visual database design tool that integrates SQL development, administration, database design, creation, and maintenance into a single integrated development environment for the MySQL database system. It was first released in 2014. It is owned by Oracle Corporation. It supports Windows, Linux, and Mac OS operating systems. In this article, We will know how can we install SQL Workbench on our Linux systems.
Follow the below steps to install SQL
Step 1: Open your browser and download SQL Workbench for your Linux system from here. You will see a screen as shown below then click on the Download button.
Step 2: After clicking on download you will get a confirmation screen, click on No thanks, just start my download on the left side of your screen.
Step 3: Open your terminal and navigate to that folder in which you have downloaded that workbench file using cd FolderName.
Step 4: Run installation command
After navigating to that folder, run the following command in your terminal to install MySQL Workbench.
sudo apt-get install ./fileNameOfInstallationPackage
After running the above command you will get a prompt screen. Choose Debian buster using your keyboard arrow buttons and press enter.
After that choose ok and press enter.
Step 5: On your terminal update your packages using the following command.
sudo apt-get update
Step 6: Install SQL workbench community. Now, we have to install MySQL Workbench Community. For this, I have used snap. You can also install this using the following command. You can learn more about snap from here.
snap install mysql-workbench-community
That’s it, Now SQL Workbench is now installed on your Linux system. To verify You can search MySQL Workbench on your app drawer.
Output:
To run click on the icon of MySQL Workbench.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 459,
"s": 28,
"text": "MySQL Workbench is a visual database design tool that integrates SQL development, administration, database design, creation, and maintenance into a single integrated developme... |
C++ Keywords | 03 Jun, 2022
C++ is a powerful language. In C++ we can write structured programs and object-oriented programs also. C++ is a superset of C and therefore most constructs of C are legal in C++ with their meaning unchanged. However, there are some exceptions and additions.
Token: When the compiler is processing the source code of a C++ program, each group of characters separated by white space is called a token. Tokens are the smallest individual units in a program. A C++ program is written using tokens. It has the following tokens:
Keywords
Identifiers
Constants
Strings
Operators
Keywords (also known as reserved words) have special meaning to the C++ compiler and are always written or typed in short(lower) cases. Keywords are words that the language uses for a special purpose, such as void, int, public, etc. It can’t be used for a variable name or function name. Below is the table for the complete set of C++ keywords.
C++ Keyword
Note: The keywords not found in ANSI C are shown here in boldface.
asm: To declare that a block of code is to be passed to the assembler.
auto: A storage class specifier that is used to define objects in a block.
break: Terminates a switch statement or a loop.
case: Used specifically within a switch statement to specify a match for the statement’s expression.
catch: Specifies actions taken when an exception occurs.
char: Fundamental data type that defines character objects.
class: To declare a user-defined type that encapsulates data members and operations or member functions.
const: To define objects whose value will not alter throughout the lifetime of program execution.
continue:- Transfers control to the start of a loop.
default:- Handles expression values in a switch statement that are not handled by case.
delete: Memory deallocation operator.
do: indicate the start of a do-while statement in which the sub-statement is executed repeatedly until the value of the expression is logical-false.
double: Fundamental data type used to define a floating-point number.
else: Used specifically in an if-else statement.
enum: To declare a user-defined enumeration data type.
extern: An identifier specified as extern has external linkage to the block.
float:- Fundamental data type used to define a floating-point number.
for: Indicates the start of a statement to achieve repetitive control.
friend: A class or operation whose implementation can access the private data members of a class.
goto: Transfer control to a specified label.
if: Indicate the start of an if statement to achieve selective control.
inline: A function specifier that indicates to the compiler that inline substitution of the function body is to be preferred to the usual function call implementation.
int: Fundamental data type used to define integer objects.
long: A data type modifier that defines a 32-bit int or an extended double.
new: Memory allocation operator.
operator: Overloads a c++ operator with a new declaration.
private: Declares class members which are not visible outside the class.
protected: Declares class members which are private except to derived classes
public: Declares class members who are visible outside the class.
register: A storage class specifier that is an auto specifier, but which also indicates to the compiler that an object will be frequently used and should therefore be kept in a register.
return: Returns an object to a function’s caller.
short: A data type modifier that defines a 16-bit int number.
signed: A data type modifier that indicates an object’s sign is to be stored in the high-order bit.
sizeof: Returns the size of an object in bytes.
static: The lifetime of an object-defined static exists throughout the lifetime of program execution.
struct: To declare new types that encapsulate both data and member functions.
switch: This keyword used in the “Switch statement”.
template: parameterized or generic type.
this: A class pointer points to an object or instance of the class.
throw: Generate an exception.
try: Indicates the start of a block of exception handlers.
typedef: Synonym for another integral or user-defined type.
union: Similar to a structure, struct, in that it can hold different types of data, but a union can hold only one of its members at a given time.
unsigned: A data type modifier that indicates the high-order bit is to be used for an object.
virtual: A function specifier that declares a member function of a class that will be redefined by a derived class.
void: Absent of a type or function parameter list.
volatile: Define an object which may vary in value in a way that is undetectable to the compiler.
while: Start of a while statement and end of a do-while statement.
Identifiers refer to the name of variables, functions, arrays, classes, etc. created by the programmer. They are the fundamental requirement of any language.
Rules for naming identifiers:
Identifier name can not start with a digit or any special character.
A keyword cannot be used as s identifier name.
Only alphabetic characters, digits, and underscores are permitted.
The upper case and lower case letters are distinct. i.e., A and a are different in C++.
The valid identifiers are GFG, gfg, geeks_for_geeks.
Program 1:
C++
// C++ program to illustrate the use// of identifiers #include <iostream>using namespace std; // Driver Codeint main(){ // Use of Underscore (_) symbol // in variable declaration int geeks_for_geeks = 1; cout << "Identifier result is: " << geeks_for_geeks; return 0;}
Identifier result is: 1
Now, the question arises how keywords are different from identifiers?
So there are some main properties of keywords that distinguish keywords from identifiers:
Keywords are predefined/reserved words and identifiers are the values used to define different programming items like a variable, integers, structures, unions.
Keywords always start with lowercase whereas identifier can start with the uppercase letter as well as a lowercase letter.
A keyword contains only alphabetical characters, but an identifier can consist of alphabetical characters, digits, and underscores.
No special symbol, punctuations used in keywords and identifiers. The only underscore can be used in an identifier.
Example of keywords and identifiers:Keywords: int, char, while, do.Identifiers: Geeks_for_Geeks, GFG, Gfg1.
Keywords: int, char, while, do.
Identifiers: Geeks_for_Geeks, GFG, Gfg1.
Program 2:
Below is the program for how to use different keywords in the program:
C++
// C++ Program to demonstrate keywords#include <iostream>using namespace std; // Driver Codeint main(){ // Variable declaration and // initialization int n = 2; // Switch Case Statement switch (n) { case 1: cout << "Computer Network" << endl; break; case 2: cout << "C++" << endl; break; case 3: cout << "DBMS" << endl; break; case 4: cout << "Data Structure" << endl; break; case 5: cout << "Operating System" << endl; break; default: cout << "Enter Valid number" << endl; } // Return keyword returns an object // to a function's caller return 0;}
C++
gabaa406
varshagumber28
jayanth_mkv
CPP-Basics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 311,
"s": 53,
"text": "C++ is a powerful language. In C++ we can write structured programs and object-oriented programs also. C++ is a superset of C and therefore most constructs of C are legal in ... |
Variance and standard-deviation of a matrix | 06 Apr, 2021
Prerequisite – Mean, Variance and Standard Deviation, Variance and Standard Deviation of an arrayGiven a matrix of size n*n. We have to calculate variance and standard-deviation of given matrix. Examples :
Input : 1 2 3
4 5 6
6 6 6
Output : variance: 3
deviation: 1
Input : 1 2 3
4 5 6
7 8 9
Output : variance: 6
deviation: 2
Explanation: First mean should be calculated by adding sum of each elements of the matrix. After calculating mean, it should be subtracted from each element of the matrix.Then square each term and find out the variance by dividing sum with total elements. Deviation: It is the square root of the variance.Example:
1 2 3
4 5 6
7 8 9
Here mean is 5 and variance is approx 6.66
Below is code implementation:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find mean and// variance of a matrix.#include <bits/stdc++.h>using namespace std; // variance function declarationint variance(int, int, int); // Function for calculating meanint mean(int a[][3], int n){ // Calculating sum int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += a[i][j]; // Returning mean return sum / (n * n);} // Function for calculating varianceint variance(int a[][3], int n, int m){ int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // subtracting mean from elements a[i][j] -= m; // a[i][j] = fabs(a[i][j]); // squaring each terms a[i][j] *= a[i][j]; } } // taking sum for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += a[i][j]; return sum / (n * n);} // driver programint main(){ // declaring and initializing matrix int mat[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // for mean int m = mean(mat, 3); // for variance int var = variance(mat, 3, m); // for standard deviation int dev = sqrt(var); // displaying variance and deviation cout << "Mean: " << m << "\n" << "Variance: " << var << "\n" << "Deviation: " << dev << "\n"; return 0;}
// Java program to find mean// and variance of a matrix.import java.io.*; class GFG{// Function for// calculating meanstatic int mean(int a[][], int n){ // Calculating sum int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += a[i][j]; // Returning mean return sum / (n * n);} // Function for// calculating variancestatic int variance(int a[][], int n, int m){ int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // subtracting mean // from elements a[i][j] -= m; // a[i][j] = fabs(a[i][j]); // squaring each terms a[i][j] *= a[i][j]; } } // taking sum for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += a[i][j]; return sum / (n * n);} // Driver Codepublic static void main (String[] args){ // declaring and// initializing matrixint mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // for meanint m = mean(mat, 3); // for varianceint var = variance(mat, 3, m); // for standard// deviationdouble dev = (int)Math.sqrt(var); // displaying variance// and deviationSystem.out.println("Mean: " + m);System.out.println("Variance: " + var);System.out.println("Deviation: " + (int)dev);}} // This code is contributed// by akt_mit
# Python3 program to find mean# and variance of a matrix.import math; # variance function declaration# Function for calculating meandef mean(a, n): # Calculating sum sum = 0; for i in range(n): for j in range(n): sum += a[i][j]; # Returning mean return math.floor(int(sum / (n * n))); # Function for calculating variancedef variance(a, n, m): sum = 0; for i in range(n): for j in range(n): # subtracting mean # from elements a[i][j] -= m; # a[i][j] = fabs(a[i][j]); # squaring each terms a[i][j] *= a[i][j]; # taking sum for i in range(n): for j in range(n): sum += a[i][j]; return math.floor(int(sum / (n * n))); # Driver Code # declaring and# initializing matrixmat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; # for meanm = mean(mat, 3); # for variancevar = variance(mat, 3, m); # for standard deviationdev = math.sqrt(var); # displaying variance# and deviationprint("Mean:", m);print("Variance:", var);print("Deviation:", math.floor(dev)); # This code is contributed by mits
// C# program to find mean// and variance of a matrix.using System; class GFG{ // Function for// calculating meanstatic int mean(int [,]a, int n){ // Calculating sum int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += a[i, j]; // Returning mean return sum / (n * n);} // Function for// calculating variancestatic int variance(int [,]a, int n, int m){ int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // subtracting mean // from elements a[i, j] -= m; // a[i][j] = fabs(a[i][j]); // squaring each terms a[i, j] *= a[i, j]; } } // taking sum for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += a[i,j]; return sum / (n * n);} // Driver Codestatic public void Main (){ // declaring and// initializing matrixint [,]mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // for meanint m = mean(mat, 3); // for varianceint var = variance(mat, 3, m); // for standard deviationdouble dev = (int)Math.Sqrt(var); // displaying variance and deviationConsole.WriteLine("Mean: " + m ); Console.WriteLine("Variance: " + var); Console.WriteLine("Deviation: " + dev);}} // This code is contributed by ajit
<?php// PHP program to find mean// and variance of a matrix. // variance function declaration// Function for calculating meanfunction mean($a, $n){ // Calculating sum $sum = 0; for ($i = 0; $i < $n; $i++) for ( $j = 0; $j < $n; $j++) $sum += $a[$i][$j]; // Returning mean return floor((int)$sum / ($n * $n));} // Function for calculating variancefunction variance($a, $n, $m){ $sum = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // subtracting mean // from elements $a[$i][$j] -= $m; // a[i][j] = fabs(a[i][j]); // squaring each terms $a[$i][$j] *= $a[$i][$j]; } } // taking sum for ($i = 0; $i < $n; $i++) for ( $j = 0; $j < $n; $j++) $sum += $a[$i][$j]; return floor((int)$sum / ($n * $n));} // Driver Code // declaring and// initializing matrix$mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); // for mean$m = mean($mat, 3); // for variance$var = variance($mat, 3, $m); // for standard deviation$dev = sqrt($var); // displaying variance// and deviationecho "Mean: " , $m , "\n", "Variance: " , $var , "\n", "Deviation: " , floor($dev) , "\n"; // This code is contributed by ajit?>
<script> // JavaScript program to find mean// and variance of a matrix // Function for// calculating meanfunction mean(a, n){ // Calculating sum let sum = 0; for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) sum += a[i][j]; // Returning mean return sum / (n * n);} // Function for// calculating variancefunction variance(a, n, m){ let sum = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // subtracting mean // from elements a[i][j] -= m; // a[i][j] = fabs(a[i][j]); // squaring each terms a[i][j] *= a[i][j]; } } // taking sum for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) sum += a[i][j]; return sum / (n * n);} // Driver code // declaring and// initializing matrixlet mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; // for meanlet m = mean(mat, 3); // for variancelet varr = variance(mat, 3, m); // for standard// deviationlet dev = Math.sqrt(varr); // displaying variance// and deviationdocument.write("Mean: " + Math.floor(m) + "<br/>");document.write("Variance: " + Math.floor(varr) + "<br/>");document.write("Deviation: " + Math.floor(dev) + "<br/>"); // This code is contributed by code_hunt. </script>
Mean: 5
Variance: 6
Deviation: 2
This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
jit_t
Mithun Kumar
code_hunt
statistical-algorithms
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 260,
"s": 52,
"text": "Prerequisite – Mean, Variance and Standard Deviation, Variance and Standard Deviation of an arrayGiven a matrix of size n*n. We have to calculate variance and standard-deviat... |
Java Examples - Validate email address format | How to validate an email address format?
Following example demonstrates how to validate e-mail address using matches() method of String class.
public class Main {
public static void main(String[] args) {
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
String email1 = "user@domain.com";
Boolean b = email1.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email1+" :Valid = " + b);
String email2 = "user^domain.co.in";
b = email2.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email2+" :Valid = " + b);
}
}
The above code sample will produce the following result.
is e-mail: user@domain.com :Valid = true
is e-mail: user^domain.co.in :Valid = false
The following is an example to validate an email address format.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
List emails = new ArrayList();
emails.add("sairamkrishna@tutorialspoint.com");
emails.add("kittuprasad700@gmail.com");
emails.add("sairamkrishna_mammahe%google-india.com");
emails.add("sairam.krishna@gmail-indai.com");
emails.add("sai#@youtube.co.in");
emails.add("kittu@domaincom");
emails.add("kittu#gmail.com");
emails.add("@pindom.com");
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
for (Object email : emails) {
Matcher matcher = pattern.matcher((CharSequence) email);
System.out.println(email + " : " + matcher.matches());
}
}
}
The above code sample will produce the following result.
sairamkrishna@tutorialspoint.com : true
kittuprasad700@gmail.com : true
sairamkrishna_mammahe%google-india.com : false
sairam.krishna@gmail-indai.com : true
sai#@youtube.co.in : true
kittu@domaincom : true
kittu#gmail.com : false
@pindom.com : false | [
{
"code": null,
"e": 2243,
"s": 2202,
"text": "How to validate an email address format?"
},
{
"code": null,
"e": 2345,
"s": 2243,
"text": "Following example demonstrates how to validate e-mail address using matches() method of String class."
},
{
"code": null,
"e": 27... |
How to Compile, Decompile and Run C# Code in Linux? | 23 Sep, 2021
C# is a modern multi-paradigm programming language developed by Microsoft and released in the year 2000. By multi-paradigm we mean that it includes static typing, strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented, and component-oriented programming disciplines. The syntax of C# is highly inspired from the JAVA syntax, therefore, it is easier to understand for most the developer what have some basic knowledge of C, C++, and JAVA. It was designed by Anders Hejlsberg and developed by Mads Torgersen.
Firstly, we need to install mono-complete, to run software for Mono or Microsoft. NET.
Step 1: To Install mono-complete, open up your Linux terminal and type the following command, and hit enter.
Run the following command to set up the system before installing the mono.
sudo apt install gnupg ca-certificates
sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo “deb https://download.mono-project.com/repo/ubuntu stable-focal main” | sudo tee /etc/apt/sources.list.d/mono-official-stable.list
sudo apt update
Then run the following to install mono.
sudo apt install mono-complete
Step 2: Write a simple hello world program in C# and save the code in a file called geeks.cs.
C#
using System; public class GFG { static public void Main() { Console.WriteLine("Hello World!"); Console.ReadKey(); }}
Hello World!
Step 3: Now make this C# file an executable file. Navigate to the file and run the following command.
making executable
chmod +x geeks.cs
Here, +x means executable.
Step 4: Now we will be using the mcs compiler and create a Windows executable named geeks.exe from the source geeeks.cs.
mcs -out:geeks.exe geeks.cs
Output:
compiling c# code
After this, an executable file, geeks.cs, will be generated.
Step 5: Now to run this geeks.exe executable file, run the following command.
mono geeks.exe
Output:
Running c# code
Step 5: Press Enter to exit back to a default terminal prompt.
Step 6: To decompile this executable file run the following command:
monodis –output=geeks.txt geeks.exe
Output:
Decompiled c# code
The decompiled code will be saved in the newly generated file, geeks.txt. To view the decompiled file in the terminal, run the following command:
cat geeks.txt
Output should look like this:
Output of decompiled code
Blogathon-2021
Picked
Blogathon
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 576,
"s": 28,
"text": "C# is a modern multi-paradigm programming language developed by Microsoft and released in the year 2000. By multi-paradigm we mean that it includes static typing, strong typin... |
How to align two navbars in bootstrap ? | 13 Jun, 2022
Navbar is a section of a web application that allows users to navigate to different sections of the website. As the name suggests, a navbar is basically a navigation bar. Bootstrap 4 comes up with an inbuilt navbar class that allows us to create navbars. Also, we can create custom navbars by defining the various CSS styles as per our requirements. In this article, we will demonstrate both the methods of aligning two navbars using CSS inbuilt classes as well as custom CSS styles.
Example 1: In the first approach, we have made use of the inbuilt navbar class of Bootstrap 4. Two navbars are placed one after the other. The first navbar has a dark background and the navigation links are left-aligned whereas the “Register” and “Logout” buttons are right-aligned. The first navbar also consists of a dropdown menu that has links to several sections of the website. The second navbar has the navigation links aligned to the right and plaintext with a hyperlink aligned to the left. Both the navbars are responsive to the screen size. The navbar toggle button appears when the screen size reduces and disappears when the screen size increases. The toggle button when clicked displays the navbar.
Code implementation:
HTML
<!DOCTYPE html><html> <head> <!--import bootstrap cdn--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <!--import jquery cdn--> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"> </script></head> <body> <!--First navbar--> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#"> Action </a> <a class="dropdown-item" href="#"> Another action </a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#"> Something else here </a> </div> </li> </ul> <button class="btn btn-success my-2 my-sm-0 mx-2" type="submit"> Register </button> <button class="btn btn-danger my-2 my-sm-0" type="submit"> Logout </button> </div> </nav> <!--Second navbar--> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> We have changed our Privacy Policy. To know more <a href="#" class="mx-1">click here</a>. <ul class="navbar-nav ml-auto"> <li class="nav-item nav-link" href="#">About Us </li> <li class="nav-item nav-link" href="#">Contact Us </li> <li class="nav-item nav-link" href="#">Explore </li> </ul> </div> </nav></body> </html>
Output:
Example 2: In this approach, navbars are created using custom CSS styles. The topnav class division represents the first navbar and the bottomnav class division represents the second navbar. The first navbar has the navigation links aligned to the left and the login link to the right. The second navbar has the navigation links to the left and the “register” and “logout” buttons to the right. Unlike the previous example, the navbars in this example are not responsive. The navbars do not adapt to the screen size.
Code Implementation:
HTML
<!DOCTYPE html><html> <head> <!--import bootstrap cdn--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <style type="text/css"> .topnav { margin-top: 10px; margin-right: 10px; margin-left: 10px; background-color: #DCEEFF; overflow: hidden; height: 40px; padding: 8px; } .bottomnav { margin-right: 10px; margin-left: 10px; background-color: #E5E5E5; overflow: hidden; height: 40px; padding: 5px; } a { color: black; padding-right: 20px; font-weight: bold; } </style></head> <body> <div class="topnav"> <a class="active" href="#">Home</a> <a href="#">Feature</a> <a href="#">Deals</a> <a href="#">Blog</a> <a href="#" class="float-right">Login</a> </div> <div class="bottomnav"> <a class="active" href="#">More</a> <a href="#">Contact</a> <a href="#">About Us</a> <a href="#">Link</a> <a class="btn btn-danger btn-sm float-right mx-2 mb-3">Logout</a> <a class="btn btn-success btn-sm float-right">Register</a> </div></body> </html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
sanjyotpanure
Bootstrap-4
Bootstrap-Misc
CSS-Misc
HTML-Misc
Technical Scripter 2020
Bootstrap
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 512,
"s": 28,
"text": "Navbar is a section of a web application that allows users to navigate to different sections of the website. As the name suggests, a navbar is basically a navigation bar. Boot... |
Comparing Means in R Programming | 16 May, 2022
There are many cases in data analysis where you’ll want to compare means for two populations or samples and which technique you should use depends on what type of data you have and how that data is grouped together. The comparison of means tests helps to determine if your groups have similar means. So this article contains statistical tests to use for comparing means in R programming. These tests include:
T-test
Wilcoxon test
ANOVA test
Kruskal-Wallis test
So as we have discussed before various techniques are used depending on what type of data we have and how the data is grouped together. So let’ discuss one by one techniques depending on the different types of data.
There are mainly two techniques used to compare the one-sample mean to a standard known mean. These two techniques are:
One Sample T-test
One-Sample Wilcoxon Test
The One-Sample T-Test is used to test the statistical difference between a sample mean and a known or assumed/hypothesized value of the mean in the population.
Implementation in R:
For performing a one-sample t-test in R, use the function t.test(). The syntax for the function is given below:
Syntax: t.test(x, mu = 0)
Parameters:
x: the name of the variable of interest
mu: set equal to the mean specified by the null hypothesis
Example:
R
# R program to illustrate# One sample t-test set.seed(0)sweetSold <- c(rnorm(50, mean = 140, sd = 5)) # Ho: mu = 150# Using the t.test()result = t.test(sweetSold, mu = 150) # Print the resultprint(result)
Output:
One Sample t-test
data: sweetSold
t = -15.249, df = 49, p-value < 2.2e-16
alternative hypothesis: true mean is not equal to 150
95 percent confidence interval:
138.8176 141.4217
sample estimates:
mean of x
140.1197
The one-sample Wilcoxon signed-rank test is a non-parametric alternative to a one-sample t-test when the data cannot be assumed to be normally distributed. It’s used to determine whether the median of the sample is equal to a known standard value i.e. a theoretical value.
Implementation in R:
To perform a one-sample Wilcoxon-test, R provides a function wilcox.test() that can be used as follows:
Syntax: wilcox.test(x, mu = 0, alternative = “two.sided”)
Parameters:
x: a numeric vector containing your data values
mu: the theoretical mean/median value. Default is 0 but you can change it.
alternative: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.
Example: Here, let’s use an example data set containing the weight of 10 rabbits. Let’s know if the median weight of the rabbit differs from 25g?
R
# R program to illustrate# one-sample Wilcoxon signed-rank test # The data setset.seed(1234)myData = data.frame(name = paste0(rep("R_", 10), 1:10),weight = round(rnorm(10, 30, 2), 1)) # Print the dataprint(myData) # One-sample wilcoxon testresult = wilcox.test(myData$weight, mu = 25) # Printing the resultsprint(result)
Output:
name weight
1 R_1 27.6
2 R_2 30.6
3 R_3 32.2
4 R_4 25.3
5 R_5 30.9
6 R_6 31.0
7 R_7 28.9
8 R_8 28.9
9 R_9 28.9
10 R_10 28.2
Wilcoxon signed rank test with continuity correction
data: myData$weight
V = 55, p-value = 0.005793
alternative hypothesis: true location is not equal to 25
In the above output, the p-value of the test is 0.005793, which is less than the significance level alpha = 0.05. So we can reject the null hypothesis and conclude that the average weight of the rabbit is significantly different from 25g with a p-value = 0.005793.
There are mainly two techniques are used to compare the means of paired samples. These two techniques are:
Paired sample T-test
Paired Samples Wilcoxon Test
This is a statistical procedure that is used to determine whether the mean difference between two sets of observations is zero. In a paired sample t-test, each subject is measured two times, resulting in pairs of observations.
Implementation in R:
For performing a one-sample t-test in R, use the function t.test(). The syntax for the function is given below.
Syntax: t.test(x, y, paired =TRUE)
Parameters:
x, y: numeric vectors
paired: a logical value specifying that we want to compute a paired t-test
Example:
R
# R program to illustrate# Paired sample t-test set.seed(0) # Taking two numeric vectorsshopOne <- rnorm(50, mean = 140, sd = 4.5)shopTwo <- rnorm(50, mean = 150, sd = 4) # Using t.tset()result = t.test(shopOne, shopTwo, var.equal = TRUE) # Print the resultprint(result)
Output:
Two Sample t-test
data: shopOne and shopTwo
t = -13.158, df = 98, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-11.482807 -8.473061
sample estimates:
mean of x mean of y
140.1077 150.0856
The paired samples Wilcoxon test is a non-parametric alternative to paired t-test used to compare paired data. It’s used when data are not normally distributed.
Implementation in R:
To perform Paired Samples Wilcoxon-test, the R provides a function wilcox.test() that can be used as follows:
Syntax: wilcox.test(x, y, paired = TRUE, alternative = “two.sided”)
Parameters:
x, y: numeric vectors
paired: a logical value specifying that we want to compute a paired Wilcoxon test
alternative: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.
Example: Here, let’s use an example data set, which contains the weight of 10 rabbits before and after the treatment. We want to know, if there is any significant difference in the median weights before and after treatment?
R
# R program to illustrate# Paired Samples Wilcoxon Test # The data set# Weight of the rabbit before treatmentbefore <-c(190.1, 190.9, 172.7, 213, 231.4, 196.9, 172.2, 285.5, 225.2, 113.7) # Weight of the rabbit after treatmentafter <-c(392.9, 313.2, 345.1, 393, 434, 227.9, 422, 383.9, 392.3, 352.2) # Create a data framemyData <- data.frame(group = rep(c("before", "after"), each = 10),weight = c(before, after)) # Print all dataprint(myData) # Paired Samples Wilcoxon Testresult = wilcox.test(before, after, paired = TRUE) # Printing the resultsprint(result)
Output:
group weight
1 before 190.1
2 before 190.9
3 before 172.7
4 before 213.0
5 before 231.4
6 before 196.9
7 before 172.2
8 before 285.5
9 before 225.2
10 before 113.7
11 after 392.9
12 after 313.2
13 after 345.1
14 after 393.0
15 after 434.0
16 after 227.9
17 after 422.0
18 after 383.9
19 after 392.3
20 after 352.2
Wilcoxon signed rank test
data: before and after
V = 0, p-value = 0.001953
alternative hypothesis: true location shift is not equal to 0
In the above output, the p-value of the test is 0.001953, which is less than the significance level alpha = 0.05. We can conclude that the median weight of the mice before treatment is significantly different from the median weight after treatment with a p-value = 0.001953.
There are mainly two techniques are used to compare the one-sample mean to a standard known mean. These two techniques are:
Analysis of Variance (ANOVA)One way ANOVATwo way ANOVAMANOVA Test
One way ANOVA
Two way ANOVA
MANOVA Test
Kruskal–Wallis Test
The one-way analysis of variance (ANOVA), also known as one-factor ANOVA, is an extension of independent two-samples t-test for comparing means in a situation where there are more than two groups. In one-way ANOVA, the data is organized into several groups base on one single grouping variable.
Implementation in R:
For performing the one-way analysis of variance (ANOVA) in R, use the function aov(). The function summary.aov() is used to summarize the analysis of the variance model. The syntax for the function is given below.
Syntax: aov(formula, data = NULL)
Parameters:
formula: A formula specifying the model.
data: A data frame in which the variables specified in the formula will be found
Example:
One way ANOVA test is performed using mtcars dataset which comes preinstalled with dplyr package between disp attribute, a continuous attribute, and gear attribute, a categorical attribute.
R
# R program to illustrate# one way ANOVA test # Loading the packagelibrary(dplyr) # Calculate test statistics using aov functionmtcars_aov <- aov(mtcars $ disp ~ factor(mtcars $ gear))print(summary(mtcars_aov))
Output:
Df Sum Sq Mean Sq F value Pr(>F)
factor(mtcars$gear) 2 280221 140110 20.73 2.56e-06 ***
Residuals 29 195964 6757
—
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
The summary shows that the gear attribute is very significant to displacement(Three stars denoting it). Also, P value less than 0.05, so it proves that gear is significant to displacement i.e related to each other, and we reject the Null Hypothesis.
Two-way ANOVA test is used to evaluate simultaneously the effect of two grouping variables (A and B) on a response variable. It takes two categorical groups into consideration.
Implementation in R:
For performing the two-way analysis of variance (ANOVA) in R, also use the function aov(). The function summary.aov() is used to summarize the analysis of variance model. The syntax for the function is given below.
Syntax: aov(formula, data = NULL)
Parameters:
formula: A formula specifying the model.
data: A data frame in which the variables specified in the formula will be found
Example: Two way ANOVA test is performed using mtcars dataset which comes preinstalled with dplyr package between disp attribute, a continuous attribute and gear attribute, a categorical attribute, am attribute, a categorical attribute.
R
# R program to illustrate# two way ANOVA test # Loading the packagelibrary(dplyr) # Calculate test statistics using aov functionmtcars_aov2 = aov(mtcars $ disp ~ factor(mtcars $ gear) * factor(mtcars $ am))print(summary(mtcars_aov2))
Output:
Df Sum Sq Mean Sq F value Pr(>F)
factor(mtcars$gear) 2 280221 140110 20.695 3.03e-06 ***
factor(mtcars$am) 1 6399 6399 0.945 0.339
Residuals 28 189565 6770
—
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
The summary shows that gear attribute is very significant to displacement(Three stars denoting it) and am attribute is not much significant to displacement. P-value of gear is less than 0.05, so it proves that gear is significant to displacement i.e related to each other. P-value of am is greater than 0.05, am is not significant to displacement i.e not related to each other.
Multivariate analysis of variance (MANOVA) is simply an ANOVA (Analysis of variance) with several dependent variables. It is a continuation of the ANOVA. In an ANOVA, we test for statistical differences on one continuous dependent variable by an independent grouping variable. The MANOVA continues this analysis by taking multiple continuous dependent variables and bundles them collectively into a weighted linear composite variable. The MANOVA compares whether or not the newly created combination varies by the different levels, or groups, of the independent variable.
Implementation in R:
R provides a method manova() to perform the MANOVA test. The class “manova” differs from class “aov” in selecting a different summary method. The function manova() calls aov and then add class “manova” to the result object for each stratum.
Syntax: manova(formula, data = NULL, projections = FALSE, qr = TRUE, contrasts = NULL, ...)
Parameters:
formula: A formula specifying the model.
data: A data frame in which the variables specified in the formula will be found. If missing, the variables are searched for in the standard way.
projections: Logical flag
qr: Logical flag
contrasts: A list of contrasts to be used for some of the factors in the formula. ...: Arguments to be passed to lm, such as subset or na.action
Example: To perform the MANOVA test in R let’s take iris data set.
R
# R program to illustrate# MANOVA test # Import required librarylibrary(dplyr) # Taking iris data setmyData = iris # Show a random sampleset.seed(1234)dplyr::sample_n(myData, 10)
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.5 2.5 4.0 1.3 versicolor
2 5.6 2.5 3.9 1.1 versicolor
3 6.0 2.9 4.5 1.5 versicolor
4 6.4 3.2 5.3 2.3 virginica
5 4.3 3.0 1.1 0.1 setosa
6 7.2 3.2 6.0 1.8 virginica
7 5.9 3.0 4.2 1.5 versicolor
8 4.6 3.1 1.5 0.2 setosa
9 7.9 3.8 6.4 2.0 virginica
10 5.1 3.4 1.5 0.2 setosa
To know if there is any important difference, in sepal and petal length, between the different species then perform MANOVA test. Hence, the function manova() can be used as follows.
R
# Taking two dependent variablesepal = iris$Sepal.Lengthpetal = iris$Petal.Length # MANOVA testresult = manova(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris)summary(result)
Output:
Df Pillai approx F num Df den Df Pr(>F)
Species 2 0.9885 71.829 4 294 < 2.2e-16 ***
Residuals 147
—
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
From the output above, it can be seen that the two variables are highly significantly different among Species.
The Kruskal–Wallis test is a rank-based test that is similar to the Mann–Whitney U test but can be applied to one-way data with more than two groups. It is a non-parametric alternative to the one-way ANOVA test, which extends the two-samples Wilcoxon test. A group of data samples is independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test, it can be decided whether the population distributions are similar without assuming them to follow the normal distribution.
Implementation in R:
R provides a method kruskal.test() which is available in the stats package to perform a Kruskal-Wallis rank-sum test.
Syntax: kruskal.test(x, g, formula, data, subset, na.action, ...)
Parameters:
x: a numeric vector of data values, or a list of numeric data vectors.
g: a vector or factor object giving the group for the corresponding elements of x
formula: a formula of the form response ~ group where response gives the data values and group a vector or factor of the corresponding groups.
data: an optional matrix or data frame containing the variables in the formula .
subset: an optional vector specifying a subset of observations to be used.
na.action: a function which indicates what should happen when the data contain NA
...: further arguments to be passed to or from methods.
Example: Let’s use the built-in R data set named PlantGrowth. It contains the weight of plants obtained under control and two different treatment conditions.
R
# Preparing the data set# to perform Kruskal-Wallis Test # Taking the PlantGrowth data setmyData = PlantGrowthprint(myData) # Show the group levelsprint(levels(myData$group))
Output:
weight group
1 4.17 ctrl
2 5.58 ctrl
3 5.18 ctrl
4 6.11 ctrl
5 4.50 ctrl
6 4.61 ctrl
7 5.17 ctrl
8 4.53 ctrl
9 5.33 ctrl
10 5.14 ctrl
11 4.81 trt1
12 4.17 trt1
13 4.41 trt1
14 3.59 trt1
15 5.87 trt1
16 3.83 trt1
17 6.03 trt1
18 4.89 trt1
19 4.32 trt1
20 4.69 trt1
21 6.31 trt2
22 5.12 trt2
23 5.54 trt2
24 5.50 trt2
25 5.37 trt2
26 5.29 trt2
27 4.92 trt2
28 6.15 trt2
29 5.80 trt2
30 5.26 trt2
[1] "ctrl" "trt1" "trt2"
Here the column “group” is called factor and the different categories (“ctr”, “trt1”, “trt2”) are named factor levels. The levels are ordered alphabetically. The problem statement is we want to know if there is any significant difference between the average weights of plants in the 3 experimental conditions. And the test can be performed using the function kruskal.test() as given below.
R
# R program to illustrate# Kruskal-Wallis Test # Taking the PlantGrowth data setmyData = PlantGrowth # Performing Kruskal-Wallis testresult = kruskal.test(weight ~ group, data = myData)print(result)
Output:
Kruskal-Wallis rank sum test
data: weight by group
Kruskal-Wallis chi-squared = 7.9882, df = 2, p-value = 0.01842
As the p-value is less than the significance level 0.05, it can be concluded that there are significant differences between the treatment groups.
kumar_satyam
sweetyty
R Data-science
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
R Programming Language - Introduction
How to Change Axis Scales in R Plots? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 437,
"s": 28,
"text": "There are many cases in data analysis where you’ll want to compare means for two populations or samples and which technique you should use depends on what type of data you hav... |
Lazy Loading Design Pattern | 07 Feb, 2018
Lazy loading is a concept where we delay the loading of object until the point where we need it.
Lazy loading is just a fancy name given to the process of initializing a class when it’s actually needed.
In simple words, Lazy loading is a software design pattern where the initialization of an object occurs only when it is actually needed and not before to preserve simplicity of usage and improve performance.
Lazy loading is essential when the cost of object creation is very high and the use of the object is very rare. So this is the scenario where it’s worth implementing lazy loading.The fundamental idea of lazy loading is to load object/data when needed.
For Example, Suppose You are creating an application in which there is a Company object and this object contains a list of employees of the company in a ContactList object. There could be thousands of employees in a company. Loading the Company object from the database along with the list of all its employees in the ContactList object could be very time consuming. In some cases you don’t even require the list of the employees, but you are forced to wait until the company and its list of employees loaded into the memory.One way to save time and memory is to avoid loading of the employee objects until required and this is done using the Lazy Loading Design Pattern.There are four common implementations of Lazy Loading pattern :
Virtual proxyLazy initializationGhostValue holder
Virtual proxy
Lazy initialization
Ghost
Value holder
Virtual proxy
The Virtual Proxy pattern is a memory saving technique that recommends postponing an object creation until it is needed. It is used when creating an object the is expensive in terms of memory usage or processing involved.
// Java program to illustrate// virtual proxy in// Lazy Loading Design Patternimport java.util.List;import java.util.ArrayList; interface ContactList{public List<Employee> getEmployeeList();} class Company { String companyName; String companyAddress; String companyContactNo; ContactList contactList; public Company(String companyName, String companyAddress, String companyContactNo, ContactList contactList) { this.companyName = companyName; this.companyAddress = companyAddress; this.companyContactNo = companyContactNo; this.contactList = contactList; } public String getCompanyName() { return companyName; } public String getCompanyAddress() { return companyAddress; } public String getCompanyContactNo() { return companyContactNo; } public ContactList getContactList() { return contactList; } } class ContactListImpl implements ContactList { public List<Employee> getEmployeeList() { return getEmpList(); } private static List<Employee> getEmpList() { List<Employee> empList = new ArrayList<Employee>(5); empList.add(new Employee("Lokesh", 2565.55, "SE")); empList.add(new Employee("Kushagra", 22574, "Manager")); empList.add(new Employee("Susmit", 3256.77, "G4")); empList.add(new Employee("Vikram", 4875.54, "SSE")); empList.add(new Employee("Achint", 2847.01, "SE")); return empList; }} class ContactListProxyImpl implements ContactList { private ContactList contactList; public List<Employee> getEmployeeList() { if (contactList == null) { System.out.println("Fetching list of employees"); contactList = new ContactListImpl(); } return contactList.getEmployeeList(); }} class Employee { private String employeeName; private double employeeSalary; private String employeeDesignation; public Employee(String employeeName, double employeeSalary, String employeeDesignation) { this.employeeName = employeeName; this.employeeSalary = employeeSalary; this.employeeDesignation = employeeDesignation; } public String getEmployeeName() { return employeeName; } public double getEmployeeSalary() { return employeeSalary; } public String getEmployeeDesignation() { return employeeDesignation; } public String toString() { return "Employee Name: " + employeeName + ", EmployeeDesignation : " + employeeDesignation + ", Employee Salary : " + employeeSalary; }} class LazyLoading { public static void main(String[] args) { ContactList contactList = new ContactListProxyImpl(); Company company = new Company ("Geeksforgeeks", "India", "+91-011-28458965", contactList); System.out.println("Company Name: " + company.getCompanyName()); System.out.println("Company Address: " + company.getCompanyAddress()); System.out.println("Company Contact No.: " + company.getCompanyContactNo()); System.out.println("Requesting for contact list"); contactList = company.getContactList(); List<Employee> empList = contactList.getEmployeeList(); for (Employee emp : empList) { System.out.println(emp); } }}
Output:
Company Name: ABC Company
Company Address: India
Company Contact No.: +91-011-28458965
Requesting for contact list
Fetching list of employees
Employee Name: Lokesh, EmployeeDesignation: SE, Employee Salary: 2565.55
Employee Name: Kushagra, EmployeeDesignation: Manager, Employee Salary: 22574.0
Employee Name: Susmit, EmployeeDesignation: G4, Employee Salary: 3256.77
Employee Name: Vikram, EmployeeDesignation: SSE, Employee Salary: 4875.54
Employee Name: Achint, EmployeeDesignation: SE, Employee Salary: 2847.01
Now, In the above code have a Company object is created with a proxy ContactList object. At this time, the Company object holds a proxy reference, not the real ContactList object’s reference, so there no employee list loaded into the memory.
Lazy Initialization
The Lazy Initialization technique consists of checking the value of a class field when it’s being used. If that value equals to null then that field gets loaded with the proper value before it is returned.Here is the example :
// Java program to illustrate// Lazy Initialization in// Lazy Loading Design Patternimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry; enum CarType { none, Audi, BMW,} class Car { private static Map<CarType, Car> types = new HashMap<>(); private Car(CarType type) {} public static Car getCarByTypeName(CarType type) { Car Car; if (!types.containsKey(type)) { // Lazy initialisation Car = new Car(type); types.put(type, Car); } else { // It's available currently Car = types.get(type); } return Car; } public static Car getCarByTypeNameHighConcurrentVersion(CarType type) { if (!types.containsKey(type)) { synchronized(types) { // Check again, after having acquired the lock to make sure // the instance was not created meanwhile by another thread if (!types.containsKey(type)) { // Lazy initialisation types.put(type, new Car(type)); } } } return types.get(type); } public static void showAll() { if (types.size() > 0) { System.out.println("Number of instances made = " + types.size()); for (Entry<CarType, Car> entry : types.entrySet()) { String Car = entry.getKey().toString(); Car = Character.toUpperCase(Car.charAt(0)) + Car.substring(1); System.out.println(Car); } System.out.println(); } }} class Program { public static void main(String[] args) { Car.getCarByTypeName(CarType.BMW); Car.showAll(); Car.getCarByTypeName(CarType.Audi); Car.showAll(); Car.getCarByTypeName(CarType.BMW); Car.showAll(); }}
Output :
Number of instances made = 1
BMW
Number of instances made = 2
BMW
Audi
Number of instances made = 2
BMW
Audi
Value Holder
Basically, A value holder is a generic object that handles the lazy loading behavior and appears in place of the object’s data fields.When the user needs to access it, they simply ask the value holder for its value by calling the GetValue method. At that time (and only then), the value gets loaded from a database or from a service.(this is not always needed).
// Java function to illustrate// Lazy Initialization in// Lazy Loading Design Patternpublic class ValueHolder<T> { private T value; private readonly Func<object, T> valueRetrieval; // Constructor public ValueHolder(Func<object, T> valueRetrieval) { valueRetrieval = this.valueRetrieval; } // We'll use the signature "GetValue" for convention public T GetValue(object parameter) { if (value == null) value = valueRetrieval(parameter); return value; }}
Note : The main drawback of this approach is that the user has to know that a value holder is expected.
Ghost
A ghost is the object that is to be loaded in a partial state. It corresponds to the real object but not in its full state. It may be empty or it may contain just some fields (such as the ID). When the user tries to access some fields that haven’t been loaded yet, the ghost object fully initializes itself (this is not always needed).
For example, Let’s consider that a developer what add an online form so that any user can request content via that online form. At the time of creation all we know is that content will be accessed but what action or content is unknown to the user.
$userData = array( "UID" = > uniqid(), "requestTime" = > microtime(true), "dataType" = > "", "request" = > ""); if (isset($_POST['data']) && $userData) { //...}
In the above PHP example, the content from the online form can be accessed to the user in the form of text file or any source.
UID is the unique id for the every particular user.
requestTime is the time when user requested the content from the online form.
dataType is the type of data. Mostly it is text but depends on the form.
request is the boolean function to notify the user about the request being completed or not.
Advantages
This approach is a faster application start-up time as it is not required to created and load all of the application objects.
Disadvantages
The code becomes complicated as we need to check if loading is needed or not. So this may cause slower in the performance.
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Feb, 2018"
},
{
"code": null,
"e": 149,
"s": 52,
"text": "Lazy loading is a concept where we delay the loading of object until the point where we need it."
},
{
"code": null,
"e": 255,
"s": 149,
"text": "Lazy loa... |
WLAN Full Form | 11 Sep, 2021
WLAN stands for Wireless Local Area Network. WLAN is a local area network that uses radio communication to provide mobility to the network users, while maintaining the connectivity to the wired network. A WLAN basically, extends wired local area network. WLAN’s are built attaching a device called the access point(AP) to the edge of the wired network. Clients communicate with the AP using a wireless network adapter which is similar in function to a ethernet adapter. It is also called a LAWN that is Local area wireless network.
The performance of WLAN is high compared to other wireless networks. The coverage of WLAN is within a campus or building or that tech parks. It is used in the mobile propagation of wired networks. The standards of WLAN are HiperLAN, Wi-Fi, and IEEE 802.11. It offers service to the desktop laptop, mobile application and all the devices works on the Internet. WLAN is an affordable method and can be set up in 24 hours. WLAN gives users the mobility to move around within a local coverage area and still be connected to the network. Most latest brands are based on IEE 802.11 standards, which are the WI-FI brand name.
History : A professor at University of Hawaii who’s name was Norman Abramson, developed the world’s first wireless computer communication network. In 1979, Gfeller and u.Bapst published a paper in the IEE proceedings reporting an experimental wireless local area network using diffused infrared communications. The first of the IEEE workshops on Wireless LAN was held in 1991.
Characteristics :
Seamless operation.
Low power for battery use.
Simple management, easy to use for everyone.
Protection of investment in wired networks.
Robust transmission technology
Advantages :
Installation speed and simplicity.
Installation flexibility.
Reduced cost of ownership.
Reliability.
Mobility.
Robustness.
Disadvantages :
Slower bandwidth.
Security for wireless LAN’s is the prime concern.
Less capacity.
Wireless networks cost four times more than wired network cards.
Wireless devices emit low levels of RF which can be harmful to our health.
anikakapoor
Picked
Computer Networks
Full Form
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 561,
"s": 28,
"text": "WLAN stands for Wireless Local Area Network. WLAN is a local area network that uses radio communication to provide mobility to the network users, while maintaining the connect... |
Find row and column index of maximum and minimum value in a matrix in R | 21 Apr, 2021
In this article, we will discuss how to find the maximum and minimum value in any given matrix and printing its row and column index in the R Programming language.
Example:
Input: 11 -9 36
20 1 81
13 99 77
Output: maximum value: 99
row col
3 2
minimum value: -9
row col
1 2
In the code below, we have created a sample matrix, in which we have passed “nrow=3“(matrix will have only 3 rows) in example 1 and “ncol=2“(matrix will have only 2 columns) in example 2.
Then we have printed the sample matrix in the next line with the message “Sample Matrix”.
Then we have used the syntax below to find the row and column number of the maximum element and stored it in the variable “max”. We have made use of the max() function which is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc.
The “which()” function is used to get the index or position of the value which satisfies the given condition. Then we have printed the maximum value along with its row and column index.
Syntax: which(m == max(m), arr.ind=TRUE)
Example 1:
R
# defining a sample matrixm = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77), nrow = 3) print("Sample Matrix:")print(m) # stores indexes of max value max = which(m == max(m), arr.ind = TRUE) print(paste("Maximum value: ", m[max]))print(max)
Output:
[1] "Sample Matrix:"
[,1] [,2] [,3]
[1,] 11 -9 36
[2,] 20 1 81
[3,] 13 99 77
[1] "Maximum value: 99"
row col
[1,] 3 2
Example 2:
R
# defining a sample matrixm = matrix(c(1:16), ncol = 2) print("Sample Matrix:")print(m) # stores indexes of max valuemax = which(m == max(m), arr.ind=TRUE) print(paste("Maximum value: ",m[max]))print(max)
Output:
[1] "Sample Matrix:"
[,1] [,2]
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
[5,] 5 13
[6,] 6 14
[7,] 7 15
[8,] 8 16
[1] "Maximum value: 16"
row col
[1,] 8 2
In the code below, we have created a sample matrix, in which we have passed “nrow=3“(matrix will have only 3 rows) in example 1 and “ncol=8“(matrix will have only 8 columns) in example 2 as a parameter while defining the matrix.
Then we have printed the sample matrix in the next line with the message “Sample Matrix”.
Then we have used the syntax below to find the row and column number of the minimum element and stored it in the variable “min”. We have made use of the min() function which is used to find the minimum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc.
The “which()” function is used to get the index or position of the value which satisfies the given condition. Then we have printed the minimum value along with its row and column index.
Syntax: which(m == min(m), arr.ind=TRUE)
Example 1:
R
# defining a sample matrixm = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77), nrow = 3) print("Sample Matrix:")print(m) # stores indexes of min valuemin = which(m == min(m), arr.ind = TRUE) print(paste("Minimum value: ", m[min]))print(min)
Output:
[1] "Sample Matrix:"
[,1] [,2] [,3]
[1,] 11 -9 36
[2,] 20 1 81
[3,] 13 99 77
[1] "Minimum value: -9"
row col
[1,] 1 2
Example 2:
R
# defining a sample matrixm = matrix(c(1:16), ncol = 8) print("Sample Matrix:")print(m) # stores indexes of min value min = which(m == min(m), arr.ind = TRUE) print(paste("Minimum value: ", m[min]))print(min)
Output:
[1] "Sample Matrix:"
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 3 5 7 9 11 13 15
[2,] 2 4 6 8 10 12 14 16
[1] "Minimum value: 1"
row col
[1,] 1 1
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "In this article, we will discuss how to find the maximum and minimum value in any given matrix and printing its row and column index in the R Programming language."
},
{
... |
R – Strings | 08 Jun, 2022
Strings are a bunch of character variables. It is a one-dimensional array of characters. One or more characters enclosed in a pair of matching single or double quotes can be considered a string in R. Strings represent textual content and can contain numbers, spaces, and special characters. An empty string is represented by using “. Strings are always stored as double-quoted values in R. Double quoted string can contain single quotes within it. Single quoted strings can’t contain single quotes. Similarly, double quotes can’t be surrounded by double quotes.
Strings can be created by assigning character values to a variable. These strings can be further concatenated by using various functions and methods to form a big string.
Example:
Python3
# R program for String Creation # creating a string with double quotesstr1 <- "OK1"cat ("String 1 is : ", str1) # creating a string with single quotesstr2 <- 'OK2'cat ("String 2 is : ", str2)str3 <- "This is 'acceptable and 'allowed' in R"cat ("String 3 is : ", str3)str4 <- 'Hi, Wondering "if this "works"'cat ("String 4 is : ", str4)str5 <- 'hi, ' this is not allowed'cat ("String 5 is : ", str5)
Output:
String 1 is: OK1
String 2 is: OK2
String 3 is: This is 'acceptable and 'allowed' in R
String 4 is: Hi, Wondering "if this "works"
Error: unexpected symbol in " str5 <- 'hi, ' this"
Execution halted
The length of strings indicates the number of characters present in the string. The function str_length() belonging to the ‘string’ package or nchar() inbuilt function of R can be used to determine the length of strings in R.
Example 1: Using the str_length() function
Python3
# R program for finding length of string # Importing packagelibrary(stringr) # Calculating length of string str_length("hello")
Output:
5
Example 2: Using nchar() function
Python3
# R program to find length of string # Using nchar() functionnchar("hel'lo")
Output:
6
The individual characters of a string can be extracted from a string by using the indexing methods of a string. There are two R’s inbuilt functions in order to access both the single character as well as the substrings of the string.
substr() or substring() function in R extracts substrings out of a string beginning with the start index and ending with the end index. It also replaces the specified substring with a new set of characters.
Syntax:
substr(..., start, end)
or
substring(..., start, end)
Example 1: Using substr() function
Python3
# R program to access# characters in a string # Accessing characters# using substr() functionsubstr("Learn Code Tech", 1, 1)
Output:
"L"
If the starting index is equal to the ending index, the corresponding character of the string is accessed. In this case, the first character, ‘L’ is printed.
Example 2: Using substring() function
Python3
# R program to access characters in stringstr <- "Learn Code" # counts the characters in the stringlen <- nchar(str) # Accessing character using# substring() functionprint (substring(str, len, len)) # Accessing elements out of indexprint (substring(str, len+1, len+1))
Output:
[1] "e"
The number of characters in the string is 10. The first print statement prints the last character of the string, “e”, which is str[10]. The second print statement prints the 11th character of the string, which doesn’t exist, but the code doesn’t throw an error and print “”, that is an empty character.
The following R code indicates the mechanism of String Slicing, where in the substrings of a string are extracted:
Python3
# R program to access characters in stringstr <- "Learn Code" # counts the number of characters of str = 10len <- nchar(str)print(substr(str, 1, 4))print(substr(str, len-2, len))
Output:
[1]"Lear"
[1]"ode"
The first print statement prints the first four characters of the string. The second print statement prints the substring from the indexes 8 to 10, which is “ode”.
The string characters can be converted to upper or lower case by R’s inbuilt function toupper() which converts all the characters to upper case, tolower() which converts all the characters to lower case, and casefold(..., upper=TRUE/FALSE) which converts on the basis of the value specified to the upper argument. All these functions can take in as arguments multiple strings too. The time complexity of all the operations is O(number of characters in the string).
Example:
Python3
# R program to Convert case of a stringstr <- "Hi LeArn CodiNG"print(toupper(str))print(tolower(str))print(casefold(str, upper = TRUE))
Output:
[1] "HI LEARN CODING"
[1] "hi learn coding"
[1] "HI LEARN CODING"
By default, the value of upper in casefold() function is set to FALSE. If we set it to TRUE, the string gets printed in upper case.
The characters, as well as substrings of a string, can be manipulated to new string values. The changes are reflected in the original string. In R, the string values can be updated in the following way:
substr (..., start, end) <- newstring
substring (..., start, end) <- newstring
Multiple strings can be updated at once, with the start <= end.
If the length of the substring is larger than the new string, only the portion of the substring equal to the length of the new string is replaced.
If the length of the substring is smaller than the new string, the position of the substring is replaced with the corresponding new string values.
aekansh53
Picked
R Data-types
R-strings
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 590,
"s": 28,
"text": "Strings are a bunch of character variables. It is a one-dimensional array of characters. One or more characters enclosed in a pair of matching single or double quotes can be c... |
Get array dimensions and size of a dimension in Julia – size() Method | 26 Mar, 2020
The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.
Syntax:size(A::AbstractArray)orsize(A::AbstractArray, Dim)
Parameters:
A: Specified array
Dim: Specified dimension
Returns: It returns a tuple containing the dimensions of the specified array.
Example 1:
# Julia program to illustrate # the use of Array size() method # Finding a tuple containing the dimension of# the specified 1D array A.A = [5, 10, 15, 20]println(size(A)) # Finding a tuple containing the dimension of# the specified 2D array B of size 2*2B = [5 10; 15 20]println(size(B)) # Finding a tuple containing the dimension of# the specified 3D array C of size 2*2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims=3)println(size(C))
Output:Example 2:
# Julia program to illustrate # the use of Array size() method # Finding a tuple containing the dimension of# the specified 1D array A.A = [1, 2, 3];println(size(A, 3)) # Finding a tuple containing the dimension of# the specified 2D array B of size 3*2B = [2 4; 6 8; 10 12];println(size(B, 2)) # Finding a tuple containing the dimension of# the specified 3D array C of size 2*2*4C = cat([10 15; 20 25], [30 35; 40 45], [50 55; 60 65], [70 75; 80 85], dims=3);println(size(C, 2))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 265,
"s": 28,
"text": "The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is... |
Program to generate random alphabets | 23 Mar, 2022
Prerequisite : rand() and srand() Given all alphabets in a character array, print a string of random characters of given size.We will use rand() function to print random characters. It returns random integer values. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called.
A ubiquitous use of unpredictable random characters is in cryptography, which underlies most of the schemes which attempt to provide security in modern communications (e.g. confidentiality, authentication, electronic commerce, etc).Random numbers are also used in situations where “fairness” is approximated by randomization, such as selecting jurors and military draft lotteries.Random numbers have uses in physics such as electronic noise studies, engineering, and operations research. Many methods of statistical analysis, such as the bootstrap method, require random numbers.
A ubiquitous use of unpredictable random characters is in cryptography, which underlies most of the schemes which attempt to provide security in modern communications (e.g. confidentiality, authentication, electronic commerce, etc).
Random numbers are also used in situations where “fairness” is approximated by randomization, such as selecting jurors and military draft lotteries.
Random numbers have uses in physics such as electronic noise studies, engineering, and operations research. Many methods of statistical analysis, such as the bootstrap method, require random numbers.
Pseudo code : 1. First we initialize two character arrays, one containing all the alphabets and other of given size n to store result.2. Then we initialize the seed to current system time so that every time a new random seed is generated.3. Next, we use for loop till n and store random generated alphabets. Below is C++ implementation of above approach :
C++
Java
C#
Javascript
// CPP Program to generate random alphabets#include <bits/stdc++.h>using namespace std; const int MAX = 26; // Returns a string of random alphabets of// length n.string printRandomString(int n){ char alphabet[MAX] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; string res = ""; for (int i = 0; i < n; i++) res = res + alphabet[rand() % MAX]; return res;} // Driver codeint main(){ srand(time(NULL)); int n = 10; cout << printRandomString(n); return 0;}
// JAVA Program to generate random alphabetsimport java.util.*; class GFG{ static int MAX = 26; // Returns a String of random alphabets of// length n.static String printRandomString(int n){ char []alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; String res = ""; for (int i = 0; i < n; i++) res = res + alphabet[(int) (Math.random() * 100 % MAX)]; return res;} // Driver codepublic static void main(String[] args){ int n = 10; System.out.print(printRandomString(n));}} // This code is contributed by Rajput-Ji
// C# Program to generate random alphabetsusing System; class GFG{static int MAX = 26; // Returns a String of random alphabets of// length n.static String printRandomString(int n){ char []alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; Random random = new Random(); String res = ""; for (int i = 0; i < n; i++) res = res + alphabet[(int)(random.Next(0, MAX))]; return res;} // Driver codepublic static void Main(){ int n = 10; Console.Write(printRandomString(n));}}
<script>// JAVAscript Program to generate random alphabetslet MAX = 26; // Returns a String of random alphabets of// length n.function printRandomString(n){ let alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; let res = ""; for (let i = 0; i < n; i++) { res = res + alphabet[Math.floor(Math.random() * 10) % MAX]; } return res;} // Driver codelet n = 10;document.write(printRandomString(n)); // This code is contributed by gfgking.</script>
urdfwootzr
This program will print different characters every time we run the code.
Rajput-Ji
gfgking
jackk787878
Arrays
C++ Programs
Technical Scripter
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 393,
"s": 52,
"text": "Prerequisite : rand() and srand() Given all alphabets in a character array, print a string of random characters of given size.We will use rand() function to print random char... |
Tournament Selection (GA) | 11 Jul, 2022
Tournament Selection is a Selection Strategy used for selecting the fittest candidates from the current generation in a Genetic Algorithm. These selected candidates are then passed on to the next generation. In a K-way tournament selection, we select k-individuals and run a tournament among them. Only the fittest candidate amongst those selected candidates is chosen and is passed on to the next generation. In this way many such tournaments take place and we have our final selection of candidates who move on to the next generation. It also has a parameter called the selection pressure which is a probabilistic measure of a candidate’s likelihood of participation in a tournament. If the tournament size is larger, weak candidates have a smaller chance of getting selected as it has to compete with a stronger candidate. The selection pressure parameter determines the rate of convergence of the GA. More the selection pressure more will be the Convergence rate. GAs are able to identify optimal or near-optimal solutions over a wide range of selection pressures. Tournament Selection also works for negative fitness values.
Algorithm --
1.Select k individuals from the population and perform a tournament amongst them
2.Select the best individual from the k individuals
3. Repeat process 1 and 2 until you have the desired amount of population
Let us have a 3-way tournament selection and our desired population size is 6 and the initial population with their fitness scores is [1, 2, 3, 4, 5, 6]. Our first tournament will look something like this (see the diagram) and the winner candidate with fitness value 6 moves on to the next generation.
Tournament Selection
If the best candidate is selected with probability pthen the next best candidate will be selected with a probability of p*(1-p)and the next one with p*(1-p)2and so on ...
References —1.http://wpmedia.wolfram.com/uploads/sites/13/2018/02/09-3-2.pdf2.https://en.wikipedia.org/wiki/Tournament_selection
Genetic Algorithms
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 1184,
"s": 54,
"text": "Tournament Selection is a Selection Strategy used for selecting the fittest candidates from the current generation in a Genetic Algorithm. These selected candidates are then... |
File Mapping in C++ Applications | 13 Apr, 2021
File mapping is a concept where a file map object can be created for a file on the disk. Thereafter, different processes can create a view of this file mapping object in their virtual address spaces. A process can create one or more views of the file mapping object in its virtual address space and work on it. Below is the working diagram for the file mapping object:
Do remember the following key points
The file is present on the disk of the machine on which the processes are running.The file mapping object is present in the physical memory.More than one process can create views for the same file mapping object.The file mapping object can contain the entire file or a part of it. Similarly, the file view for processes can contain the entire file mapping object or a part of it.All the copies are coherent and the same as that present on the disk.
The file is present on the disk of the machine on which the processes are running.
The file mapping object is present in the physical memory.
More than one process can create views for the same file mapping object.
The file mapping object can contain the entire file or a part of it. Similarly, the file view for processes can contain the entire file mapping object or a part of it.
All the copies are coherent and the same as that present on the disk.
Advantages
It is a great help when working with huge files like database files as not the whole file needs to be present in the physical memory.More than one process can use a file on the disk for both read and write operations. Each process can create a new view, un-mapping the current file view.
It is a great help when working with huge files like database files as not the whole file needs to be present in the physical memory.
More than one process can use a file on the disk for both read and write operations. Each process can create a new view, un-mapping the current file view.
Steps to create a file mapping object and file view
Step 1: Create or open a file object that represents the file on the disk. Here, we created a new file object with handle as hFile and named as “datafile.txt”.
HANDLE CreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
// Can be used as
HANDLE hFile = CreateFile(TEXT("datafile.txt"),
GENERIC_READ | GENERIC_WRITE,
0,
// Open with exclusive access
NULL,
// No security attributes
// Creating a new temp file
CREATE_NEW,
// Delete the file after unmapping the view
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
HANDLE CreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
// Can be used as
HANDLE hFile = CreateFile(TEXT("datafile.txt"),
GENERIC_READ | GENERIC_WRITE,
0, // open with exclusive access
NULL, // no security attributes
CREATE_NEW, // creating a new temp file
FILE_FLAG_DELETE_ON_CLOSE, //delete the file after unmapping the view
NULL);
Step 2: Create a map object for the file that contains information about how to access the file and its size. So, after creating the above file we use its handle and create its mapping in the physical memory.
HANDLE CreateFileMappingA(
HANDLE hFile,
LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
LPCSTR lpName
);
// Can be used as
HANDLE hFileMapping = ::CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, bufferSize, filename);
Step 3: Map all or part of the file-mapping object from the physical memory into your process’s virtual address space. So here we are creating the view of the mapped file which will be used by the process.
LPVOID MapViewOfFile(
HANDLE hFileMappingObject,
DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh,
DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap
);
// Can be used as
void* p = ::MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, param1, param2);
Step 4: Cleaning up
4(A) Un-map the file mapping object from the process address space. Backtrack the above steps and firstly, remove the file views from the process’s address space.
BOOL UnmapViewOfFile(LPCVOID lpBaseAddress
);
// Can be used as
UnmapViewOfFile(p);
4(B) Close the file mapping object. This step removes the file mapping from physical memory.
CloseHandle(hFileMapping);
4(C) Close the file object. Here, close the file opened on the disk and free the handle. Since in the first step we set flag FILE_FLAG_DELETE_ON_CLOSE, the file will be deleted after this step.
CloseHandle(hFile);
Note:
Close the handles in the same order or else it will give rise to discrepancies.Close all the open file handles before trying to delete the file.
Close the handles in the same order or else it will give rise to discrepancies.
Close all the open file handles before trying to delete the file.
cpp-file-handling
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "File mapping is a concept where a file map object can be created for a file on the disk. Thereafter, different processes can create a view of this file mapping object in their... |
How to detect value change on hidden input field in JQuery ? - GeeksforGeeks | 03 Aug, 2021
In the <input> element with the type=”hidden”, the change() method of jQuery is not automatically triggered. The change() method is only triggered automatically when the user himself changes the value of the field and not the developer. When the developer changes the value inside the hidden field, he has to trigger the change as well.
There two possible way to detect the value change on the hidden input field:
By using bind() method
By using change() method
Below examples will illustrate both the methods to detect the change of value in the hidden field.
Example 1: The following example uses the inbuilt bind() method of jQuery.
<!DOCTYPE html><html> <head> <title> By using bind() method detecting change of value in the hidden field </title> <script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3>By using bind() method</h3> <form> <input type="hidden" value="" id="hidField"> <button type="button" id="changeValue"> Click to change value </button> </form> <script> $(document).ready(function() { alert("Value of hidden field before updating: " + $("#hidField").val()); $("#changeValue").click(function() { $("#hidField").val(10).trigger("change"); }); $("input[type='hidden']").bind("change", function() { alert("Value of hidden field after updating: " + $(this).val()); }); }) </script></body> </html>
Output:
Example 2: The following example uses the inbuilt change() method of jQuery.
<!DOCTYPE html><html> <head> <title> By using change() method detecting change of value in the hidden field </title> <script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3>By using change() method</h3> <form> <input type="hidden" value="" id="hidField"> <br> <button type="button" id="changeValue"> Click to change value </button> </form> <script> $(document).ready(function() { alert("Value of hidden field before updating: " + $("#hidField").val()); $("#changeValue").click(function() { $("#hidField").val(101).trigger("change"); }); $("#hidField").change(function() { alert("Value of hidden field after updating: " + $("#hidField").val()); }); }) </script></body> </html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
AnasShamoon
ManasChhabra2
jQuery-Misc
Picked
JQuery
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
How to reset a form using jQuery with .reset() method?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24867,
"s": 24839,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25204,
"s": 24867,
"text": "In the <input> element with the type=”hidden”, the change() method of jQuery is not automatically triggered. The change() method is only triggered automatically wh... |
Importance of transferTo() method of InputStream in Java 9? | The transferTo() method has been added to the InputStream class in Java 9. This method has been used to copy data from input streams to output streams in Java. It means it reads all bytes from an input stream and writes the bytes to an output stream in the order in which they are reading.
public long transferTo(OutputStream out) throws IOException
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class TransferToMethodTest {
public void testTransferTo() throws IOException {
byte[] inBytes = "tutorialspoint".getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(inBytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
bis.transferTo(bos);
byte[] outBytes = bos.toByteArray();
System.out.println(Arrays.equals(inBytes, outBytes));
} finally {
try {
bis.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
bos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws Exception {
TransferToMethodTest test = new TransferToMethodTest();
test.testTransferTo();
}
}
true | [
{
"code": null,
"e": 1352,
"s": 1062,
"text": "The transferTo() method has been added to the InputStream class in Java 9. This method has been used to copy data from input streams to output streams in Java. It means it reads all bytes from an input stream and writes the bytes to an output stream in ... |
How do I set the default value for a column in MySQL? | To set the default value, use the DEFAULT keyword.
Let us first create a table −
mysql> create table DemoTable758 (
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(100)
);
Query OK, 0 rows affected (0.66 sec)
Following is the query to set default value for a column −
mysql> alter table DemoTable758 add column Colors ENUM('RED','GREEN','BLUE','ORANGE','YELLOW') DEFAULT 'YELLOW';
Query OK, 0 rows affected (0.44 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again −
mysql> desc DemoTable758;
This will produce the following output -
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| FirstName | varchar(100) | YES | | NULL | |
| Colors | enum('RED','GREEN','BLUE','ORANGE','YELLOW') | YES | | YELLOW | |
+-----------+----------------------------------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Insert some records in the table using insert command. Here, we haven’t inserted the value for 2nd column with FirstName “John”. The default value “YELLOW” will get placed there −
mysql> insert into DemoTable758(FirstName) values('John');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable758(FirstName,Colors) values('Carol','RED');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable758;
This will produce the following output -
+----+-----------+--------+
| Id | FirstName | Colors |
+----+-----------+--------+
| 1 | John | YELLOW |
| 2 | Carol | RED |
+----+-----------+--------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1113,
"s": 1062,
"text": "To set the default value, use the DEFAULT keyword."
},
{
"code": null,
"e": 1143,
"s": 1113,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1291,
"s": 1143,
"text": "mysql> create table DemoTable7... |
Faster R-CNN | ML - GeeksforGeeks | 14 Feb, 2022
After the improvement in architecture of object detection network in R-CNN to Fast R_CNN. The training and detection time of the network decrease considerably, but the network is not fast enough to be used as a real-time system because it takes approximately (2 seconds) to generate output on an input image. The bottleneck of architecture is a selective search algorithm. Therefore K He et al. proposed a new architecture called Faster R-CNN. It does not use selective search instead they propose another region proposal generation algorithm called Region Proposal Network. Let’s discuss the Faster R-CNN architecture.
Faster R-CNN architecture
Faster R-CNN architecture contains 2 networks:
Region Proposal Network (RPN)Object Detection Network
Region Proposal Network (RPN)
Object Detection Network
Before discussing the Region proposal we need to look into the CNN architecture which is the backbone of this network. This CNN architecture is common between both Region Proposal Network and Object Detection Network. We experimented with ZF (which has 5 shareable Conv layers) or VGG-16 (which has 13 shareable Conv) as the backbone in their architecture. Both backbone network has the network stride of 16 which means an image of dimension 1000 * 600 is reduced to (1000/16 * 600/16) or approximately (~ 62 *37) size feature map before passing into region proposal network.
Region Proposal Network (RPN): This region proposal network takes convolution feature map that is generated by the backbone layer as input and outputs the anchors generated by sliding window convolution applied on the input feature map.
Function of RPN (Feature Map to Region Proposal)
Anchors: For each sliding window, the network generates the maximum number of k- anchor boxes. By the default the value of k=9 (3 scales of (128*128, 256*256 and 512*512) and 3 aspect ratio of (1:1, 1:2 and 2:1)) for each of different sliding position in image. Therefore, for a convolution feature map of W * H, we get N = W* H* k anchor boxes. These region proposals then passed into an intermediate layer of 3*3 convolution and 1 padding and 256 (for ZF) or 512 (for VGG-16 ) output channels. The output generated from this layer is passed into two layers of 1*1 convolution, the classification layer, and the regression layer. the regression layer has 4*N (W * H * (4*k)) output parameters (denoting the coordinates of bounding boxes) and the classification layer has 2*N (W * H * (2*k)) output parameters (denoting the probability of object or not object).
Anchor generation
Training and Loss Function (RPN) : First of all, we remove all the cross-boundary anchors, so, that they do not increase the loss function. For a typical 1000*600 image, there are roughly 20000(~ 60*40*9) anchors. If we remove the cross-boundary anchors then there are roughly 6000 anchors left per image. The paper also uses Non-Maximum Suppression based on their classification and IoU. Here they use a fixed IoU of 0.7. This also reduces the number of anchors to 2000. The advantage of using Non-Maximum suppression that it also doesn’t hurt accuracy as well. RPN can be trained end to end by using backpropagation and stochastic gradient descent. It generates each mini-batch from the anchors of a single image. It does not train loss function on each anchor instead it selects 256 random anchors with positive and negative sample s in the ratio of 1:1. If an image contains <128 positives then it uses more negative samples. For training RPNs, First, we need to assign binary class label (weather the concerned anchor contains an object or background). In the faster R-CNN paper, the author uses two conditions to assign a positive label to an anchor. These are :
those anchors which have the highest Intersection-over-Union (IoU) with a ground-truth box, or
an anchor that has an IoU overlap higher than 0.7 with any ground-truth box.
and negative label to those which has IoU overlap is <0.3 for all ground truth boxes. Those anchors which does not have either positive or negative label does not contribute to training. Now Loss function is defined as follows :
where,
pi = predicted probability of anchors contains an object or not.
pi* = ground truth value of anchors contains and object or not.
ti = coordinates of predicted anchors.
ti* = ground truth coordinate associated with bounding boxes.
Lcls = Classifier Loss (binary log loss over two classes).
Lreg = Regression Loss (Here, Lreg = R(ti-ti*) where R is smooth L1 loss)
Ncls = Normalization parameter of mini-batch size (~256).
Nreg = Normalization parameter of regression (equal to number of anchor locations ~2400).
In order to make n=both loss parameter equally weighted right.
Object Detection Network: The object detection network used in Faster R-CNN is very much similar to that used in Fast R-CNN. It is also compatible with VGG-16 as a backbone network. It also uses the RoI pooling layer for making region proposal of fixed size and twin layers of softmax classifier and the bounding box regressor is also used in the prediction of the object and its bounding box.
Fast R-CNN architecture
RoI pooling : We take the output generated from region proposal as input and passed into the RoI pooling layer, this RoI pooling layer has the same function as it performed in Fast R-CNN, to make different sizes region proposals generated from RPN into a fixed-size feature map. We have discussed RoI pooling in this article in great detail. This RoI pooling layer generates the output of size (7*7*D) (where D =256 for ZF and 512 of VGG-16).
Softmax and Bounding Box Regression Layer: The feature map of size (7 * 7 * D) generated in RoI pooling are then sent to two fully connected layers, these fully connected layers flatten the feature maps and then send the output into two parallel fully connected layer each with the different task assigned to them:
The first layer is a softmax layer of N+1 output parameters (N is the number of class labels and background ) that predicts the objects in the region proposal. The second layer is a bounding box regression layer that has 4* N output parameters. This layer regresses the bounding box location of the object in the image.
Softmax Classifier and Bounding Box Regressor
Training (Full Architecture): We have discussed training the RPN but in this part, we will discuss training the whole architecture. The authors of Faster R-CNN papers use an approach called 4 steps alternating training method. This approach is as follows
We first initialize the backbone CNN network with ImageNet weights and fine-tuned these weights for region proposal. Now, we trained the RPN as described above.
We separately trained the object detection network using the proposal generated by the RPN network. In this part also the backbone network is initialized with ImageNet weight and until now it is not connected to the RPN network.
The RPN is now initialized with weights from a detector network (Fast R-CNN). This time only the weights of layers unique to the RPN are fine-tuned.
Using the new fine-tuned RPN, the Fast R-CNN detector is fine-tuned. Again, only the layers unique to the detector network are fine-tuned and the common layer weights are fixed.
Results and Conclusion:
Since the bottleneck of Fast R-CNN architecture is region proposal generation with the selective search. Faster R-CNN replaced it with its own Region Proposal Network. This Region proposal network is faster as compared to selective and it also improves region proposal generation model while training. This also helps us reduce the overall detection time as compared to fast R-CNN (0.2 seconds with Faster R-CNN (VGG-16 network) as compared to 2.3 in Fast R-CNN).
Faster R-CNN (with RPN and VGG shared) when trained with COCO, VOC 2007 and VOC 2012 dataset generates mAP of 78.8% against 70% in Fast R-CNN on VOC 2007 test dataset)
Region Proposal Network (RPN) when compared to selective search, also contributed marginally to the improvement of mAP.
References :
Fast R-CNN paper
Faster R-CNN paper
sumitgumber28
Artificial Intelligence
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Python | Decision tree implementation
Search Algorithms in AI
Decision Tree Introduction with example
Elbow Method for optimal value of k in KMeans
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24486,
"s": 24458,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 25107,
"s": 24486,
"text": "After the improvement in architecture of object detection network in R-CNN to Fast R_CNN. The training and detection time of the network decrease considerably, but... |
Valid Substring | Practice | GeeksforGeeks | Given a string S consisting only of opening and closing parenthesis 'ie '(' and ')', find out the length of the longest valid(well-formed) parentheses substring.
NOTE: Length of the smallest valid substring ( ) is 2.
Example 1:
Input: S = "(()("
Output: 2
Explanation: The longest valid
substring is "()". Length = 2.
Example 2:
Input: S = "()(())("
Output: 6
Explanation: The longest valid
substring is "()(())". Length = 6.
Your Task:
You dont need to read input or print anything. Complete the function findMaxLen() which takes S as input parameter and returns the maxlength.
Expected Time Complexity:O(n)
Expected Auxiliary Space: O(1)
Constraints:
1 <= |S| <= 105
+4
amonk6 days ago
it is a hard question on leetcode
0
velspace011 week ago
Java sol TC-->O(N)
SC-->O(1)
static int findMaxLen(String s) {
int max=0;
int open=0;
int close=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('){
open++;
}else{
close++;
}
if(open==close){
max=Math.max(max,open+close);
}
else if(close>open){
open=0;
close=0;
}
}
close=0;
open=0;
for(int i=s.length()-1;i>=0;i--){
if(s.charAt(i)=='('){
open++;
}
else{
close++;
}
if(open==close){
max=Math.max(max,open+close);
}
else if(open>close){
open=0;
close=0;
}
}
return max;
}
0
harshscode2 weeks ago
stack<int> st; int res=0; int n=s.length(); st.push(-1); for(int i=0;i<n;i++) { if(s[i]=='(') { st.push(i); } else { st.pop(); if(!st.empty()) { res=max(res,i-st.top()); } else { st.push(i); } } } return res;
-2
yadavbanti4953 weeks ago
int findMaxLen(string s) { stack<int>S; S.push(-1); int count=0; for(int i=0;i<s.length();i++) { if(s[i]=='(') { S.push(s[i]); } else if(s[i]==')' && S.top()!=-1) { if(S.top()=='(') { count=count+2; S.pop(); } else { S.push(s[i]); } } } return count;
why this code not pass all the test case pls anyone find error
0
vishalja77191 month ago
int findMaxLen(string s) {
stack<int>st;
int count=0;
st.push(-1);
for(int i=0;i<s.length();i++)
{
if(s[i] == '(')
{
st.push(i);
}else if(s[i] == ')')
{
st.pop();
if(!st.empty())
{
count=max(count,i-st.top());
}else{
st.push(i);
}
}
}
return count;
}
+1
hanumanmanyam8371 month ago
class Solution {
static int findMaxLen(String S) {
// code here
Stack<Integer>st=new Stack<>();
int count=0;
st.push(-1);
for(int i=0;i<S.length();i++)
{
if(S.charAt(i)=='(')
{
st.push(i);
}
else if(S.charAt(i)==')')
{
st.pop();
if(!st.isEmpty())
{
count=Math.max(count,i-st.peek());
}
else
{
st.push(i);
}
}
}
return count;
}
};
0
sanketgharatkar123
This comment was deleted.
0
aahankatiyar1 month ago
why code is not passing all test cases ??
int findMaxLen(string s) { stack<char> sta; int count=0; for(int i=0; i< s.size() ; i++) { if(sta.empty()) { sta.push(s[i]); } else if(s[i] =='(') { sta.push(s[i]); } else if(s[i]==')') { if(sta.top() == '(') { count +=2; sta.pop(); } else { sta.push(s[i]); } } } return count;
}
+2
manaskhare330s1 month ago
Is it a easy question, I don't think so.
0
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
class Solution {
static int findMaxLen(String s) {
// code here
Stack<Integer> st = new Stack<>();
for(int i=0;i<s.length();i++){
if(st.isEmpty() || s.charAt(i)=='(') st.push(i);
else if(s.charAt(st.peek())=='(') st.pop();
else st.push(i);
}
int curr = s.length();
int ans = 0;
while(!st.isEmpty()){
ans = Math.max(ans,curr-st.peek()-1);
curr = st.pop();
}
return Math.max(ans,curr);
}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 456,
"s": 238,
"text": "Given a string S consisting only of opening and closing parenthesis 'ie '(' and ')', find out the length of the longest valid(well-formed) parentheses substring.\nNOTE: Length of the smallest valid substring ( ) is 2."
},
{
"code": null,
"e":... |
Groovy - Dates & Times equals() | Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.
Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.
public boolean equals(Object obj)
obj - the object to compare with.
True if the objects are the same; false otherwise.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
Date olddate = new Date("05/11/2015");
Date newdate = new Date("05/11/2015");
Date latestdate = new Date();
System.out.println(olddate.equals(newdate));
System.out.println(latestdate.equals(newdate));
}
}
When we run the above program, we will get the following result −
true
false
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2427,
"s": 2238,
"text": "Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object."
},
{
"code": null,
"e": 2532,
"s": 2427,
"t... |
How to show all X-axis labels in a bar graph created by using barplot function in R? | In base R, the barplot function easily creates a barplot but if the number of bars is large or we can say that if the categories we have for X-axis are large then some of the X-axis labels are not shown in the plot. Therefore, if we want them in the plot then we need to use las and cex.names.
Consider the below data and bar graph −
Live Demo
> x<-sample(1:5,20,replace=TRUE)
> names(x)<-rep(c("IN","CO","LA","NY"),times=5)
> barplot(x)
Showing all the X-axis labels −
> barplot(x,las=2,cex.names=0.5) | [
{
"code": null,
"e": 1356,
"s": 1062,
"text": "In base R, the barplot function easily creates a barplot but if the number of bars is large or we can say that if the categories we have for X-axis are large then some of the X-axis labels are not shown in the plot. Therefore, if we want them in the plo... |
What is 3-way merge or merge commit in Git? | Let us look at an example of a 3-way merge. In this example, the Feature branch is two commits ahead of the Master branch.
Diagram 1
Before we merge it with Master, let us say we have added an additional commit to the Master as shown in the below diagram.
Diagram 2
Due to the commit performed on the Master branch, both our branches Master and Feature are now diverged.
This means we have some changes in the Master branch that is not present in the Feature branch. If we perform a merge in this case, Git cannot move the master pointer towards the Feature branch.
If git simply moves the Master pointer to the Feature pointer, then the latest commit C6 performed on the Master branch will be lost.
So how do we perform a merge if the branches are diverged?
When we want to merge the branches that are diverged, Git creates a new commit (Merge Commit) and combines the changes of these two branches as shown in the below diagram.
Diagram 3
The reason it is called a 3-way merge is because the Merge Commit is based on 3 different commits.
The common ancestor of our branches, in this case commit number C3. This commit contains code before we diverge into different branches.
The common ancestor of our branches, in this case commit number C3. This commit contains code before we diverge into different branches.
The tip of the Master branch, that is the last commit performed on the Master branch - C6
The tip of the Master branch, that is the last commit performed on the Master branch - C6
The tip of the Feature branch, the last commit performed on the Feature branch - C5
The tip of the Feature branch, the last commit performed on the Feature branch - C5
To merge the changes from both the branches, Git looks at the three different snapshots - the before snapshot and the after snapshots. Based on these snapshots, Git combines the changes by creating the new commit called the Merge Commit.
$ git init
$ echo one>1.txt
$ git add .
$ git commit -m 'c1'
$ echo two>2.txt
$ git add .
$ git commit -m 'c2'
$ echo three>3.txt
$ git add .
$ git commit -m 'C3'
$ git branch feature
$ git switch feature
$ echo four>4.txt
$ git add .
$ git commit -m 'c4'
$ echo five>5.txt
$ git add .
$ git commit -m 'c5'
$ git switch master
$echo six>6.txt
$ git add .
$ git commit -m 'c6'
$ git merge feature
$ git log --oneline --all --graph
hint: Waiting for your editor to close the file... unix2dos: converting file E:/git_clone/test_repo/.git/MERGE_MSG to DOS format...
dos2unix: converting file E:/git_clone/test_repo/.git/MERGE_MSG to Unix format...
Merge made by the 'recursive' strategy.
4.txt | 1 +
5.txt | 1 +
2 files changed, 2 insertions(+)
create mode 100644 4.txt
create mode 100644 5.txt
* e1ce060 (HEAD -> master) Merge branch 'feature'
|\
| * 3435c89 (feature) c5
| * 7e7761b c4
* | 5618675 c6
|/
* 6ad93bf C3
* 9031c20 c2
* 3f68f83 c1 | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "Let us look at an example of a 3-way merge. In this example, the Feature branch is two commits ahead of the Master branch."
},
{
"code": null,
"e": 1195,
"s": 1185,
"text": "Diagram 1"
},
{
"code": null,
"e": 1318,
"s... |
Hibernate - Annotations | So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata.
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM applications, you must use annotations to represent the mapping information, but still if you want greater flexibility, then you should go with XML-based mappings.
First of all you would have to make sure that you are using JDK 5.0 otherwise you need to upgrade your JDK to JDK 5.0 to take advantage of the native support for annotations.
Second, you will need to install the Hibernate 3.x annotations distribution package, available from the sourceforge: (Download Hibernate Annotation) and copy hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your CLASSPATH.
As I mentioned above while working with Hibernate Annotation, all the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development.
Consider we are going to use the following EMPLOYEE table to store our objects −
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Following is the mapping of Employee class with annotations to map objects with the defined EMPLOYEE table −
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Hibernate detects that the @Id annotation is on a field and assumes that it should access properties of an object directly through fields at runtime. If you placed the @Id annotation on the getId() method, you would enable access to properties through getter and setter methods by default. Hence, all other annotations are also placed on either fields or getter methods, following the selected strategy.
Following section will explain the annotations used in the above class.
The EJB 3 standard annotations are contained in the javax.persistence package, so we import this package as the first step. Second, we used the @Entity annotation to the Employee class, which marks this class as an entity bean, so it must have a no-argument constructor that is visible with at least protected scope.
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.
The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table. For now, we are using just table name, which is EMPLOYEE.
Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure.
By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but you can override this by applying the @GeneratedValue annotation, which takes two parameters strategy and generator that I'm not going to discuss here, so let us use only the default key generation strategy. Letting Hibernate determine which generator type to use makes your code portable between different databases.
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes −
name attribute permits the name of the column to be explicitly specified.
name attribute permits the name of the column to be explicitly specified.
length attribute permits the size of the column used to map a value particularly for a String value.
length attribute permits the size of the column used to map a value particularly for a String value.
nullable attribute permits the column to be marked NOT NULL when the schema is generated.
nullable attribute permits the column to be marked NOT NULL when the schema is generated.
unique attribute permits the column to be marked as containing only unique values.
unique attribute permits the column to be marked as containing only unique values.
Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records and then we will apply CRUD operations on those records.
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Employee.class).
buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
/* List down all the employees */
ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator = employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Now let us create hibernate.cfg.xml configuration file to define database related parameters.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name = "hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume students is the database name -->
<property name = "hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name = "hibernate.connection.username">
root
</property>
<property name = "hibernate.connection.password">
cohondob
</property>
</session-factory>
</hibernate-configuration>
Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
Delete Employee.hbm.xml mapping file from the path.
Delete Employee.hbm.xml mapping file from the path.
Create Employee.java source file as shown above and compile it.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
Execute ManageEmployee binary to run the program.
You would get the following result, and records would be created in EMPLOYEE table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Zara Last Name: Ali Salary: 1000
First Name: Daisy Last Name: Das Salary: 5000
First Name: John Last Name: Paul Salary: 10000
First Name: Zara Last Name: Ali Salary: 5000
First Name: John Last Name: Paul Salary: 10000
If you check your EMPLOYEE table, it should have the following records −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 29 | Zara | Ali | 5000 |
| 31 | John | Paul | 10000 |
+----+------------+-----------+--------+
2 rows in set (0.00 sec
mysql>
108 Lectures
11 hours
Chaand Sheikh
65 Lectures
5 hours
Karthikeya T
39 Lectures
4.5 hours
TELCOMA Global
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2369,
"s": 2063,
"text": "So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addi... |
MongoDB query to convert string to int? | To convert string to int, use parseInt() in MongoDB. Let us first create a collection with documents −
> db.demo369.insertOne({"Price":"1000000"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e57e2e32ae06a1609a00aed")
}
> db.demo369.insertOne({"Price":"1747864"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e57e2e92ae06a1609a00aee")
}
> db.demo369.insertOne({"Price":"19548575"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e57e2ee2ae06a1609a00aef")
}
Display all documents from a collection with the help of find() method −
> db.demo369.find();
This will produce the following output −
{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : "1000000" }
{ "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : "1747864" }
{ "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : "19548575" }
Following is the query to convert string to int −
> db.demo369.find().forEach( function (d) {
... d.Price= parseInt(d.Price);
... db.demo369.save(d);
... });
Display all documents from a collection with the help of find() method −
> db.demo369.find();
This will produce the following output −
{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : 1000000 }
{ "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : 1747864 }
{ "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : 19548575 } | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "To convert string to int, use parseInt() in MongoDB. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1556,
"s": 1165,
"text": "> db.demo369.insertOne({\"Price\":\"1000000\"});\n{\n \"acknowledged\" : true... |
Ethereum - Quick Guide | A huge success of Bitcoin raised interest in the minds of several to create their own currencies. Looking at the advantages offered by Bitcoin - a digital currency, people wanted to use the concept of Blockchain in their own applications. People wanted to move out of their physical contracts to smart digital contracts where several issues like repudiation, transparency, security, etc. would be automatically addressed. The outcome of this effort resulted in the creation of Ethereum - a popular platform for creating distributed Blockchain applications that support smart contracts.
In this tutorial, you will learn how to create a distributed application (DAPP) on Ethereum platform. More specifically, you will learn how to write a contract, test it on a local Blockchain and finally deploy it on an external Blockchain for deep testing and commercial use. You will use Solidity, an object-oriented language for contract development. You will also use Remix, an open source IDE for developing and testing contracts. To deploy the tested contract on an external Blockchain, you will use Ganache. To interact with the contract you will need a client application. We will use MyEtherWallet to create a wallet for each such client. The contract creator will publish the contract. Any other client will look at the contact value by using the interface provided by the contract and send some money to the creator for executing a part of the contract.
So let us begin by writing the contract.
There are several tools available to develop and test contracts. One of the simplest tools is provided on the official Ethereum site itself. The tool is called Remix, we will use this for our contract development.
Open the Remix IDE by typing in the following URL in your browser.
The following screen will appear.
In the center window, you will see some default code, which is a sample Solidity code. You will type your contract code in this code editor. Your code may be auto-compiled. Upon successful compilation of the code, you will be able to run the code in the same IDE. When you execute the contract methods, the results will be displayed in the same IDE window. There are facilities to debug the code and to unit test your project. These can be seen in the menu bar at the top right hand side as shown in the IDE screenshot below. You will be using these options shortly.
You will now start writing your contract.
Solidity is an object-oriented language especially developed for contract writing. It is a high-level language, which inherits traits from C++, Python, and JavaScript. The Solidity compiler compiles your source code into bytecode that runs on Ethereum Virtual Machine (EVM).
For quick understanding of the Solidity syntax, look at the sample code in the IDE.
pragma solidity >=0.4.22 <0.6.0;
contract Ballot {
The first line is a directive to the compiler. The second line starts the definition of the contract. Within the contract, you declare variables such as −
address chairperson;
You can also define structures such as Proposal and create an array of these structure items. Examine this in the code window.
You may then define a constructor which is invoked at the time of instantiating a contract.
constructor(uint8 _numProposals) public {
After the constructor, you will define several methods, which are the contract methods. In the sample contract, giveRightToVote is one such method having the following syntax −
function giveRightToVote(address toVoter) public {
The public keyword makes this method publicly invokable by any client who has access to the contract.
Likewise, the sample contract defines three more methods called delegate, vote, and winningProposal. Examine these for your own understanding of the Solidity syntax. These are the prerequisites to writing your own contract. Explaining the full syntax of Solidity is beyond the scope of this tutorial.
We will name our contract MyContract as in the following declaration −
contract MyContract {
We will declare two variables as follows −
uint amount;
uint value;
The variable amount will hold the accumulated money sent by the contract executors to the contract creator. The value field will hold the contract value. As the executors execute the contract, the value field will be modified to reflect the balanced contract value.
In the contract constructor, we set the values of these two variables.
constructor (uint initialAmount, uint initialValue) public {
amount = 0;
value = 1000;
}
As initially, the amount collected on the contract is zero, we set the amount field to 0. We set the contract value to some arbitrary number, in this case it is 1000. The contract creator decides this value.
To examine the collected amount at any given point of time, we provide a public contract method called getAmount defined as follows −
function getAmount() public view returns(uint) {
return amount;
}
To get the balanced contract value at any given point of time, we define getBalance method as follows −
function getBalance() public view returns(uint) {
return value;
}
Finally, we write a contract method (Send). It enables the clients to send some money to the contract creator −
function send(uint newDeposit) public {
value = value - newDeposit;
amount = amount + newDeposit;
}
The execution of the send method will modify both value and amount fields of the contract.
The complete contract code is given below −
contract MyContract {
uint amount;
uint value;
constructor (uint initialAmount, uint initialValue) public {
amount = 0;
value = 1000;
}
function getBalance() public view returns(uint) {
return value;
}
function getAmount() public view returns(uint) {
return amount;
}
function send(uint newDeposit) public {
value = value - newDeposit;
amount = amount + newDeposit;
}
}
Once you write the complete contract code, compiling it in this IDE is trivial. Simply click on the Autocompile checkbox in the IDE as shown in the screenshot below −
Alternatively, you may compile the contract by clicking the button with the title “Start to compile”.
If there is any typo, fix it in the code window. Make sure the code is compiled fully without errors. Now, you are ready to deploy the contract.
In this chapter, we will learn how to deploy contract on Ethereum. Click on the Run menu option to deploy the contract. The following screen will appear.
The contract name is shown in the highlighted list box. Below this, you will notice the Deploy button, click on it to deploy the contract. The contract will be deployed on the Remix built-in Blockchain. You will be able to see the deployed contract at the bottom of the screen. You can see this in the highlighted portion of the screenshot below.
Notice, the presence of three method names in this highlighted region. Next, you will interact with the contract by executing the contract methods.
When you click the deployed contract, you will see the various public methods provided by the contract. This is shown in the screenshot below.
The first method send contains an edit box in front of it. Here, you will type the parameters required by the contract method. The other two methods do not take any parameters.
Now, enter some amount such as 100 in front of the send function seen in the contract window. Click the send button. This will execute the contract send method, reducing the value of the contract value field and increasing the value of the amount field.
The previous send money action has reduced the contract value by 100. You can now examine this by invoking the getBalance method of the contract. You will see the output when you click on the getBalance button as shown in the screenshot below −
The contract value is now reduced to 900.
In this section, we will examine the amount of money collected so far on this contract. For this, click on the getAmount button. The following screen will appear.
The amount field value has changed from 0 to 100.
Try a few send operations and examine the contract value and the amount fields to conclude that the deployed contract is executing as expected.
The Remix IDE that you have used so far is good enough for development and initial testing of your contract. For real-life contracts, you need to test your functionality against various parameters. Remix cannot create real (non-test) user accounts to transfer funds between them. You have no control over the configuration of the Blockchain created by Remix. You cannot even monitor the execution of the transactions.
Remix misses out on several advanced operations. Thus, we need to deploy our contract on a more sophisticated Blockchain that provides all these features. One such Blockchain is Ganache that you will learn about in our subsequent chapter.
Ganache is used for setting up a personal Ethereum Blockchain for testing your Solidity contracts. It provides more features when compared to Remix. You will learn about the features when you work out with Ganache. Before you begin using Ganache, you must first download and install the Blockchain on your local machine.
You may download Ganache from the following URL −
Ganache is available on several platforms. We developed and tested this entire tutorial on Mac. Thus, the screenshots below will show Mac installation. When you open the installation URL given above, it automatically detects your machine’s OS and directs you to the appropriate binary installation. The screenshot below shows the Mac installation.
When you click on the DOWNLOAD button, it will begin downloading the DMG file for Mac installation.
Locate the “Ganache-2.0.0.dmg” in your Downloads folder and double-click on it to install Ganache. Upon successful installation, the following screen will appear −
Drag Ganache icon to the Application folder. Now, Ganache is available as an application on your Mac.
If you are using some other OS, follow the instructions provided for successful installation.
Now locate Ganache in your Application folder and double-click on its icon to start Ganache.
When Ganache starts, the Ganache screen will appear as shown below −
Click QUICKSTART to start Ganache. You will see Ganache console as shown below −
The console in the above screenshot shows two user accounts with balance of 100 ETH (Ether - a currency for transaction on Ethereum platform). It also shows a transaction count of zero for each account. As the user has not performed any transactions so far, this count is obviously zero.
We will now get an overview of a few important screens of Ganache that are of immediate relevance to us.
Click on the settings icon at the top right hand side of the screen as shown in the screenshot below −
The server settings screen will appear as shown below −
Here, you will be able to set the values of server address and the port number for your Ganache server. For the time being, leave these to their default values. The Network ID is an internal Blockchain identifier of Ganache server; leave this to its default value. The Automine button is in the ON state indicating that the transactions would be processed instantly. If you switched this off, it will ask you to enter the time in seconds after which the blocks would be mined.
When you click on the Accounts & Keys menu option, you will see the following screen −
Here you would be able to set the default balance for each account. The default value is 100. This now explains why you saw 100 ETH displayed for each account in the Desktop screenshot. You can also set the number of accounts on this screen. The value displayed in this screenshot is 2 and that is why the desktop showed only two accounts.
Now, we will work out with the two settings’ screen; the knowledge of how these two work would suffice. Restart the server by clicking on the RESTART button in the right hand side of the screen. You will now return to the Desktop screen. Try inputting different values in the above two fields, restart the server and see its effect.
We will now briefly understand what is available on the Ganache desktop. On the Desktop, at the top we have several menu options out of which a few are of immediate relevance to us. The menu bar is highlighted in the screenshot below −
Clicking on the TRANSACTIONS menu shows all the transactions performed so far. You will be performing transactions very soon. Now, come back to the above screen and check the transactions from time to time. A typical transaction screen is as shown below −
Likewise, when you click on the BLOCKS menu, you will see the various mined blocks. Consider the following screenshot to understand how the BLOCKS menu looks like −
Click on the LOGS menu. It will open the system log for you. Here, you can examine the various operations that you have performed on the Ethereum Blockchain.
Now, as you have understood how to use Ganache for setting up a private Ethereum Blockchain, you will now create a few clients who would use this Blockchain.
For client application, you will use MyEtherWallet.
Download MyEtherWallet software from the following URL −
https://github.com/kvhnuke/etherwallet/releases/tag/v3.21.06
If required, unzip the downloaded file and open index.html. You will see the following interface for creating a new wallet.
In this chapter, we will learn how to create Ethereum wallet. To create a new wallet, enter a password of your choice and then click on the “Create New Wallet” button. When you do so, a Wallet would be created. A digital wallet is essentially the generation of a public/private key pair that you need to store in a safe place. The wallet creation results in the following screen −
Click on the “Download Keystore File (UTC / JSON)” button to save the generated keys. Now, click on the “I understand. Continue” button. Your private key will appear on the screen as seen in the screenshot below −
Click on the “Print Paper Wallet” button to keep a physical record of your wallet’s private key. You will need this later for unlocking the wallet. You will see the following screen. Do not lose this output.
To unlock your wallet, click on the “Save Your Address” button. You will see the following screen.
The wallet can be unlocked using the Private Key option as highlighted in the above screen. Cut-n-paste the private key from the previous screenshot and click the Unlock button. Your wallet will be unlocked and you will see a message appear at the bottom of the screen. As the wallet does not contain anything as of now, unlocking the wallet is not really useful to us at this point.
You have now created a wallet; this wallet is a client interface to the Blockchain. We will attach the wallet to the Ganache Blockchain that you have started in the earlier lesson. To do so, click on the Network dropdown box as shown in the screenshot below −
Go to the bottom of the list. You will see an option for “Add Custom Network / Node”. Select this item.
Now, a screen will appear asking for the Ganache server address and the port to which it is listening.
Type your Ganache server details – http://127.0.0.1 and Port: 8545. These would be the values set by you in the Ganache server setup. Give a name of your choice to this node. Click on the “Save & Use Custom Node” button. You will see the connected message at the bottom of the screen. At this point, your wallet is successfully connected to the Ganache Blockchain.
You are now ready to deploy the contract on this connected Blockchain.
To deploy the contract, select the Contracts menu option as shown in the screenshot below −
You will need to enter the contract’s bytecode on this screen. Remember, when you compile your Solidity contract code, it generated a bytecode that runs on EVM. You will now need to obtain this bytecode from Remix IDE.
Go to the Remix IDE screen, your earlier typed contract should be there in the code window. If not, retype the contract in the code window. Click on the Bytecode button as shown in the following screenshot −
The bytecode for your compiled source is copied to the clipboard along with some other information. Paste the copied code into your favorite text editor. Following is the screenshot of the text editor −
The value of the object tag contains the desired bytecode. Copy this carefully making sure that you do not copy the enclosing quotes. The bytecode is really long, so make sure that you copy right upto the last byte inclusive of it. Now, paste this bytecode in the Deploy Contract screen as shown below −
The Gas Limit field is automatically set.
Below the Gas Limit field, you will find the selection for accessing the wallet.
Now, access the wallet using the Private Key of the Ganache account on which this contract will be deployed. To get this private key, go back to the Ganache window. Click on the keys icon of the first account as shown below −
You will see the private key of the user account # 1 as seen in the screenshot below −
Copy this private key and paste it in the “Paste Your Private Key” section as shown below −
You will see the “Unlock” button at the bottom of the screen. After unlocking, a “success” message will appear at the bottom of the screen. At this point, your wallet is attached to account #1 of the Ganache Blockchain.
Now, you are ready to sign and deploy the contract. Click on the “Sign Transaction” button as shown in the screenshot below −
Signing the transaction generates and displays both Raw and Signed transactions. Click on the “Deploy Contract” button to deploy the contract on the Ganache Blockchain. Remember the contract is deployed by account # 1 user of the Ganache Blockchain. Therefore, account # 1 user becomes the contract creator. Before the contract is deployed, you will be asked to confirm the transaction as it may cost you some real money if you were to deploy this contract on a public real Ethereum Blockchain. Do not worry, for the current private Blockchain running on your local machine, there is no real money involved. Click on the Make transaction button as shown in the screenshot below −
Examine the Ganache console; you will see that the ETH balance in the account # 1 has reduced as seen in the screenshot below −
Now, click on the TRANSACTIONS menu as shown in the screenshot below −
You will see the transaction details.
On this screen, you will find the contract’s published address. The address is marked in the above screenshot. You will distribute this address publicly to let others know that your contract is available at this specified address to which they can connect and execute the contract methods, such as sending money to you - the contract creator. Copy this contract address for your own reference as you are going to need it in the next step.
Now, you are ready to interact with the contract that you have deployed. Go back to MyEtherWallet desktop and click on the “Interact with Contract” tab as shown in the screenshot below −
Paste the contract address that you previously copied in the “Contract Address” field. You also need to paste the “ABI / JSON Interface” of the contract on the above screen.
To get the ABI, go to the Remix window and click on the ABI button as shown in the screenshot below.
The ABI / JSON interface will be copied to the clipboard. Paste this in your favorite editor to examine the generated interface, which is shown below −
ABI / JSON Interface
[
{
"constant": false,
"inputs": [
{
"name": "newDeposit",
"type": "uint256"
}
],
"name": "send",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"name": "initialAmount",
"type": "uint256"
},
{
"name": "initialValue",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": true,
"inputs": [],
"name": "getAmount",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getBalance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
After you paste this JSON in the MyEtherWallet interface, you will notice that the ACCESS button below the JSON interface is now activated, as shown below −
Click Access button to access the contract.
Upon clicking the Access button, the contract address and function selection dropdown will appear on the screen like in the Remix editor. This is shown in the screenshot below −
You may check the various functions of the contract as in the case of Remix deployment. Note that the contact is now deployed on an external Ganache Blockchain. Check the getAmount function; you will get the Amount value of zero and the getBalance will show a balance of 1000.
Now try sending some money. It will present you a textedit control for entering the amount. When you write the contract, some “gas” would be used and you will be asked to confirm the transaction before writing it to the Blockchain. The transaction would be executed in a short while depending on the mining timing set by you on the Ganache server. After this, you can reexamine the value and the amount fields of the contract to verify that these are indeed modified.
You may now examine the Ganache desktop to view the transactions that you have performed so far. A sample output is shown below −
So far, you were both the contract creator and the contract executor. This does not make much sense, as you expect others to use your contract. For this, we will create another client for our Ganache Blockchain and send some money from the newly created account # 2 to the contract creator at account # 1.
In this chapter, we will learn the creation of contract users on Ethereum. To create a user for our published contract, we will create another MyEtherWallet client attached to the same Ganache Blockchain that you have been using in the previous steps. Go to the MyEtherWallet screen and create a new wallet.
Click on the contracts menu and select the “Interact with Contract” option as in the earlier case. Note that this new user is going to simply interact with the already published contract and not deploying his own contract. Specify the contract address and the ABI that you used in the earlier case.
Now, click Access button and invoke send method. When asked, input some value say 100 ETH to be sent. Submit the transaction. Upon submission, the following screen will appear.
To attach this new client to our Ganache Blockchain, go to Ganache Console. Click on the keys icon of account # 2 as shown in the following screenshot −
You will get the private key for account # 2.
Copy the key that you receive and use it in your newly created wallet as shown here −
Click on the Unlock button to attach the wallet.
When the wallet is successfully unlocked, write the desired send transaction.
Generate the transaction by clicking on the “Generate Transaction” button.
Make the transaction and wait for some time for it to reflect in the Blockchain. Now, execute “getAmount”, the amount shown should be 200 now.
Execute “getBalance”. The value field should now be 800.
Examine the transaction log to see the various transactions performed by different users.
You learned how to write your own digital contract in Solidity. You developed and tested the contract interface in the Remix IDE. For further multi-user testing, you deployed this contract on Ganache Blockchain. On Ganache, you created two user accounts. The first account was used for publishing the contract. The second account was used for consuming the contract.
The Ganache Blockchain that you used in this entire process is private and local to your machine. Once you are fully satisfied with the functioning of the contract, you may proceed to publish it on a real-life Ethereum Blockchain. However, doing so would require you to spend real money. In the demo application, we used 1000 ETH as default for each user account in Ganache. When you deploy your contract on a real-life Blockchain, you will have to buy the ETH by converting your own country’s currency to ETH. This currency would be stored in your wallet and you will be able to spend it the way you want.
38 Lectures
4.5 hours
Abhilash Nelson
53 Lectures
9.5 hours
Frahaan Hussain
62 Lectures
8.5 hours
Frahaan Hussain
103 Lectures
9.5 hours
Total Seminars
31 Lectures
3.5 hours
Swapnil Kole
64 Lectures
12.5 hours
Blockchain Post
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2749,
"s": 2163,
"text": "A huge success of Bitcoin raised interest in the minds of several to create their own currencies. Looking at the advantages offered by Bitcoin - a digital currency, people wanted to use the concept of Blockchain in their own applications. People wanted ... |
Detecting people with a RaspberryPi, a thermal camera and machine learning | by Fabio Manganiello | Towards Data Science | An updated version of this story is available for free on the Platypush blog.
Triggering events based on the presence of people has been the dream of many geeks and DIY automators for a while. Having your house to turn the lights on or off when you enter or exit your living room is an interesting application, for instance. Most of the solutions out there to solve these kinds of problems, even more high-end solutions like the Philips Hue sensors, detect motion, not actual people presence — which means that the lights will switch off once you lay on your couch like a sloth. The ability to turn off music and/or tv when you exit the room and head to your bedroom, without the hassle of switching all the buttons off, is also an interesting corollary. Detecting the presence of people in your room while you’re not at home is another interesting application.
Thermal cameras coupled with deep neural networks are a much more robust strategy to actually detect the presence of people. Unlike motion sensors, they will detect the presence of people even when they aren’t moving. And, unlike optical cameras, they detect bodies by measuring the heat that they emit in the form of infrared radiation, and are therefore much more robust — their sensitivity doesn’t depend on lighting conditions, on the position of the target, or the colour. Before exploring the thermal camera solution, I tried for a while to build a model that instead relied on optical images from a traditional webcam. The differences are staggering: I trained the optical model on more than ten thousands 640x480 images taken all through a week in different lighting conditions, while I trained the thermal camera model on a dataset of 900 24x32 images taken during a single day. Even with more complex network architectures, the optical model wouldn’t score above a 91% accuracy in detecting the presence of people, while the thermal model would achieve around 99% accuracy within a single training phase of a simpler neural network. Despite the high potential, there’s not much out there in the market — there’s been some research work on the topic (if you google “people detection thermal camera” you’ll mostly find research papers) and a few high-end and expensive products for professional surveillance. In lack of ready-to-go solutions for my house, I decided to take on my duty and build my own solution — making sure that it can easily be replicated by anyone.
A RaspberryPi (cost: around $35). In theory any model should work, but it’s probably not a good idea to use a single-core RaspberryPi Zero for machine learning tasks — the task itself is not very expensive (we’ll only use the Raspberry for doing predictions on a trained model, not to train the model), but it may still suffer some latency on a Zero. Any more performing model should do the job well.
A thermal camera. For this project, I’ve used the MLX90640 Pimoroni breakout camera (cost: $55), as it’s relatively cheap, easy to install, and it provides good results. This camera comes in standard (55°) and wide-angle (110°) versions. I’ve used the wide-angle model as the camera monitors a large living room, but take into account that both have the same resolution (32x24 pixels), so the wider angle comes with the cost of a lower spatial resolution. If you want to use a different thermal camera there’s not much you’ll need to change, as long as it comes with a software interface for RaspberryPi and it’s compatible with platypush.
If you used a breakout camera I personally advise to install it on something like the Breakout Garden (cost: $10-14), as it makes it easy to install it just on top of your RaspberryPi with no need for soldering.
Setting up the MLX90640 on your RaspberryPi if you have a Breakout Garden it’s easy as a pie. Fit the Breakout Garden on top of your RaspberryPi. Fit the camera breakout into an I2C slot. Boot the RaspberryPi. Done.
I tested my code on Raspbian, but with a few minor modifications it should be easily adaptable to any distribution installed on the RaspberryPi.
The software support for the thermal camera requires a bit of work. The MLX90640 doesn’t come (yet) with a Python ready-to-use interface, but a C++ open-source driver is provided for it. Instructions to install it:
# Install the dependencies[sudo] apt-get install libi2c-dev# Enable the I2C interfaceecho dtparam=i2c_arm=on | sudo tee -a /boot/config.txt# It's advised to configure the SPI bus baud rate to# 400kHz to support the higher throughput of the sensorecho dtparam=i2c1_baudrate=400000 | sudo tee -a /boot/config.txt# A reboot is required here if you didn't have the# options above enabled in your /boot/config.txt# Clone the driver's codebasegit clone https://github.com/pimoroni/mlx90640-librarycd mlx90640-library# Compile the rawrgb examplemake cleanmake I2C_MODE=LINUX examples/rawrgb
If it all went well you should see an executable named rawrgb under the examples directory. If you run it you should see a bunch of binary data — that’s the raw binary representation of the frames captured by the camera. Remember where it is located or move it to a custom bin folder, as it’s the executable that platypush will use to interact with the camera module.
This post assumes that you have already installed and configured platypush on your system. If not, head to my post on getting started with platypush, the readthedocs page, the GitHub page or the wiki.
You’ll need the following Python dependencies on the RaspberryPi as well:
# For machine learning image predictionspip install opencv opencv-contrib-python# For image manipulation in the MLX90640 pluginpip install Pillow
In this example we’ll use the RaspberryPi for the capture and prediction phases and a more powerful machine for the training phase. You’ll need the following dependencies on the machine you’ll be using to train your model:
# For image manipulationpip install opencv# Install Jupyter notebook to run the training codepip install jupyterlab# Then follow the instructions at https://jupyter.org/install# Tensorflow framework for machine learning and utilitiespip install tensorflow numpy matplotlib# Clone my repository with the image and training utilities# and the Jupyter notebooks that we'll use for traininggit clone https://github.com/BlackLight/imgdetect-utils
Now that you’ve got all the hardware and software in place, it’s time to start capturing frames with your camera and use them to train your model. First, configure the MLX90640 plugin in your platypush configuration file:
camera.ir.mlx90640: fps: 16 # Frames per second rotate: 270 # Can be 0, 90, 180, 270 rawrgb_path: /path/to/your/rawrgb
Restart platypush. If you enabled the HTTP backend you can test if you are able to take pictures:
curl -XPOST -H 'Content-Type: application/json' \ -d '{"type":"request", "action":"camera.ir.mlx90640.capture", "args": {"output_file":"~/snap.png", "scale_factor":20}}' \ http://localhost:8008/execute?token=...
The thermal picture should have been stored under ~/snap.png. In my case it looks like this while I’m in front of the sensor:
Notice the glow at the bottom-right corner — that’s actually the heat from my RaspberryPi 4 CPU. It’s there in all the images I take, and you may probably see similar results if you mounted your camera on top of the Raspberry itself, but it shouldn’t be an issue for your model training purposes.
If you open the webpanel (http://your-host:8008) you’ll also notice a new tab, represented by the sun icon, that you can use to monitor your camera from a web interface.
You can also monitor the camera directly outside of the webpanel by pointing your browser to http://your-host:8008/camera/ir/mlx90640/stream?rotate=270&scale_factor=20.
Now add a cronjob to your platypush configuration to take snapshots every minute:
cron.ThermalCameraSnapshotCron: cron_expression: '* * * * *' actions: - action: camera.ir.mlx90640.capture args: output_file: "${__import__(’datetime’).datetime.now().strftime(’/img/folder/%Y-%m-%d_%H-%M-%S.jpg’)}" grayscale: true
The images will be stored under /img/folder in the format YYYY-mm-dd_HH-MM-SS.jpg. No scale factor is applied — even if the images will be tiny we’ll only need them to train our model. Also, we’ll convert the images to grayscale — the neural network will be lighter and actually more accurate, as it will only have to rely on one variable per pixel without being tricked by RGB combinations.
Restart platypush and verify that every minute a new picture is created under your images directory. Let it run for a few hours or days until you’re happy with the number of samples. Try to balance the numbers of pictures with no people in the room and those with people in the room, trying to cover as many cases as possible — e.g. sitting, standing in different points of the room etc. As I mentioned earlier, in my case I only needed less than 1000 pictures with enough variety to achieve accuracy levels above 99%.
Once you’re happy with the number of samples you’ve taken, copy the images over to the machine you’ll be using to train your model (they should be all small JPEG files weighing under 500 bytes each). Copy them to the folder where you have cloned my imgdetect-utils repository:
BASEDIR=~/git_tree/imgdetect-utils# This directory will contain your raw imagesIMGDIR=$BASEDIR/datasets/ir/images# This directory will contain the raw numpy training# data parsed from the imagesDATADIR=$BASEDIR/datasets/ir/datamkdir -p $IMGDIRmkdir -p $DATADIR# Copy the imagesscp pi@raspberry:/img/folder/*.jpg $IMGDIR# Create the labels for the images. Each label is a# directory under $IMGDIRmkdir $IMGDIR/negativemkdir $IMGDIR/positive
Once the images have been copied and the directories for the labels created, run the label.py script provided in the repository to interactively label the images:
cd $BASEDIRpython utils/label.py -d $IMGDIR --scale-factor 10
Each image will open in a new window and you can label it by typing either 1 (negative) or 2 (positive):
At the end of the procedure the negative and positive directories under the images directory should have been populated.
Once we’ve got all the labelled images it’s time to train our model. A train.ipynb Jupyter notebook is provided under notebooks/ir and it should be relatively self-explanatory:
If you managed to execute the whole notebook correctly you’ll have a file named ir.pb under models/ir/tensorflow. That’s your Tensorflow model file, you can now copy it over to the RaspberryPi and use it to do predictions:
scp $BASEDIR/models/ir/tensorflow/ir.pb pi@raspberry:/home/pi/models
Replace the content of the ThermalCameraSnapshotCron we previously created with a logic that takes pictures at scheduled intervals and uses the model we have just trained to predict if there are people in the room or not, using the platypush MlCv plugin.
You can implement whichever logic you like in procedure.people_detected and procedure.no_people_detected. These procedures will only be invoked when there is a status change from the previous observation. For example, a simple logic to turn on or off your lights when someone enters/exits the room:
procedure.sync.people_detected: - action: light.hue.onprocedure.sync.no_people_detected: - action: light.hue.off
That’s your call! Feel free to experiment with more elaborate rules, for example to change the status of the music/video playing in the room when someone enters, using platypush media plugins. Or say a custom good morning text when you first enter the room in the morning. Or build your own surveillance system to track the presence of people when you’re not at home. Or enhance the model to detect also the number of people in the room, not only the presence. Or you can combine it with an optical flow sensor, distance sensor, laser range sensor or optical camera (platypush provides plugins for some of them) to build an even more robust system that also detects and tracks movements or proximity to the sensor, and so on. | [
{
"code": null,
"e": 250,
"s": 172,
"text": "An updated version of this story is available for free on the Platypush blog."
},
{
"code": null,
"e": 1034,
"s": 250,
"text": "Triggering events based on the presence of people has been the dream of many geeks and DIY automators for a... |
What I Learned From Analyzing and Visualizing Traffic Accidents Data | by Susan Li | Towards Data Science | The National Highway Traffic Safety Administration (NHTSA) has some really interesting data that they make available to public. I downloaded several datasets that contain information on fatal motor vehicle crashes and fatalities from 1994 to 2015. The purpose of this analysis is to explore and gain a better understanding of some of the factors that affect the likelihood of vehicle crashes.
The analysis and visualization are done in R language. R is awesome, as you will come to find out.
Load the libraries
I’ll be using the following libraries for the analysis and visualization. I don’t show the code for most of the data cleaning and analysis steps to keep the post concise, but as with all of my posts, the code can be found on Github.
library(XML)library(RCurl)library(rvest)library(dplyr)library(tidyr)library(ggplot2)library(ggthemes)library(reshape)library(treemap)
Traffic fatalities in the United States have been trending downwards. Notably, fatalities in 2014(less than 33,000) is far lower than the peak in 2005(more than 43,000).
ggplot(aes(x=Year, y=Val), data = df_long_total) + geom_line(size = 2.5, alpha = 0.7, color = "mediumseagreen", group=1) + geom_point(size = 0.5) + ggtitle('Total Number of Accidents and Fatalities in the US 1994 - 2015') + ylab('count') + xlab('Year') + theme_economist_white()
And the above figures did not take into account the ever-increasing number of cars on the road. Americans are driving more than ever before.
ggplot(aes(x=Year, y=Val), data = df_long_travel) + geom_line(size = 2.5, alpha = 0.7, color = "mediumseagreen", group=1) + geom_point(size = 0.5) + ggtitle('Total Vehicle Miles Traveled 1994 - 2015') + ylab('Billion Miles') + xlab('Year') + theme_economist_white()
2015 Traffic Fatalities by the State and Percent Change from 2014
state <- state[c('State', 2015, 2014, 'Percent.Change')]newdata <- state[order(-state$`2015`),]newdata
Texas led the U.S. with the most traffic fatalities in both 2014 and 2015.
Understandably, the states that have the fewest traffic fatalities are also among those have the fewest residents, including the District of Columbia, followed by Rhode Island and Vermont.
Nationwide, motor vehicle crash fatalities were higher for males than females every year (more than double).
ggplot(aes(x = year, y=count, fill=killed), data=kill_full) + geom_bar(stat = 'identity', position = position_dodge()) + xlab('Year') + ylab('Killed') + ggtitle('Number of Persons Killed in Traffic Accidents by Gender 1994 - 2015') + theme_economist_white()
The age group of 25 to 34 had the highest number of fatalities.
age_full$age <- ordered(age_full$age, levels = c('< 5', '5 -- 9', '10 -- 15', '16 -- 20', '21 -- 24', '25 -- 34', '35 -- 44', '45 -- 54', '55 -- 64', '65 -- 74', '> 74'))ggplot(aes(x = age, y=count), data =age_full) + geom_bar(stat = 'identity') + xlab('Age') + ylab('Number of Killed') + ggtitle('Fatalities Distribution by Age Group 1994 - 2015') + theme_economist_white()
From 2005 to 2015, fatalities increased in only two age groups; 55 to 64 and 65 to 74. Age groups of 16 to 20 and 35 to 44 had the highest decrease in fatalities.
ggplot(age_full, aes(x = year, y = count, colour = age)) + geom_line() + geom_point() + facet_wrap(~age) + xlab('Year') + ggtitle('Traffic Fatalities by Age 1994 - 2015') + theme(legend.position="none")
From this treemap, we see 3pm to 5:59pm and 6pm to 8:59pm had the most fatalities. Let’s dive it deeper.
treemap(kill_by_hour_group, index=c("hours","variable"), vSize="sum_hour", type="index", fontsize.labels=c(15,12), title='Fatalities by time of the day', fontcolor.labels=c("white","orange"), fontface.labels=c(2,1), bg.labels=c("transparent"), align.labels=list( c("center", "center"), c("right", "bottom")), overlap.labels=0.5, inflate.labels=F,)
The most accidents occurred between Midnight and 2:59am on Saturdays and Sundays. Let’s dive even deeper to find out why.
ggplot(aes(x = variable, y = sum_hour, fill = hours), data = kill_by_hour_group) + geom_bar(stat = 'identity', position = position_dodge()) + xlab('Hours') + ylab('Total Fatalities') + ggtitle('Fatalities Distribution by Time of the Day and Day of the week 1994-2015') + theme_economist_white()
Between Midnight and 2:59am on Saturdays and Sundays is the time many people leave the bars. How many times do we still have to say, don’t drink and drive?
ggplot(aes(x = year, y = count, fill = hour), data = pair_all) + geom_bar(stat = 'identity', position = position_dodge()) + xlab('Year') + ylab('Number of Fatalities') + ggtitle('Fatal Crashes caused by Alcohol-Impaired Driving, by Time of Day 1994-2015') + theme_economist_white()
The percentage of alcohol-impaired driving fatalities is actually flat over the past 10 years.
ggplot(aes(x = year, y = mean, color = bac), data = al_all_by_bac) + geom_jitter(alpha = 0.05) + geom_smooth(method = 'loess') + xlab('Year') + ylab('Percentage of Killed') + ggtitle('Fatalities and Blood Alcohol Concentration of Drivers 1994-2015') + theme_economist_white()
NHTSA provides a rich data source for information on traffic fatalities. There are hundreds of methods to analyze them and the best one really depends on the data, and the questions you are trying to answer. Our job is to tell a story backed-up by the data. What type of the vehicle is more likely to be involved in a crash? Where is the safest seat in a vehicle? So, come out with your own story, and let me know what you find in the data!
Data does not inspire people, stories do. | [
{
"code": null,
"e": 564,
"s": 171,
"text": "The National Highway Traffic Safety Administration (NHTSA) has some really interesting data that they make available to public. I downloaded several datasets that contain information on fatal motor vehicle crashes and fatalities from 1994 to 2015. The pur... |
Logic Gates in Python - GeeksforGeeks | 11 Apr, 2022
Logic gates are elementary building blocks for any digital circuits. It takes one or two inputs and produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are implemented using diodes or transistors. It can also be constructed using vacuum tubes, electromagnetic elements like optics, molecules, etc. In a computer, most of the electronic circuits are made up of logic gates. Logic gates are used to circuits that perform calculations, data storage, or show off object-oriented programming especially the power of inheritance.
There are seven basic logic gates defined are: AND gate, OR gate, NOT gate, NAND gate, NOR gate, XOR gate, an XNOR gate.
1. AND Gate The AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.
Python3
# Python3 program to illustrate# working of AND gate def AND (a, b): if a == 1 and b == 1: return True else: return False # Driver codeif __name__=='__main__': print(AND(1, 1)) print("+---------------+----------------+") print(" | AND Truth Table | Result |") print(" A = False, B = False | A AND B =",AND(False,False)," | ") print(" A = False, B = True | A AND B =",AND(False,True)," | ") print(" A = True, B = False | A AND B =",AND(True,False)," | ") print(" A = True, B = True | A AND B =",AND(True,True)," | ")
Output:
True
+---------------+----------------
| AND Truth Table | Result |
A = False, B = False | A AND B = False |
A = False, B = True | A AND B = False |
A = True, B = False | A AND B = False |
A = True, B = True | A AND B = True |
2. NAND Gate The NAND gate (negated AND) gives an output of 0 if both inputs are 1, it gives 1 otherwise.
Python3
# Python3 program to illustrate# working of NAND gate def NAND (a, b): if a == 1 and b == 1: return False else: return True # Driver codeif __name__=='__main__': print(NAND(1, 0)) print("+---------------+----------------+") print(" | NAND Truth Table | Result |") print(" A = False, B = False | A AND B =",NAND(False,False)," | ") print(" A = False, B = True | A AND B =",NAND(False,True)," | ") print(" A = True, B = False | A AND B =",NAND(True,False)," | ") print(" A = True, B = True | A AND B =",NAND(True,True)," | ")
Output:
True
+---------------+----------------
| NAND Truth Table | Result |
A = False, B = False | A AND B = True |
A = False, B = True | A AND B = True |
A = True, B = False | A AND B = True |
A = True, B = True | A AND B = False |
3. OR Gate The OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.
Python3
# Python3 program to illustrate# working of OR gate def OR(a, b): if a == 1 or b ==1: return True else: return False # Driver codeif __name__=='__main__': print(OR(0, 0)) print("+---------------+----------------+") print(" | OR Truth Table | Result |") print(" A = False, B = False | A OR B =",OR(False,False)," | ") print(" A = False, B = True | A OR B =",OR(False,True)," | ") print(" A = True, B = False | A OR B =",OR(True,False)," | ") print(" A = True, B = True | A OR B =",OR(True,True)," | ")
Output:
False
+---------------+----------------+
| OR Truth Table | Result |
A = False, B = False | A OR B = False |
A = False, B = True | A OR B = True |
A = True, B = False | A OR B = True |
A = True, B = True | A OR B = True |
4. XOR Gate The XOR gate gives an output of 1 if either of the inputs is different, it gives 0 if they are the same.
Python3
# Python3 program to illustrate# working of Xor gate def XOR (a, b): if a != b: return 1 else: return 0 # Driver codeif __name__=='__main__': print(XOR(5, 5)) print("+---------------+----------------+") print(" | XOR Truth Table | Result |") print(" A = False, B = False | A XOR B =",XOR(False,False)," | ") print(" A = False, B = True | A XOR B =",XOR(False,True)," | ") print(" A = True, B = False | A XOR B =",XOR(True,False)," | ") print(" A = True, B = True | A XOR B =",XOR(True,True)," | ")
Output:
0
+---------------+----------------+
| XOR Truth Table | Result |
A = False, B = False | A XOR B = 0 |
A = False, B = True | A XOR B = 1 |
A = True, B = False | A XOR B = 1 |
A = True, B = True | A XOR B = 0 |
5. NOT Gate It acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.
Python3
# Python3 program to illustrate# working of Not gate def NOT(a): return not a# Driver codeif __name__=='__main__': print(NOT(0)) print("+---------------+----------------+") print(" | NOT Truth Table | Result |") print(" A = False | A NOT =",NOT(False)," | ") print(" A = True, | A NOT =",NOT(True)," | ")
Output:
1
+---------------+----------------+
| NOT Truth Table | Result |
A = False | A NOT = 1 |
A = True, | A NOT = 0 |
6. NOR Gate The NOR gate (negated OR) gives an output of 1 if both inputs are 0, it gives 0 otherwise.
Python3
# Python3 program to illustrate# working of NOR gate def NOR(a, b): if(a == 0) and (b == 0): return 1 elif(a == 0) and (b == 1): return 0 elif(a == 1) and (b == 0): return 0 elif(a == 1) and (b == 1): return 0 # Driver codeif __name__=='__main__': print(NOR(0, 0)) print("+---------------+----------------+") print(" | NOR Truth Table | Result |") print(" A = False, B = False | A NOR B =",NOR(False,False)," | ") print(" A = False, B = True | A NOR B =",NOR(False,True)," | ") print(" A = True, B = False | A NOR B =",NOR(True,False)," | ") print(" A = True, B = True | A NOR B =",NOR(True,True)," | ")
Output:
1
+---------------+----------------+
| NOR Truth Table | Result |
A = False, B = False | A NOR B = 1 |
A = False, B = True | A NOR B = 0 |
A = True, B = False | A NOR B = 0 |
A = True, B = True | A NOR B = 0 |
7. XNOR Gate The XNOR gate (negated XOR) gives an output of 1 both inputs are same and 0 if both are different.
Python3
# Python3 program to illustrate# working of Not gate def XNOR(a,b): if(a == b): return 1 else: return 0# Driver codeif __name__=='__main__': print(XNOR(1,1)) print("+---------------+----------------+") print(" | XNOR Truth Table | Result |") print(" A = False, B = False | A XNOR B =",XNOR(False,False)," | ") print(" A = False, B = True | A XNOR B =",XNOR(False,True)," | ") print(" A = True, B = False | A XNOR B =",XNOR(True,False)," | ") print(" A = True, B = True | A XNOR B =",XNOR(True,True)," | ")
Output:
1
+---------------+----------------+
| XNOR Truth Table | Result |
A = False, B = False | A XNOR B = 1 |
A = False, B = True | A XNOR B = 0 |
A = True, B = False | A XNOR B = 0 |
A = True, B = True | A XNOR B = 1 |
Akanksha_Rai
boyc30880
kumarv456
shashankshandilya8904
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
C++ Classes and Objects | [
{
"code": null,
"e": 24530,
"s": 24502,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 25091,
"s": 24530,
"text": "Logic gates are elementary building blocks for any digital circuits. It takes one or two inputs and produces output based on those inputs. Outputs may be high (1) ... |
How to convert hex string into int in Python? | Hex strings generally have a "0x" prefix. If you have this prefix and a valid string, you can use int(string, 0) to get the integer. The 0 is provided to tell the function to automatically interpret the base from prefix. For example:
>>> int("0xfe43", 0)
65091
If you don't have a "0x" prefix, you can pass 16 instead of 0 to specify the base of the number. For example:
>>> int("fe43", 16)
65091 | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "Hex strings generally have a \"0x\" prefix. If you have this prefix and a valid string, you can use int(string, 0) to get the integer. The 0 is provided to tell the function to automatically interpret the base from prefix. For example:"
},
{
"co... |
The Kalman Filter and External Control Inputs | by Ben Ogorek | Towards Data Science | In this article, you will
Use the statsmodels Python module to implement a Kalman Filter model with external control inputs,
Use Maximum Likelihood to estimate unknown parameters in the Kalman Filter model matrices,
See how cumulative impact can be modeled via the Kalman Filter in the context of the fitness-fatigue model of athletic performance.
The following is a specification of the Kalman Filter model with external “control” input B u_t:
where q_t ∼ N(0, Q) and r_t ∼ N(0, R). The model matrices A, B, H, Q, and R may contain unknown parameters and are often allowed to vary through time. The external “control-vector” input, u_t, must be known for all time points up to the present and — if the task requires predicting multiple time steps ahead — the future as well.
In many forecasting contexts, the external control term is unused. Standard time series models, where the internal system dynamics are the only forces at play (e.g., ARIMA), do not need them. Consequently, the lack of an explicit control specification mechanism in statsmodels is no surprise. Fortunately, statsmodels does provide an interface to the state intercept that is sufficient to incorporate external control inputs.
Take a moment to familiarize yourself with the statsmodels statespace representation, which uses slightly different notation for the state equation than presented at the beginning of this article:
The “state_intercept” c_t, which was not included in our specification, is zero by default in statsmodels. The description reads “c : state_intercept (k_states x nobs)” meaning that the user is free to specify a different value for the state intercept at every time point. (This is true for all statsmodels Kalman Filter model matrices.) But set
for t=1...T, and we have a Kalman Filter model with control inputs.
The fitness-fatigue model from Modeling Cumulative Impact Part I is:
where p_t is (athletic) performance and w_t is training “dose” (time-weighted training intensity) at time t. In my previous articles exploring this model, convolutions of training history with other functions has been the mechanism of representing the cumulative impact of the training sessions. This article will do something different by keeping a system state. In order to do that, we must put the fitness-fatigue model in state-space form, with training dose as the external control input.
In the above equation, the first convolution sum represents athletic fitness, which I’ll now call h_t. Below is the result of lagging one time step:
Separating the final term in the convolution sum defining h_t, we arrive at the recursion:
This argument proceeds in the same manner for fatigue’s convolution sum, called g_t henceforth, and the recursive relationship for both fitness and fatigue can be expressed in the following “state-space form”:
We can continue using matrices to express the second “measurement” stage of the model with:
where r_t ~ N(0, σ2). The control input is lagged by one time period, which we’ll have to account for, but otherwise we have a typical state-space formulation of the fitness-fatigue model with exogenous control inputs. Combined with the measurement model of performance given the current state of fitness and fatigue, the Kalman Filter toolkit (state estimation, easy imputation, and likelihood evaluation) is at our disposal.
This section will use simulated data that can be reproduced from the R gist that was used in Modeling Cumulative Impact Part II, which is also available to the reader as a csv file. To run the code below, change the file path in the following Python code block:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport statsmodels as smfrom statsmodels.tsa.statespace.mlemodel import MLEModeltrain_df = pd.read_csv("<your location>/train_df.csv")train_df.head()
This block loads the required dependencies and prints a few lines of our input data set train_df:
day day_of_week period w perf0 1 0 build-up 10 489.1973631 2 1 build-up 40 500.5453122 3 2 build-up 42 479.8866483 4 3 build-up 31 474.2268654 5 4 build-up 46 459.322820
To create a Kalman Filter model in statsmodels, we must extend the MLEModel base class (from the mlemodel module).
class FitnessFatigue(MLEModel): start_params = [500, .1, .3, 60, 15, 10] param_names = ['p_0', 'k_g', 'k_h', 'tau_g', 'tau_h', 'sigma'] def __init__(self, p, w_lag1): super().__init__(endog=p, k_states=2, exog=w_lag1) self.initialize_approximate_diffuse() def update(self, params, **kwargs): params = super().update(params, **kwargs) self['obs_intercept', 0, 0] = params[0] # state space model ------ self['transition'] = ( np.array([[np.exp(-1.0 / params[3]), 0], [0, np.exp(-1.0 / params[4])]]) ) self['state_intercept'] = ( np.array([[np.exp(-1.0 / params[3])], [np.exp(-1.0 / params[4])]]) * self.exog ) # measurement model self['design', 0, 0] = params[1] self['design', 0, 1] = params[2] self['obs_cov', 0, 0] = params[5] ** 2
A few things to note about the class above:
We had to put in starting values in start_params
We have to specify an __init__ method that will accept data. In this case it must accept both performance measurements and training (i.e., control) data.
Note the creation of the lag training variable within __init__. The fitness-fatigue model specifically specifies a one time period lag before a training event can impact fitness or fatigue.
We’re able to avoid specifying the selection matrix which premultiplies the state error term in the statsmodels representation. That defaults to a matrix of zeros that we’d typically be in trouble for not setting, but the fitness-fatigue model, when directly translated to state space form, has no state error term.
Next, instantiate the object with the data and estimate the unknown parameters using maximum likelihood. Note that we do need to lag the training input in order to match the model’s specification (I’ve gone back and forth on this during the time the article’s been published).
train_df['lag_w'] = train_df['w'].shift(1)train_df = train_df.iloc[1:]ffm_kf = FitnessFatigue(train_df.perf, train_df.lag_w)mle_results = ffm_kf.fit(method = 'bfgs', maxiter = 1000)mle_results.summary()
The last command produces the following output (spacing has been modified):
The output shows that the Kalman Filter has done a good job recovering parameter values used in the simulation. Standard errors, which required a custom nonlinear approximation in Modeling Cumulative Impact Part III, are now available “out of the box.” On the other hand, the maximum likelihood procedure did require some tuning in this situation; increasing the minimum number of iterations and choosing the BFGS method led to a stable fit.
The reader is encouraged to repeat the exercise above with the “approximate diffuse” initialization replaced by the known initialization (currently commented out). Unlike in The Kalman Filter and Maximum Likelihood, the results using the known initialization are somewhat different, especially the standard errors. When the known initialization is used, the standard error estimates from the Kalman Filter are similar to those estimated using the nonlinear approximation. With the approximate diffuse initialization, they are considerably larger for some parameters (especially the “time constants” in the exponentials).
The Kalman Filter gives us access to both filtered state estimates, which use only the data available up to a particular time point, and smoothed state estimates, which incorporate all available data into each time point’s state estimate. Below we’ll visualize the filtered state estimates, which naturally experience a rough start:
fig = plt.figure(figsize = (12, 8))plt.rcParams.update({'font.size': 18})plt.plot(mle_results.filtered_state[0, :], color='green', label='fitness')plt.plot(mle_results.filtered_state[1, :], color='red', label='fatigue')plt.title("Filtered estimates of state vector (Fitness and " + "Fatigue) over time")plt.xlabel('Time')plt.ylabel('Filtered state estimate')plt.legend()plt.show()
Given that the true fitness state is initialized at 0 and gradually travels higher, the first few filtered state estimates are off by a lot and explain why likelihood_burn was set to 15. Replacing filtered_state with smoothed_state in the graphing code shows a picture that is much more similar to those in Modeling Cumulative Impact Part I.
Before writing this article, I thought the only way to get a Kalman Filter with control inputs was to pay for MATLAB or SAS/ETS . And while statsmodels could make the specification a little more straightforward, adding in a control input to its Kalman Filter routines is still easily accomplished using the time-varying state intercept.
Subclass derivation for defining a model, like that used in statsmodels, is sleek but makes debugging less transparent. (There were hours where these examples were not working.) Remember that the resulting objects contain their model matrices; printing them out is a good way to debug! Don’t forget about the “selection matrix” which multiplies the state error in statsmodels — it defaults to zero. We didn’t need it here because the fitness-fatigue model doesn’t specify state error, but it can lead to the frustrating debugging scenario where code changes aren’t affecting the output.
Though the lack of a state error term made the current task simpler due to statsmodels defaults, the ability to add a state error term is an advantage of the Kalman Filter over the original fitness-fatigue model. It’s easy to imagine things besides training that affect the latent fitness and fatigue, including sleep quality and nutrition. Adding a state error term to the original fitness-fatigue model is another variation to be explored.
Unlike in The Kalman Filter and Maximum Likelihood, the “approximate diffuse” initialization led to different results than a known initialization of the state. In that article, perhaps the stationary ARMA(1, 2) model was too much of a softball, and that uncertainty about the initial state would really only matter in a non-stationary situation without the mean to fall back on. Nevertheless, it makes me curious about how different the “exact diffuse” initialization would have performed had it been implemented in statsmodels.
The Kalman Filter is a very powerful tool for time series analysis and modeling. Not only is it able to calculate difficult likelihoods of classical time series models, but it can handle non-stationary models with exogenous control inputs and even guide the next space shuttle to the moon. As data scientists, we’re lucky to have a free open-source implementation of the Kalman Filter, one that is sufficiently flexible for both statistical and engineering purposes, in statsmodels. | [
{
"code": null,
"e": 198,
"s": 172,
"text": "In this article, you will"
},
{
"code": null,
"e": 297,
"s": 198,
"text": "Use the statsmodels Python module to implement a Kalman Filter model with external control inputs,"
},
{
"code": null,
"e": 388,
"s": 297,
"... |
PyQtGraph – Getting Tool Tip of Scatter Plot Graph - GeeksforGeeks | 22 Nov, 2021
In this article, we will see how we can get tool tip of the scatter plot graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). A scatter plot (aka scatter chart, scatter graph) uses dots to represent values for two different numeric variables. It is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. The tooltip or hint is a common graphical user interface element displayed as an informational text box when hovering over an item. The user hovers the pointer over an item, without clicking it, and a tooltip may appear as a small “hover box” with information about the item being hovered over. t can be set with the help of setToolTip method. We can create a plot window and create a scatter plot graph on it with the help of commands given below.
# creating a pyqtgraph plot window
plt = pg.plot()
# creating a scatter plot graph of size = 10
scatter = pg.ScatterPlotItem(size=10)
In order to do this we use toolTip method with the scatter plot graph objectSyntax : scatter.toolTip()Argument : It takes no argumentReturn : It returns string
Below is the implementation.
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel("Geeksforgeeks Scatter Plot") # making label do word wrap label.setWordWrap(True) # creating a plot window plot = pg.plot() # number of points n = 300 # creating a scatter plot item # of size = 10 # using brush to enlarge the of green color scatter = pg.ScatterPlotItem( size=10, brush=pg.mkBrush(30, 255, 35, 255)) # data for x-axis x_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # data for y-axis y_data = [5, 4, 6, 4, 3, 5, 6, 6, 7, 8] # setting data to the scatter plot scatter.setData(x_data, y_data) # add item to plot window # adding scatter plot item to the plot window plot.addItem(scatter) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # setting tool tip to the scatter plot scatter.setToolTip("This is tip") # getting tool tip of scatter plot value = scatter.toolTip() # setting text to the value label.setText("Tool tip : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
anikakapoor
Python-gui
Python-PyQtGraph
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() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 25457,
"s": 24292,
"text": "In this article, we will see how we can get tool tip of the scatter plot graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Pyth... |
8085 program to find the sum of first n natural numbers - GeeksforGeeks | 24 May, 2019
Problem – Write an assembly language program for calculating the sum of first n natural numbers using 8085 microprocessor.
Example –
Input : 04H
Output : 0AH
as 01+02+03+04 = 10 in decimal => 0AH
The formula for calculating the sum of first n natural numbers is .
Algorithm –
With n as the input, increment it to obtain n+1.Multiply n with n+1.Divide the product obtained by 2.
With n as the input, increment it to obtain n+1.
Multiply n with n+1.
Divide the product obtained by 2.
In 8085 microprocessor, no direct instruction exists to multiply two numbers, so multiplication is done by repeated addition as 4×5 is equivalent to 4+4+4+4+4 (i.e., 5 times).Input: 04HAdd 04H 5 timesProduct: 14H(2010)
Similarly, in 8085 microprocessor, no direct instruction exists to divide two numbers, so division is done by repeated subtraction.Input: 14HKeep subtracting 2 from the input till it reduces to 0.Since subtraction has to be performed 1010 times before 14H becomes 0, the quotient is 1010 => 0AH.
Steps –
Load the data from the memory location (201BH, arbitrary choice) into the accumulatorMove this data into BIncrement the value in the accumulator by one and move it to the register CInitialise the accumulator with 0Multiplication: Keep adding B to accumulator. The number of times B has to be added is equal to the value of CInitialise B with 00H. B will store the quotient of the divisionInitialise C with 02H. This is the divisor for the divisionDivision: Keep subtracting C from A till A becomes 0. For each subtraction, increment B by oneThe final answer is in B. Move it to A. Then store the value of A in 201CH (arbitrary choice again)
Load the data from the memory location (201BH, arbitrary choice) into the accumulator
Move this data into B
Increment the value in the accumulator by one and move it to the register C
Initialise the accumulator with 0
Multiplication: Keep adding B to accumulator. The number of times B has to be added is equal to the value of C
Initialise B with 00H. B will store the quotient of the division
Initialise C with 02H. This is the divisor for the division
Division: Keep subtracting C from A till A becomes 0. For each subtraction, increment B by one
The final answer is in B. Move it to A. Then store the value of A in 201CH (arbitrary choice again)
201CH contains the final answer.
Store the value of n in 201BH. The sum can be found at 201CH.
nidhi_biet
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Addressing modes in 8085 microprocessor
Memory Hierarchy Design and its Characteristics
Computer Organization | Von Neumann architecture
Computer Organization | RISC and CISC
Interrupts
Architecture of 8085 microprocessor
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Difference between Von Neumann and Harvard Architecture | [
{
"code": null,
"e": 25088,
"s": 25060,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 25211,
"s": 25088,
"text": "Problem – Write an assembly language program for calculating the sum of first n natural numbers using 8085 microprocessor."
},
{
"code": null,
"e": 252... |
How to clear all values from the Hash table in PowerShell? | Hash table in the PowerShell session is created temporarily. It is like a variable, when the session is closed, hash table is deleted automatically. If you want to delete all the values from the hash table at once but retaining the hash table variable, you need to use the Clear() method.
We have the hash table below created already.
$htable = [Ordered]@{EmpName="Charlie";City="New York";EmpID="001"}
PS C:\WINDOWS\system32> $htable
Name Value
---- -----
EmpName Charlie
City New York
EmpID 001
To clear the above hashtable,
$htable.Clear()
If you check the hash table data, it won’t display anything now but it is still the OrderedDictionary and not converted into any variable data type. | [
{
"code": null,
"e": 1351,
"s": 1062,
"text": "Hash table in the PowerShell session is created temporarily. It is like a variable, when the session is closed, hash table is deleted automatically. If you want to delete all the values from the hash table at once but retaining the hash table variable, ... |
Python Data Visualization with Matplotlib — Part 1 | Rizky Maulana N | Towards Data Science | Data visualization aims to present the data into a more straightforward representation, such as scatter plot, density plot, bar chart, etc. It is also useful to give readers or analysts a global picture of their data. By visualizing your data, you can detect potential outliers. In Python, you can use various modules or libraries to visualize data. One of the mainstream modules is Matplotlib. You can visualize data using Matplotlib in various plotting styles. But, Matplotlib can not show you a dynamics plot. If you want to create a tremendous dynamic plot, you can use Dash from plotly (I hope to finish a story about a complete tutorial with Dash next month).
This story will guide you on how to visualize data with Matplotlib in a various way. 90 examples maybe can inspire you to create a plot from different points of view. It is not the most completed tutorials in data visualization with Matplotlib, but I believe that this story can accommodate many people’s needs, reach many disciples to be applied.
As I mentioned before, I will guide you through creating 90 various plot examples. The examples are distributed in 11 different style plots: scatter plot, line plot, histogram 1D, 2D, marginal plot, bar chart, box plot, violin plot, pie chart, polar chart, geographic projection, 3D plot, and contour plot. You can see Figure 1 to have a general idea of this story.
In this story, I try to focus on creating and customizing various plots. So, I assume you have known several techniques outside it, e.g., creating multiple subplots and customizing colormaps in Matplotlib. If you have not known it, I will give you some links to understand it.
At the beginning of writing this story, I plan to write only 1 story. But, I think I need to divide it into several parts because of the reading time. If I write it all in one story, it will cost more than 40 minutes. I guess you will be bored to read it all just in one story :). So, I divide it into 2 or 3 parts. I will limit the reading time to less than 30 minutes. This is the first part. Let’s start it.
To install Matplotlib, you can install it via pip with this code
pip install matplotlib
or via conda
conda install -c anaconda matplotlib
When I write this story, I installed Matplotlib version 3.3.2. You can check it by writing this code.
pip show matplotlib
If you want to check it in Jupyter Notebook (hereafter, Jupyter), you can add ! before pip, as shown in Figure 2.
If you want to upgrade your Matplotlib version, you can use the following code
pip install matplotlib --upgrade
Again, you can add ! before pip to upgrade Matplotlib via Jupyter.
If you have installed a different Matplotlib version with Matplotlib I used in this story, maybe you will face different results. Just write the issues you meet in the response columns below. I recommend you to save this story. So, you can continue your reading if you have limited time.
Before we move on the first section, I need to inform you that I have customized my Matplotlib plotting style such as using LaTeX font as default, changing the font size and family, changing xtick and ytick direction and size, and adding minor tick in the x-axis and y-axis. To use LaTeX font as your default font in Matplotlib, you can use this code
plt.rcParams['text.usetex'] = True
If you face some errors, you need to read the following story. I have explained the detailed procedures to deal with LaTeX font in Matplotlib
towardsdatascience.com
To customize the other parameters (font size, font family, and tick params) you just write this code at the beginning of your code
plt.rcParams['font.size'] = 15plt.rcParams['font.family'] = "serif"tdir = 'in'major = 5.0minor = 3.0plt.rcParams['xtick.direction'] = tdirplt.rcParams['ytick.direction'] = tdirplt.rcParams['xtick.major.size'] = majorplt.rcParams['xtick.minor.size'] = minorplt.rcParams['ytick.major.size'] = majorplt.rcParams['ytick.minor.size'] = minor
If you need to understand it in more detail, you can visit this story
towardsdatascience.com
In this section, there are eight examples of scatter plots. Before creating a scatter plot, I need to generate mock data using this code
import numpy as npimport matplotlib.pyplot as pltN = 50x = np.linspace(0., 10., N)y = np.sin(x)**2 + np.cos(x)
Variable x is an array of 50 data, from 0 to 10. Variable y is the summation of the square of sin(x) and cos(x). I want to visualize variable x in the x-axis, and variable y in the y-axis in the form of a scatter plot using this code
plt.figure()plt.scatter(x, y)
It is so simple. The code will show you a result, as shown in Figure 3.
To make it more beautiful, you can reduce the size of each data and give the label using this code
plt.scatter(x, y, s = 15, label = r'$y = sin^2(x) + cos(x)$')
To change the color, you need to add this argument in scatter syntax
color = 'r' # r means red
If you want to make the axis scale is at the same scale, you can use this code
plt.axis('equal')
To create an axis label for the x- and y-axis, you can add the following code
plt.xlabel(r'$x$ (rad)')plt.ylabel(r'$y$')
You have labeled your scatter plot, but you have not shown it as a legend. To show it, you can use this code
plt.legend()
To save your plot, you can use save figure syntax as shown in the following code
plt.savefig('scatter2.png', dpi = 300, bbox_inches = 'tight', facecolor='w')
The code above will save your plot with the name of scatter2.png, resolution of 300 dots per inch, tight bbox, and white background. It is okay if you omitted bbox_inches and face color arguments, but maybe you will get a different result. Just try it.
Here is the full code
The code will create a scatter plot, as shown in Figure 4.
You can see that the tick direction in the x-axis and y-axis inside the axes, and the font used is in LaTeX format. If you want to change the figure size, you can add figure size arguments inside plt.figure()
plt.figure(figsize=(7, 4.5))
Change marker style
To change the marker style, for example, I want to change from dot to cross, you can add this argument in plt.scatter
marker = 'x'
Figure 5 is the result if you apply the code above
There are tons of marker styles you can use in Matplotlib. You can check it at the following link.
matplotlib.org
If you have read the documentation above, you can realize that you can use the alphabet as your marker style. I will show you the example of applying the alphabet as a marker, as shown in Figure 6.
To generate Figure 6, I create a different function for the parameter in the x- and y-axis. Here is the code to generate it
np.random.seed(100)N = 50randx = np.random.random(N) * 100randy = np.random.random(N) * 100
To visualize variable randx and randy, I run this code
plt.figure(figsize=(7, 6))plt.scatter(randx, randy, marker=r'$\beta$', s = 150, color = 'darkorange')plt.axis('equal')plt.xlabel('randx')plt.ylabel('randy')plt.tight_layout()
I use the Greek symbol beta as my marker style. You can change it with a different alphabet, such as a, B, C, d, or 1, 2, 3, etc.
Customizing the size for each data
This subsection will show you how to create a scatter plot with different sizes for each data, as shown in Figure 7.
To create it, I generate a random position for variable randx and randy, from 0 to 100 using this code
np.random.seed(100)N = 30randx = np.random.random(N) * 100randy = np.random.random(N) * 100
For your reminder, I generate random data using Numpy. In generating a random number, Numpy only generates it in a range of 0 to 1. As I know, it is a convention in generating a random number (not only in Numpy), just from 0 to 1. To modify it, you can multiply it by 100. So, you will get a random number in the range of 0 to 100.
After that, I generate a random integer size for each data from 50 to 200, using this code
size = np.random.randint(50, 200, size=N)
To visualize it, you just add the argument of the size that will be applied in each data, using this code
plt.scatter(randx, randy, s = size, color = 'darkorange')
The additional syntax in creating Figure 7 is inserting the minor tick in the x- and y-axis. To insert it, you need to import submodule MultipleLocator using this code
from matplotlib.ticker import MultipleLocator
After that, you can add this syntax to insert minor axis
ax = plt.gca()ax.xaxis.set_minor_locator(MultipleLocator(10))ax.yaxis.set_minor_locator(MultipleLocator(10))
Here is the full code to generate Figure 7.
Color-coded scatter plot
You can change the color using colormaps. It means that data with different sizes will be color-coded by a different color. You can add color arguments in plt.scatter() like this
c = size
To embed the colorbar, you can use this code
plt.colorbar()
You will get a plot, as shown in Figure 8.
Here is the full code to generate Figure 8.
Customizing the colormaps
You can change the colormaps using this argument
cmap = 'inferno'
You can check this link to understand all of the colormaps provided by Matplotlib
matplotlib.org
In this tutorial, I have created my own colormaps by combining colormaps Blues and Oranges, as shown in Figure 9.
To combine it, I use this code
from matplotlib import cmfrom matplotlib.colors import ListedColormap, LinearSegmentedColormaptop = cm.get_cmap('Oranges_r', 128)bottom = cm.get_cmap('Blues', 128)newcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))orange_blue = ListedColormap(newcolors, name='OrangeBlue')
I create my own colormaps named orange_blue. To understand how to create and customize your own colormaps in Matplotlib, you can read it in the following link
towardsdatascience.com
To apply it, I just change color arguments c = orange_blue. You can check the result in Figure 11.
Here is the full code to generate Figure 11.
This the end of this section, creating a scatter plot with Matplotlib. If you face some errors, you can leave a comment in the response columns.
To make a line plot in Matplotlib, I will generate mock data using this code
N = 50x = np.linspace(0., 10., N)y = np.sin(x)**2 + np.cos(x)
To visualize variable x and y in the form of a line plot, you need to use the following simple code
plt.plot(x, y)
The code above will generate a figure, as shown in Figure 12.
Customizing line styles
You can change the line style of the line plot in Matplotlib using this argument
linestyle = '-'
The argument above should be inserted in plt.plot() syntax. In this tutorial, I will show you four different line style; they are
['-', '--', '-.', ':']
To generate it automatically, I use looping to make it simple. Here is the full code
I will distribute the 4 different line styles in one figure. It means that I need to create 4 axes in a figure. In Matplotlib, you can generate it by customizing subplots using GridSpec(), subplot(), and add_subplot(). In this session, I use GridSpec() syntax. I create 4 axes (2 rows and 2 columns) with width and height space equals 0.25 (see lines 6 to 12). As I mentioned at the beginning, I will only focus on customizing plots. If you need more explanation in customizing subplots in Matplotlib, you can visit this link
towardsdatascience.com
If you run the code above, it will create a figure, as shown in Figure 13.
The code will simply generate 4 different line styles, with labels and annotations for each line style. Matplotlib provides many line styles you can use. You can choose your favorite line styles via this link
matplotlib.org
Customizing line width
To customize the line width for your line plot, you can use this argument
lw = 2.0
I present you with 4 different line width, as shown in Figure 14.
I use a similar technique to create Figure 14. Here is the full code.
Creating mark every
This subsection will guide you to create a mark every feature. To understand it, I will show the result first, as shown in Figure 15.
In Figure 15, I create a circle mark for every 5 data. You can create it with this argument
'o' # shape for each 5 datamarkevery = 5 # mark every ms = 7 # size of the circle in mark every
Here is the full code
You need to place the argument ‘o’ in the third position.
Changing the line color
To change the line color, you can apply a similar concept to change the scatter color, as shown in the following code
color = 'royalblue'
I want to show you how to generate 4 different colors and 4 different marks using looping, as shown in Figure 16.
You can reproduce Figure 16 with this code
4 different colors I used are colorblind-friendly. I get it from this link. To understand how to create colorblind-friendly palettes using that link, you read this story.
Inserting error in line plot
To demonstrate an error bar in line plot, I need to generate the error, using this code
np.random.seed(100)noise_x = np.random.random(N) * .2 + .1noise_y = np.random.random(N) * .7 + .4
The code will generate random numbers from 0.1 to 0.3 for noise_x and from 0.3 to 0.7 for noise_y. To insert the error bar for the y-axis, you can use this code
plt.errorbar(x, y, yerr = noise_y)
Figure 17 is an example of error bar in line plot.
You can create Figure 17 with this code.
To insert error bar in the x-axis, you can use this argument
xerr = noise_x
You can see the example of inserting an error bar in the x- and y-axis in Figure 18.
You can use this code to reproduce Figure 18.
If you want to visualize your data without a line plot, only the error bar, you can use this argument
fmt = 'o' # shape of the data pointcolor = 'r' # color of the data pointecolor ='k' # color of the error bar
Here is the full code
The code above will show a plot, as shown in Figure 19.
Filling the error area
To visualize the error, you can also use this code
plt.fill_between(x, y + noise, y - noise, alpha = .5)
The fill_between arguments are data for the x-axis, upper limit, and lower limit for the filled area. In the code above, it is represented by y + noise and y-noise. You need to lower the transparency of the filled area. Here is the full code
If you run the code above, you will get a result, as shown in Figure 20.
Inserting the vertical and horizontal lines
You can insert a horizontal and a vertical line with this code
plt.hlines(0, xmin = 0, xmax = 10)plt.vlines(2, ymin = -3, ymax = 3)
You need to define horizontal lines in the first argument, followed by the horizontal line’s starting point and ending point. For the vertical line, it has similar arguments.
Figure 21 is an example of inserting a horizontal and vertical line.
To generate Figure 21, you can use this code
In Figure 21, the legend is placed outside the axes. You can realize it in line 17.
Filling between two vertical lines
This subsection will guide you to make a filled area between two vertical lines, as shown in Figure 22.
To reproduce Figure 22, you can use this code
You need to know the important thing in creating a filled area in Matplotlib, you need to set a suitable y-axis limit.
This section will explain how to make a histogram in 1D and 2D. I will tell you about the 1D histogram first. Before visualizing a 1D histogram, I will make a mock data, a Normal distributed random number, using this code.
N = 1000np.random.seed(10021)x = np.random.randn(N) * 2 + 15
In default, Numpy will generate a normal distributed random number with mean/median (mu) equals 0 and variance (sigma) equals 1. In the code above, I change mu to 15 and sigma to 2. To visualize variable x in 1D histogram, you can use this code
plt.hist(x)
The code will show a figure, as shown in Figure 23.
Matplotlib will generate 10 bins for a 1D histogram as the default setting. If you want to change the bins number, you can use this argument.
bins = 40
The argument will generate a 1D histogram with 40 bins, as shown in Figure 24.
Here is the full code to create Figure 24.
N = 1000np.random.seed(10021)x = np.random.randn(N) * 2 + 15plt.figure(figsize=(9, 6))plt.hist(x, bins = 40, label = r'$\mu = 15, \sigma = 2$')plt.legend()
You can also limit the range of histogram using this argument
range = (12, 18)
The argument will let histogram only shows the data from 12 to 18, as shown in Figure 25.
You can reproduce Figure 25 with this code.
I also change the histogram color using a color argument.
Horizontal histogram
You can create a horizontal histogram, as shown in Figure 26.
You need to use this argument to create a horizontal histogram
orientation = 'horizontal'
To create Figure 25, you can run this code.
If you want to show the border from each histogram, you can use this argument.
edgecolor = 'k'
I want to make the histogram border in black color, as shown in Figure 26.
To generate Figure 26, you can use this full code.
Overlapping histogram
You can show many histograms in a single figure, as shown in Figure 27.
In Figure 27, I generate three normal distributions, with different mu and sigma. You can reproduce Figure 27 with this code.
You can make it prettier by changing the histograms’ transparency, as shown in Figure 28.
If you need the full code to create Figure 28, you can read the code below. The difference with the previous code is just in the alpha argument.
You can also generate Figure 28 using a looping, as shown in this code
N = 1000mu1 = 5mu2 = 10mu3 = 15sigma1 = 5sigma2 = 3sigma3 = 2x1 = np.random.randn(N) * sigma1 + mu1x2 = np.random.randn(N) * sigma2 + mu2x3 = np.random.randn(N) * sigma3 + mu3mu = np.array([mu1, mu2, mu3])sigma = np.array([sigma1, sigma2, sigma3])x = np.array([x1, x2, x3])colors = ['royalblue', 'tomato', 'gray']plt.figure(figsize=(9, 6))for i in range(len(x)): plt.hist(x[i], bins = 30, color = colors[i], label = r'$\mu = $ ' + str(mu[i]) + ', $\sigma = $ ' + str(sigma[i]), alpha = .7)plt.legend()
After see the code above, maybe you have an imagination to create a lot of histogram (more than 3) in a single figure. I will accommodate it :D. Here is the code to create and visualize 10 histograms in a single figure cleanly.
If you run the code above, you will get a result, as shown in Figure 29.
You can generate many colors merely using this link. After generating the palettes, just copy and paste it into your code. The detailed procedure of generating the palettes is provided here.
2D histogram
You can generate a 2D histogram with Matplotlib, as shown in Figure 30.
To create Figure 30, I need to generate 2 normal distribution with this code.
N = 1_000np.random.seed(100)x = np.random.randn(N)y = np.random.randn(N)
To visualize variable x and y in the 2D histogram, you can use this code.
plt.hist2d(x, y)
As in the 1D histogram, Matplotlib will generate 10 bins as the default setting for the 2D histogram. To change it, you can apply the same argument as in the 1D histogram, as shown in the code below.
bins = (25, 25)
You can see the modified bins number of the 2D histogram in Figure 31.
You also can change the colormaps of your 2D histogram using this argument
cmap = orange_blue
I want to change the colormaps from Viridis (default colormaps from Matplotlib) to my own colormaps named orange_blue. I have explained how to create your own colormaps in the previous section, or you can read it here.
Here is the full code for modifying the colormaps used in the 2D histogram.
If you run the code above, it will create a figure, as shown in Figure 32.
You can limit the range of counts for each (change the limit of the colorbar) by applying this argument into plt.hist2d().
cmin = 5, cmax = 25
Here is the full code
N = 10_000np.random.seed(100)x = np.random.randn(N)y = np.random.randn(N)plt.figure(figsize=(8.5, 7))plt.hist2d(x, y, bins=(75, 75), cmap = 'jet', cmin = 5, cmax = 25)cb = plt.colorbar()cb.set_label('counts each bin', labelpad = 10)
I use ‘jet’ colormaps with the lower limit for the colorbar equlas 5 and for the upper limit is 25. The code will generate a figure, as shown in Figure 33.
I try to change the generated random number counts from 10000 to 100000 using this code.
N = 100_000np.random.seed(100)x = np.random.randn(N)y = np.random.randn(N)plt.figure(figsize=(8.5, 7))plt.hist2d(x, y, bins=(75, 75), cmap = 'Spectral')cb = plt.colorbar()cb.set_label('counts each bin', labelpad = 10)
The code will show a result, as shown in Figure 34.
Figure 34 peaked at around 0 and distributed around -1 to 1 because I did not change the value of mu and sigma.
Marginal plot
This subsection will tell how to create a marginal distribution, as shown in Figure 35.
Figure 35 is built by scatter plot and 2 histogram. To create it, you need to understand how to customize the subplots or axes in a single figure. Figure 35 is constructed by 25 axes (5 columns and 5 rows). The detailed is shown in Figure 36. You can create Figure 36 with this code. You need to read this link to understand it.
rows = 5columns = 5grid = plt.GridSpec(rows, columns, wspace = .4, hspace = .4)plt.figure(figsize=(10, 10))for i in range(rows * columns): plt.subplot(grid[i]) plt.annotate('grid '+ str(i), xy = (.5, .5), ha = 'center', va = 'center')for i in range(rows): exec (f"plt.subplot(grid[{i}, 0])") plt.ylabel('rows ' + str(i), labelpad = 15)for i in range(columns): exec (f"plt.subplot(grid[-1, {i}])") plt.xlabel('column ' + str(i), labelpad = 15)
Figure 35 shows the transformation of Figure 36. I merge some grids in Figure 36 to only 3 bigger grids. The first grid combines grids 0 to grids 3 (rows 1, column 0 to column 3). I will fill the first grid with the histogram plot. The second grid merges 16 grids from rows 1 to rows 4 and from column 0 to column 3. The last grid is built by combining grids 9, 14, 19, and 24 (rows 1, 2, 3, 4, and column 4).
To create the first grid, you can use this code.
rows = 5columns = 5grid = plt.GridSpec(rows, columns, wspace = .4, hspace = .4)plt.figure(figsize=(10, 10))plt.subplot(grid[0, 0:-1])
After that, add the code below to insert 1D histogram
plt.hist(x, bins = 30, color = 'royalblue', alpha = .7)
To create the second grid, you can add this code to the code above
plt.subplot(grid[1:rows+1, 0:-1])
Add this code to generate scatter plot in the second grid.
plt.scatter(x, y, color = 'royalblue', s = 10)plt.axis('equal')
Here is the code to generate the third grid and its histogram. You need to insert the code below into the first grid code
plt.subplot(grid[1:rows+1, -1])plt.hist(y, bins = 30, orientation='horizontal', color = 'royalblue', alpha = .7)
You can combine it all, as shown in the following code.
Next, I will change the scatter plot in the second grid with the 2D histogram, as shown in Figure 37.
You can reproduce Figure 37 with this code.
Please leave some comments in the response column if you meet some errors.
If you want to visualize your data with a bar chart, this is suitable for you. Before I create a bar chart in Matplotlib, as usual, I want to create the mock data to be shown. I want to create data in the Math exam score for six persons. To create it, I use the following code.
name = ['Adam', 'Barry', 'Corbin', 'Doe', 'Evans', 'Frans']np.random.seed(100)N = len(name)math = np.random.randint(60, 100, N)
I generate the Math exam scores from 60 to 100. To visualize it, you can use this code.
plt.bar(name, math, alpha = .7)
After adding some information, I generate a bar chart, as shown in Figure 38.
Here is the full code to generate Figure 38.
name = ['Adam', 'Barry', 'Corbin', 'Doe', 'Evans', 'Frans']np.random.seed(100)N = len(name)math = np.random.randint(60, 100, N)plt.figure(figsize=(9, 6))plt.bar(name, math, alpha = .7)plt.ylabel('Math Exam')
After that, I create some more mock data for Physics, Biology, and Chemistry exam scores using this code.
np.random.seed(100)N = len(name)math = np.random.randint(60, 100, N)physics = np.random.randint(60, 100, N)biology = np.random.randint(60, 100, N)chemistry = np.random.randint(60, 100, N)
You can create a table, in Python we call it DataFrame, using Pandas. The DataFrame I create from the mock data is shown in Figure 39.
As a default, I did not insert the code on how to create the DataFrame. But, if you need it, you leave your request in the response column.
Then, I visualize it, as shown in Figure 40.
To create Figure 40, you can use this code.
name = ['Adam', 'Barry', 'Corbin', 'Doe', 'Evans', 'Frans']np.random.seed(100)N = len(name)math = np.random.randint(60, 100, N)physics = np.random.randint(60, 100, N)biology = np.random.randint(60, 100, N)chemistry = np.random.randint(60, 100, N)rows = 2columns = 2plt.figure(figsize=(12, 8))grid = plt.GridSpec(rows, columns, wspace = .25, hspace = .25)plt.subplot(grid[0])plt.bar(name, math, alpha = .7)plt.ylabel('Math Exam')plt.ylim(60, 100)plt.subplot(grid[1])plt.bar(name, physics, alpha = .7)plt.ylabel('Physics Exam')plt.ylim(60, 100)plt.subplot(grid[2])plt.bar(name, biology, alpha = .7)plt.ylabel('Biology Exam')plt.ylim(60, 100)plt.subplot(grid[3])plt.bar(name, chemistry, alpha = .7)plt.ylabel('Chemistry Exam')plt.ylim(60, 100)
or use this code if you want use a looping.
name = ['Adam', 'Barry', 'Corbin', 'Doe', 'Evans', 'Frans']course_name = ['Math', 'Physics', 'Biology', 'Chemistry']N = len(name)rows = 2columns = 2plt.figure(figsize=(12, 8))grid = plt.GridSpec(rows, columns, wspace = .25, hspace = .25)for i in range(len(course_name)): np.random.seed(100) course = np.random.randint(60, 100, N) plt.subplot(grid[i]) plt.bar(name, course, alpha = .7) plt.ylabel(course_name[i] + ' Exam') plt.ylim(60, 100)
Horizontal bar chart
You can use a horizontal bar chart with this code.
plt.barh(name, course)
I want to present Figure 40 in the form of horizontal bar chart and in various colors. Here is the full code to generate it.
name = ['Adam', 'Barry', 'Corbin', 'Doe', 'Evans', 'Frans']course_name = ['Math', 'Physics', 'Biology', 'Chemistry']colors = ['#00429d', '#7f40a2', '#a653a1', '#c76a9f', '#e4849c', '#d0e848']N = len(name)rows = 2columns = 2plt.figure(figsize=(12, 8))grid = plt.GridSpec(rows, columns, wspace = .25, hspace = .25)for i in range(len(course_name)): np.random.seed(100) course = np.random.randint(60, 100, N) plt.subplot(grid[i]) plt.barh(name, course, color = colors) plt.xlabel(course_name[i] + ' Exam') plt.xlim(60, 100) plt.gca().invert_yaxis()
After you run the code above, you will get a result, as shown in Figure 41.
You can insert the error bar in the horizontal bar chart using this argument
N = len(name)noise = np.random.randint(1, 3, N)plt.barh(name, course, xerr = noise)
I create the error using integer random number from 1 to 3, as mentioned in the variable noise. After adding some elements for my horizontal bar chart, I show it, as shown in Figure 42.
You can reproduce Figure 42 with this code.
name = ['Adam', 'Barry', 'Corbin', 'Doe', 'Evans', 'Frans']course_name = ['Math', 'Physics', 'Biology', 'Chemistry']N = len(name)rows = 2columns = 2plt.figure(figsize=(12, 8))grid = plt.GridSpec(rows, columns, wspace = .25, hspace = .25)np.random.seed(100)for i in range(len(course_name)): course = np.random.randint(60, 95, N) noise = np.random.randint(1, 3, N) plt.subplot(grid[i]) plt.barh(name, course, color = colors, xerr = noise, ecolor = 'k') plt.xlabel(course_name[i] + ' Exam') plt.xlim(60, 100) plt.gca().invert_yaxis()
Maybe, you realize that my mock data (with error) is not realistic. You can not meet an exam score with the uncertainty. But, I think it is still a good example in understanding the bar chart in Matplotlib.
This is the end of part 1. As I mentioned before, I try to limit the reading time (less than 30 minutes), so you can enjoy the reading. This part only covers 4 from 11 sections, scatter plot, line plot, histogram, and bar chart. In the next part, I will show the tutorials to create a box plot, violin plot, pie chart, polar chart, geographic projection, 3D plot, and contour plot. If the next part is consuming more than 30 minutes, I will divide it again.
Data visualization is significant in analyzing data from small data or big data in the technological era. We need it to have a global picture of our data. Various types of visualization you can use with Matplotlib. This is just a small part of python plotting with Matplotlib.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
That’s all. Thanks for reading this story. Comment and share if you like it. I also recommend you follow my account to get a notification when I post my new story. In a couple of days, I will publish Part 2 for Visualizations with Matplotlib. | [
{
"code": null,
"e": 838,
"s": 172,
"text": "Data visualization aims to present the data into a more straightforward representation, such as scatter plot, density plot, bar chart, etc. It is also useful to give readers or analysts a global picture of their data. By visualizing your data, you can det... |
Set conditions for columns with values 0 or 1 in MySQL | To set conditions, use CASE WHEN statement in MySQL. Let us first create a table −
mysql> create table DemoTable
-> (
-> Value1 int,
-> Value2 int,
-> Value3 int,
-> Value4 int
-> );
Query OK, 0 rows affected (0.98 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1,0,1,1);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(1,0,1,0);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(1,1,1,1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(0,0,0,0);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+--------+--------+--------+--------+
| Value1 | Value2 | Value3 | Value4 |
+--------+--------+--------+--------+
| 1 | 0 | 1 | 1 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 1 | 1 |
| 0 | 0 | 0 | 0 |
+--------+--------+--------+--------+
4 rows in set (0.00 sec)
Here is the query to set conditions for columns with values 0 or 1 in MySQL−
mysql> select case when Value1+Value2+Value3+Value4 < 2 then 'NotGood' else 'Good' end as Status from DemoTable;
This will produce the following output −
+---------+
| Status |
+---------+
| Good |
| Good |
| Good |
| NotGood |
+---------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To set conditions, use CASE WHEN statement in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1300,
"s": 1145,
"text": "mysql> create table DemoTable\n -> (\n -> Value1 int,\n -> Value2 int,\n -> Value3 int,\n ... |
Object level and Class level locks in Java - GeeksforGeeks | 10 Mar, 2021
Synchronization:
Synchronization is a modifier that is used for the method and blocks only. With the help of a synchronized modifier, we can restrict a shared resource to be accessed only by one thread. When two or more threads need access to shared resources, there is some loss of data i.e. data inconsistency. The process by which we can achieve data consistency between multiple threads is called Synchronization.
Why do you need Synchronization?
Let us assume if you have two threads that are reading and writing to the same ‘resource’. Suppose there is a variable named geek, and you want that at one time only one thread should access the variable(atomic way). But Without the synchronized keyword, your thread 1 may not see the changes thread 2 made to geek, or worse, it may only be half changed that cause the data inconsistency problem. This would not be what you logically expect. The tool needed to prevent these errors is synchronization.
In synchronization, there are two types of locks on threads:
Object-level lock: Every object in java has a unique lock. Whenever we are using a synchronized keyword, then only the lock concept will come into the picture. If a thread wants to execute then synchronized method on the given object. First, it has to get a lock-in that object. Once the thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock. Acquiring and release lock internally is taken care of by JVM and the programmer is not responsible for these activities. Let’s have a look at the below program to understand the object level lock:
JAVA
// Java program to illustrate// Object lock conceptclass Geek implements Runnable { public void run() { Lock(); } public void Lock() { System.out.println( Thread.currentThread().getName()); synchronized (this) { System.out.println( "in block " + Thread.currentThread().getName()); System.out.println( "in block " + Thread.currentThread().getName() + " end"); } } public static void main(String[] args) { Geek g = new Geek(); Thread t1 = new Thread(g); Thread t2 = new Thread(g); Geek g1 = new Geek(); Thread t3 = new Thread(g1); t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); t1.start(); t2.start(); t3.start(); }}
t1
t3
t2
in block t3
in block t1
in block t3 end
in block t1 end
in block t2
in block t2 end
Class level lock: Every class in Java has a unique lock which is nothing but a class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock. Let’s look at the below program for better understanding:
JAVA
// Java program to illustrate class level lockclass Geek implements Runnable { public void run() { Lock(); } public void Lock() { System.out.println( Thread.currentThread().getName()); synchronized (Geek.class) { System.out.println( "in block " + Thread.currentThread().getName()); System.out.println( "in block " + Thread.currentThread().getName() + " end"); } } public static void main(String[] args) { Geek g1 = new Geek(); Thread t1 = new Thread(g1); Thread t2 = new Thread(g1); Geek g2 = new Geek(); Thread t3 = new Thread(g2); t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); t1.start(); t2.start(); t3.start(); }}
t1
t2
t3
in block t1
in block t1 end
in block t3
in block t3 end
in block t2
in block t2 end
Reference: https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
AyushBaheti
vishalmehatre16
Java-Class and Object
Java-Multithreading
Java
Java-Class and Object
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
LinkedList in Java
Collections in Java
Overriding in Java
Different ways of Reading a text file in Java | [
{
"code": null,
"e": 24330,
"s": 24302,
"text": "\n10 Mar, 2021"
},
{
"code": null,
"e": 24348,
"s": 24330,
"text": "Synchronization: "
},
{
"code": null,
"e": 24749,
"s": 24348,
"text": "Synchronization is a modifier that is used for the method and blocks onl... |
Program to implement Collatz Conjecture - GeeksforGeeks | 08 Feb, 2022
Given a positive integer n, the task is to find whether this number reaches to 1 after performing following two operations:-
If n is even, then n = n/2.If n is odd, then n = 3*n + 1.Repeat above steps, until it becomes 1.
If n is even, then n = n/2.
If n is odd, then n = 3*n + 1.
Repeat above steps, until it becomes 1.
For example, for n = 12, we get the sequence 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.Examples:
Input : n = 4
Output : Yes
Input : n = 5
Output : Yes
The idea is to simply follow given rules and recursively call function with reduced values until it reaches 1. If a value is seen again during recursion, then there is a cycle and we can’t reach 1. In this case, we return false.
C++
Java
Python3
C#
Javascript
// C++ program to implement Collatz Conjecture#include<bits/stdc++.h>using namespace std; // Function to find if n reaches to 1 or not.bool isToOneRec(int n, unordered_set<int> &s){ if (n == 1) return true; // If there is a cycle formed, we can't r // reach 1. if (s.find(n) != s.end()) return false; s.insert(n);//inserting elements to the s // If n is odd then pass n = 3n+1 else n = n/2 return (n % 2)? isToOneRec(3*n + 1, s) : isToOneRec(n/2, s);} // Wrapper over isToOneRec()bool isToOne(int n){ // To store numbers visited using recursive calls. unordered_set<int> s; return isToOneRec(n, s);} // Drivers codeint main(){ int n = 5; isToOne(n) ? cout << "Yes" : cout <<"No"; return 0;}
// Java program to implement Collatz Conjectureimport java.util.*; class GFG{ // Function to find if n reaches to 1 or not. static boolean isToOneRec(int n, HashSet<Integer> s) { if (n == 1) { return true; } // If there is a cycle formed, we can't r // reach 1. if (s.contains(n)) { return false; } // If n is odd then pass n = 3n+1 else n = n/2 return (n % 2 == 1) ? isToOneRec(3 * n + 1, s) : isToOneRec(n / 2, s); } // Wrapper over isToOneRec() static boolean isToOne(int n) { // To store numbers visited using recursive calls. HashSet<Integer> s = new HashSet<Integer>(); return isToOneRec(n, s); } // Drivers code public static void main(String[] args) { int n = 5; if (isToOne(n)) { System.out.print("Yes"); } else { System.out.print("No"); } }} /* This code contributed by PrinciRaj1992 */
# Python3 program to implement Collatz Conjecture # Function to find if n reaches to 1 or not.def isToOneRec(n: int, s: set) -> bool: if n == 1: return True # If there is a cycle formed, # we can't reach 1. if n in s: return False # If n is odd then pass n = 3n+1 else n = n/2 if n % 2: return isToOneRec(3 * n + 1, s) else: return isToOneRec(n // 2, s) # Wrapper over isToOneRec()def isToOne(n: int) -> bool: # To store numbers visited # using recursive calls. s = set() return isToOneRec(n, s) # Driver Codeif __name__ == "__main__": n = 5 if isToOne(n): print("Yes") else: print("No") # This code is contributed by# sanjeev2552
// C# program to implement// Collatz Conjectureusing System;using System.Collections.Generic; class GFG{ // Function to find if n reaches to 1 or not. static Boolean isToOneRec(int n, HashSet<int> s) { if (n == 1) { return true; } // If there is a cycle formed, // we can't reach 1. if (s.Contains(n)) { return false; } // If n is odd then pass n = 3n+1 else n = n/2 return (n % 2 == 1) ? isToOneRec(3 * n + 1, s) : isToOneRec(n / 2, s); } // Wrapper over isToOneRec() static Boolean isToOne(int n) { // To store numbers visited using // recursive calls. HashSet<int> s = new HashSet<int>(); return isToOneRec(n, s); } // Driver code public static void Main(String[] args) { int n = 5; if (isToOne(n)) { Console.Write("Yes"); } else { Console.Write("No"); } }} // This code contributed by Rajput-Ji
<script> // Javascript program to implement Collatz Conjecture // Function to find if n reaches to 1 or not. function isToOneRec(n, s) { if (n == 1) { return true; } // If there is a cycle formed, // we can't reach 1. if (s.has(n)) { return false; } // If n is odd then pass n = 3n+1 else n = n/2 return (n % 2 == 1) ? isToOneRec(3 * n + 1, s) : isToOneRec(n / 2, s); } // Wrapper over isToOneRec() function isToOne(n) { // To store numbers visited using // recursive calls. let s = new Set(); return isToOneRec(n, s); } let n = 5; if (isToOne(n)) { document.write("Yes"); } else { document.write("No"); } // This code is contributed by divyeshrabadiya07.</script>
Output:
Yes
The above program is inefficient. The idea is to use Collatz Conjecture. It states that if n is a positive then somehow it will reaches to 1 after a certain amount of time. So, by using this fact it can be done in O(1) i.e. just check if n is a positive integer or not. Note that the answer would be false for negative numbers. For negative numbers, the above operations would keep number negative and it would never reach 1.
C++
Java
Python 3
C#
Javascript
PHP
// C++ program to implement Collatz Conjecture#include<bits/stdc++.h>using namespace std; // Function to find if n reaches to 1 or not.bool isToOne(int n){ // Return true if n is positive return (n > 0);} // Drivers codeint main(){ int n = 5; isToOne(n) ? cout << "Yes" : cout <<"No"; return 0;}
// Java program to implement Collatz// Conjectureclass GFG { // Function to find if n reaches // to 1 or not. static boolean isToOne(int n) { // Return true if n is positive return (n > 0); } // Drivers code public static void main(String[] args) { int n = 5; if(isToOne(n) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Smitha.
# Python 3 program to implement# Collatz Conjecture # Function to find if n# reaches to 1 or not.def isToOne(n): # Return true if n # is positive return (n > 0) # Drivers coden = 5 if isToOne(n) == True: print("Yes")else: print("No") # This code is contributed# by Smitha.
// C# program to implement// Collatz Conjectureusing System; class GFG { // Function to find if n // reaches to 1 or not. static bool isToOne(int n) { // Return true if n // is positive return (n > 0); } // Drivers code public static void Main() { int n = 5; if(isToOne(n) == true) Console.Write("Yes") ; else Console.Write("No"); }} // This code is contributed// by Smitha.
<script> // Javascript program to implement Collatz Conjecture // Function to find if n // reaches to 1 or not. function isToOne(n) { // Return true if n // is positive return (n > 0); } let n = 5; if(isToOne(n) == true) document.write("Yes") ; else document.write("No"); // This code is contributed by mukesh07.</script>
<?php// PHP program to implement Collatz Conjecture // Function to find if n reaches// to 1 or not.function isToOne($n){ // Return true if n is positive if($n > 0) return true; return false;} // Driver code$n = 5;isToOne($n)? print("Yes") : print("No"); // This code is contributed by princiraj1992?>
Output:
Yes
We strongly recommend to refer below problem as an exercise: Maximum Collatz sequence lengthThis article is contributed by Sahil Chhabra (akku). 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.
Smitha Dinesh Semwal
princiraj1992
Rajput-Ji
sanjeev2552
divyeshrabadiya07
mukesh07
varshagumber28
hazemk537
sumitgumber28
Mathematical
Recursion
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for Tower of Hanoi
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Sum of the digits of a given number
Backtracking | Introduction | [
{
"code": null,
"e": 24598,
"s": 24570,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 24725,
"s": 24598,
"text": "Given a positive integer n, the task is to find whether this number reaches to 1 after performing following two operations:- "
},
{
"code": null,
"e":... |
Logo detection in Images using SSD | by Ankur Singh | Towards Data Science | Logos sometimes also known as trademark have high importance in today’s marketing world. Products, companies and different gaming leagues are often recognized by their respective logos. Logo recognition in images and videos is the key problem in a wide range of applications, such as copyright infringement detection, vehicle logo for intelligent traffic-control systems, augmented reality, contextual advertise placement and others. In this post we will look on how to use SSD from Tensorflow API to detect as well as localize brand logos in images of a T.V. show(Big Boss India). The task is to detect and localize six brand logos: fizz, oppo, samsung, garnier, faber, cpplus from images of the show.
According to the paper on SSD, SSD: Single Shot Multibox Detector is a method for detecting objects in images using a single deep neural network. SSD, discretizes the output space of bounding boxes into a set of default boxes over different aspect ratios and scales per feature map location. At prediction time, the network generates scores for the presence of each object category in each default box and produces adjustments to the box to better match the object shape. Additionally, the network combines predictions from multiple feature maps with different resolutions to naturally handle objects of various sizes. Experimental results on the PASCAL VOC, COCO, and ILSVRC datasets confirm that SSD has competitive accuracy to methods that utilize an additional object proposal step and is much faster, while providing a unified framework for both training and inference.
The tasks of object detection and localization and classification are done in a single forward pass of the network.
Architecture of SSD
Logo Detection Dataset
Data for this task was obtained by capturing individual frames from a video clip of the show. A total of 6267 images were captured. I used 600 images for Test and the rest for the Training part. Now, the next step was to annotate the images obtained. To do that, I used LabelImg. LabelImg is a graphical image annotation tool. The annotations produced are saved as XML files in PASCAL VOC format. The installation instructions are given in the repository.
Similarly, I had to go through all the images of the dataset and annotate them individually.
TFRecords
If we are working with large datasets, using a binary file format for storage of data can have a significant impact on the performance of our import pipeline and as a consequence on the training time of our model. Binary data takes up less space on disk, takes less time to copy and can be read much more efficiently from disk. This is where a TFRecord comes up. However, pure performance isn’t the only advantage of the TFRecord file format. It is optimized for use with Tensorflow in multiple ways. To start with, it makes it easy to combine multiple datasets and integrates seamlessly with the data import and preprocessing functionality provided by the library. Especially for datasets that are too large to be stored fully in memory this is an advantage as only the data that is required at the time (e.g. a batch) is loaded from disk and then processed. Since, we are going to work with the Tensorflow API, we will be converting our XML files to TFRecords.
Converting XML to TFRecord
To convert XML files to TFRecord, we will first convert them to CSV using a python script, thanks to this repository. There are some minor changes that need to be introduced. Here is the code that converts your XML files to CSV files.
The XML files stored in ‘images/train’ and ‘images/test’ are converted to two CSV files, one for train and one for test which are generated in the folder ‘data’.(Note these details, if you want to train your SSD model on a custom dataset)
Once, the XML files have been converted to CSV files, we can then output the TFRecords using a python script from the same repository with some changes.
For training on your custom dataset, change the class names in the class_text_to_int function. Also, make sure you follow the installation instructions over here to install the dependencies to run the above code. Clone the tensorflow repository as well. It will be helpful later on.
Once you are done with the installations, we are all set to generate our tfrecords using the code snippet above. Type this in your terminal to generate the tfrecord for the training data.
python generate_tfrecord.py — csv_input=data/train_labels.csv — output_path=data/train.record
Ahh finally!! we have our train.record. Similarly do this for the test data.
python generate_tfrecord.py — csv_input=data/test_labels.csv — output_path=data/test.record
Training Brand Logos Detector
To get our brand logos detector we can either use a pre-trained model and then use transfer learning to learn a new object, or we could learn new objects entirely from scratch. The benefit of transfer learning is that training can be much quicker, and the required data that you might need is much less. For this reason, we’re going to be doing transfer learning here. TensorFlow has quite a few pre-trained models with checkpoint files available, along with configuration files.
For this task I have used Inception. You can always use some other model. You can get a list of models and their download links from here. To get the configuration file of your corresponding model click here. Now, that we are done with downloading our model and our configuration file, we need to edit the configuration file according to our dataset.
In your configuration file search for “PATH_TO_BE_CONFIGURED” and change it to something similar to what has been shown in the code snippet above. Also, change the number of classes in the config file.
One last thing that still remains before we can start training is creating the label map. Label map is basically a dictionary which contains the id and name of the classes that we want to detect.
That’s it. That’s it. We can now start training. Ahh finally! Copy all your data to the cloned tensorflow repository on your system(Clone it if you haven’t earlier). And from within ‘models/object_detection’ type this command in your terminal.
python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_inception_v2_coco_2017_11_17.config
You can wait until the total loss reaches around 1.
Testing Brand Logos Detector
To test how good our model is doing, we need to export the inference graph. In the ‘models/object_detection’ directory, there is a script that does this for us: ‘export_inference_graph.py’To run this, you just need to pass in your checkpoint and your pipeline config. Your checkpoint files should be in the ‘training’ directory. Just look for the one with the largest step (the largest number after the dash), and that's the one you want to use. Next, make sure the pipeline_config_path is set to whatever config file you chose, and then finally choose the name for the output directory. For eg:
python3 export_inference_graph.py \ --input_type image_tensor \ --pipeline_config_path training/ssd_inception_v2_coco_2017_11_17.config \ --trained_checkpoint_prefix training/model.ckpt-7051 \ --output_directory logos_inference_graph
Once this runs successfully you should have a new directory with the name ‘logos_inference_graph’. After this open ‘object_detection_tutorial.ipynb’ and change the ‘MODEL_NAME’ to ‘logos_inference_graph’ and change the number of classes in the Variables section. Next, we can just delete the entire Download Model section in the notebook, since we don't need to download our model anymore. In the ‘Test_Images_Path’ you can enter the directory where your test images have been stored.
Results
Here are some of my results:
Summary
To detect logos in images, these are the procedures that I followed:
Obtaining DatasetCreating XML files using LabelImgConverting XML files to TFRecordsDownloading the model and editing the corresponding configuration fileCreating a label mapStart Training
Obtaining Dataset
Creating XML files using LabelImg
Converting XML files to TFRecords
Downloading the model and editing the corresponding configuration file
Creating a label map
Start Training
References
https://arxiv.org/pdf/1512.02325.pdfhttps://github.com/tensorflow/tensorflowhttps://pythonprogramming.net/introduction-use-tensorflow-object-detection-api-tutorial/ (Please go through this for a better insight)https://github.com/tzutalin/labelImghttps://github.com/datitran/raccoon_datasethttps://medium.com/mostly-ai/tensorflow-records-what-they-are-and-how-to-use-them-c46bc4bbb564https://towardsdatascience.com/understanding-ssd-multibox-real-time-object-detection-in-deep-learning-495ef744fab
https://arxiv.org/pdf/1512.02325.pdf
https://github.com/tensorflow/tensorflow
https://pythonprogramming.net/introduction-use-tensorflow-object-detection-api-tutorial/ (Please go through this for a better insight)
https://github.com/tzutalin/labelImg
https://github.com/datitran/raccoon_dataset
https://medium.com/mostly-ai/tensorflow-records-what-they-are-and-how-to-use-them-c46bc4bbb564
https://towardsdatascience.com/understanding-ssd-multibox-real-time-object-detection-in-deep-learning-495ef744fab
Feel free to comment your opinions and do clap, if you liked it. | [
{
"code": null,
"e": 875,
"s": 172,
"text": "Logos sometimes also known as trademark have high importance in today’s marketing world. Products, companies and different gaming leagues are often recognized by their respective logos. Logo recognition in images and videos is the key problem in a wide ra... |
Python program to find the maximum of three numbers | In this tutorial, we are going to write a program which finds the max amount from the three figures. We will have three number, and our goal is to find out the maximum number from those three numbers.
Let's see some sample test cases for better understanding.
Input:
a, b, c = 2, 34, 4
Output:
34
Input:
a, b, c = 25, 3, 12
Output:
25
Input:
a, b, c = 5, 5, 5
Output:
5
Follow the below steps to find out the max number among three numbers.
1. Initialise three numbers a, b, c.
2. If a is higher than b and c then, print a.
3. Else if b is greater than c and a then, print b.
4. Else if c is greater than a and b then, print c.
5. Else print any number.
Let's see the code for the above algorithm.
## initializing three numbers
a, b, c = 2, 34, 4
## writing conditions to find out max number
## condition for a
if a > b and a > c:
## printing a
print(f"Maximum is {a}")
## condition for b
elif b > c and b > a:
## printing b
print(f"Maximum is {b}")
## condition for c
elif c > a and c > b:
## printing
print(f"Maximum is {c}")
## equality case
else:
## printing any number among three
print(a)
If you run the above program, you will get the following output.
Maximum is 34
Let's execute the code once again for different test case
## initializing three numbers
a, b, c = 5, 5, 5
## writing conditions to find out max number
## condition for a
if a > b and a > c:
## printing a
print(f"Maximum is {a}")
## condition for b
elif b > c and b > a:
## printing b
print(f"Maximum is {b}")
## condition for c
elif c > a and c > b:
## printing
print(f"Maximum is {c}")
## equality case
else:
## printing any number among three
print(f"Maximum is {a}")
If you run the above program, you will get the following output.
Maximum is 5
If you have any doubts regarding the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "In this tutorial, we are going to write a program which finds the max amount from the three figures. We will have three number, and our goal is to find out the maximum number from those three numbers."
},
{
"code": null,
"e": 1322,
"s": ... |
Develop a NLP Model in Python & Deploy It with Flask, Step by Step | by Susan Li | Towards Data Science | By far, we have developed many machine learning models, generated numeric predictions on the testing data, and tested the results. And we did everything offline. In reality, generating predictions is only part of a machine learning project, although it is the most important part in my opinion.
Considering a system using machine learning to detect spam SMS text messages. Our ML systems workflow is like this: Train offline -> Make model available as a service -> Predict online.
A classifier is trained offline with spam and non-spam messages.
The trained model is deployed as a service to serve users.
When we develop a machine learning model, we need to think about how to deploy it, that is, how to make this model available to other users.
Kaggle and Data science bootcamps are great for learning how to build and optimize models, but they don’t teach engineers how to take them to the next step, where there’s a major difference between building a model, and actually getting it ready for people to use in their products and services.
In this article, we will focus on both: building a machine learning model for spam SMS message classification, then create an API for the model, using Flask, the Python micro framework for building web applications.This API allows us to utilize the predictive capabilities through HTTP requests. Let’s get started!
The data is a collection of SMS messages tagged as spam or ham that can be found here. First, we will use this dataset to build a prediction model that will accurately classify which texts are spam.
Naive Bayes classifiers are a popular statistical technique of e-mail filtering. They typically use bag of words features to identify spam e-mail. Therefore, We’ll build a simple message classifier using Naive Bayes theorem.
Not only Naive Bayes classifier is easy to implement but also provides very good result.
After training the model, it is desirable to have a way to persist the model for future use without having to retrain. To achieve this, we add the following lines to save our model as a .pkl file for the later use.
from sklearn.externals import joblibjoblib.dump(clf, 'NB_spam_model.pkl')
And we can load and use saved model later like so:
NB_spam_model = open('NB_spam_model.pkl','rb')clf = joblib.load(NB_spam_model)
The above process called “persist model in a standard format”, that is, models are persisted in a certain format specific to the language in development.
And the model will be served in a micro-service that expose endpoints to receive requests from client. This is the next step.
Having prepared the code for classifying SMS messages in the previous section, we will develop a web application that consists of a simple web page with a form field that lets us enter a message. After submitting the message to the web application, it will render it on a new page which gives us a result of spam or not spam.
First, we create a folder for this project called SMS-Message-Spam-Detector , this is the directory tree inside the folder. We will explain each file.
spam.csvapp.pytemplates/ home.html result.htmlstatic/ style.css
The sub-directory templates is the directory in which Flask will look for static HTML files for rendering in the web browser, in our case, we have two html files: home.html and result.html .
The app.py file contains the main code that will be executed by the Python interpreter to run the Flask web application, it included the ML code for classifying SMS messages:
We ran our application as a single module; thus we initialized a new Flask instance with the argument __name__ to let Flask know that it can find the HTML template folder (templates) in the same directory where it is located.
Next, we used the route decorator (@app.route('/')) to specify the URL that should trigger the execution of the home function.
Our home function simply rendered the home.html HTML file, which is located in the templates folder.
Inside the predict function, we access the spam data set, pre-process the text, and make predictions, then store the model. We access the new message entered by the user and use our model to make a prediction for its label.
we used the POST method to transport the form data to the server in the message body. Finally, by setting the debug=True argument inside the app.run method, we further activated Flask's debugger.
Lastly, we used the run function to only run the application on the server when this script is directly executed by the Python interpreter, which we ensured using the if statement with __name__ == '__main__'.
The following are the contents of the home.html file that will render a text form where a user can enter a message:
In the header section of home.html, we loaded styles.cssfile. CSS is to determine how the look and feel of HTML documents. styles.css has to be saved in a sub-directory calledstatic, which is the default directory where Flask looks for static files such as CSS.
we create a result.html file that will be rendered via the render_template('result.html', prediction=my_prediction) line return inside the predictfunction, which we defined in the app.py script to display the text that a user submitted via the text field. The result.htmlfile contains the following content:
From result.htm we can see that some code using syntax not normally found in HTML files: {% if prediction ==1%},{% elif prediction == 0%},{% endif %}This is jinja syntax, and it is used to access the prediction returned from our HTTP request within the HTML file.
We are almost there!
Once you have done all of the above, you can start running the API by either double click appy.py , or executing the command from the Terminal:
cd SMS-Message-Spam-Detectorpython app.py
You should get the following output:
Now you could open a web browser and navigate to http://127.0.0.1:5000/, we should see a simple website with the content like so:
Let’s test our work!
Congratulations! We have now created an end-to-end machine learning (NLP) application at zero cost. If you look it back, the overall process is not complicated at all. With a little bit patience and desire to learn, anyone can do it. All the open-source tools make every thing possible.
More importantly, we are able to extend our knowledge of machine learning theory to a useful and practical web application and lets us make our SMS spam message classifier available to the outside world!
The complete working source code is available at this repository. Have a great week!
Reference:
Book: Python Machine Learning | [
{
"code": null,
"e": 467,
"s": 172,
"text": "By far, we have developed many machine learning models, generated numeric predictions on the testing data, and tested the results. And we did everything offline. In reality, generating predictions is only part of a machine learning project, although it is... |
getopt() function in C to parse command line arguments - GeeksforGeeks | 10 Sep, 2018
The getopt() function is a builtin function in C and is used to parse command line arguments.
Syntax:
getopt(int argc, char *const argv[], const char *optstring)
optstring is simply a list of characters,
each representing a single character option.
Return Value: The getopt() function returns different values:
If the option takes a value, that value is pointer to the external variable optarg.
‘-1’ if there are no more options to process.
‘?’ when there is an unrecognized option and it stores into external variable optopt.
If an option requires a value (such as -f in our example) and no value is given, getopt normally returns ?.By placing a colon as the first character of the options string, getopt returns: instead of ? when no value is given.
Generally, the getopt() function is called from inside of a loop’s conditional statement. The loop terminates when the getopt() function returns -1. A switch statement is then executed with the value returned by getopt() function.
A second loop is used to process the remaining extra arguments that cannot be processed in the first loop.
Below program illustrate the getopt() function in C:
// Program to illustrate the getopt()// function in C #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { int opt; // put ':' in the starting of the // string so that program can //distinguish between '?' and ':' while((opt = getopt(argc, argv, “:if:lrx”)) != -1) { switch(opt) { case ‘i’: case ‘l’: case ‘r’: printf(“option: %c\n”, opt); break; case ‘f’: printf(“filename: %s\n”, optarg); break; case ‘:’: printf(“option needs a value\n”); break; case ‘?’: printf(“unknown option: %c\n”, optopt); break; } } // optind is for the extra arguments // which are not parsed for(; optind < argc; optind++){ printf(“extra arguments: %s\n”, argv[optind]); } return 0;}
Output:
C-Functions
C-Library
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Strings in C
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses | [
{
"code": null,
"e": 24598,
"s": 24570,
"text": "\n10 Sep, 2018"
},
{
"code": null,
"e": 24692,
"s": 24598,
"text": "The getopt() function is a builtin function in C and is used to parse command line arguments."
},
{
"code": null,
"e": 24700,
"s": 24692,
"text... |
Absolute and Relative Pathnames in UNIX - GeeksforGeeks | 18 Mar, 2021
A path is a unique location to a file or a folder in a file system of an OS.A path to a file is a combination of / and alpha-numeric characters.
Absolute Path-name
An absolute path is defined as the specifying the location of a file or directory from the root directory(/).To write an absolute path-name:
Start at the root directory ( / ) and work down.
Write a slash ( / ) after every directory name (last one is optional)For Example :$cat abc.sql
will work only if the fie “abc.sql” exists in your current directory. However, if this file is not present in your working directory and is present somewhere else say in /home/kt , then this command will work only if you will use it like shown below:cat /home/kt/abc.sql
In the above example, if the first character of a pathname is /, the file’s location must be determined with respect to root. When you have more than one / in a pathname, for each such /, you have to descend one level in the file system like in the above kt is one level below home, and thus two levels below root.An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory.Relative pathRelative path is defined as the path related to the present working directly(pwd). It starts at your current directory and never starts with a / .To be more specific let’s take a look on the below figure in which if we are looking for photos then absolute path for it will be provided as /home/jono/photos but assuming that we are already present in jono directory then the relative path for the same can be written as simple photos.Using . and .. in Relative Path-namesUNIX offers a shortcut in the relative pathname– that uses either the current or parent directory as reference and specifies the path relative to it. A relative path-name uses one of these cryptic symbols:.(a single dot) - this represents the current directory.
..(two dots) - this represents the parent directory. Now, what this actually means is that if we are currently in directory /home/kt/abc and now you can use .. as an argument to cd to move to the parent directory /home/kt as :$pwd
/home/kt/abc
$cd .. ***moves one level up***
$pwd
/home/kt
NOTE:Now / when used with .. has a different meaning ;instead of moving down a level,it moves one level up:
$pwd
/home/kt/abc ***moves two level up***
$cd ../..
$pwd
/home
Example of Absolute and Relative PathSuppose you are currently located in home/kt and you want to change your directory to home/kt/abc. Let’s see both the absolute and relative path concepts to do this:Changing directory with relative path concept :$pwd
/home/kt
$cd abc
$pwd
/home/kt/abc
Changing directory with absolute path concept:$pwd
/home/kt
$cd /home/kt/abc
$pwd
/home/kt/abc
This article is contributed by Dimpy Varshni. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.My Personal Notes
arrow_drop_upSave
For Example :
$cat abc.sql
will work only if the fie “abc.sql” exists in your current directory. However, if this file is not present in your working directory and is present somewhere else say in /home/kt , then this command will work only if you will use it like shown below:
cat /home/kt/abc.sql
In the above example, if the first character of a pathname is /, the file’s location must be determined with respect to root. When you have more than one / in a pathname, for each such /, you have to descend one level in the file system like in the above kt is one level below home, and thus two levels below root.
An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory.
Relative path
Relative path is defined as the path related to the present working directly(pwd). It starts at your current directory and never starts with a / .
To be more specific let’s take a look on the below figure in which if we are looking for photos then absolute path for it will be provided as /home/jono/photos but assuming that we are already present in jono directory then the relative path for the same can be written as simple photos.
Using . and .. in Relative Path-names
UNIX offers a shortcut in the relative pathname– that uses either the current or parent directory as reference and specifies the path relative to it. A relative path-name uses one of these cryptic symbols:
.(a single dot) - this represents the current directory.
..(two dots) - this represents the parent directory.
Now, what this actually means is that if we are currently in directory /home/kt/abc and now you can use .. as an argument to cd to move to the parent directory /home/kt as :
$pwd
/home/kt/abc
$cd .. ***moves one level up***
$pwd
/home/kt
NOTE:Now / when used with .. has a different meaning ;instead of moving down a level,it moves one level up:
$pwd
/home/kt/abc ***moves two level up***
$cd ../..
$pwd
/home
Example of Absolute and Relative Path
Suppose you are currently located in home/kt and you want to change your directory to home/kt/abc. Let’s see both the absolute and relative path concepts to do this:
Changing directory with relative path concept :$pwd
/home/kt
$cd abc
$pwd
/home/kt/abc
Changing directory with absolute path concept:$pwd
/home/kt
$cd /home/kt/abc
$pwd
/home/kt/abc
Changing directory with relative path concept :$pwd
/home/kt
$cd abc
$pwd
/home/kt/abc
$pwd
/home/kt
$cd abc
$pwd
/home/kt/abc
Changing directory with absolute path concept:$pwd
/home/kt
$cd /home/kt/abc
$pwd
/home/kt/abc
$pwd
/home/kt
$cd /home/kt/abc
$pwd
/home/kt/abc
This article is contributed by Dimpy Varshni. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
echo command in Linux with Examples
ps command in Linux with Examples | [
{
"code": null,
"e": 25392,
"s": 25364,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 25537,
"s": 25392,
"text": "A path is a unique location to a file or a folder in a file system of an OS.A path to a file is a combination of / and alpha-numeric characters."
},
{
"cod... |
30 Examples to Master Pandas. A comprehensive practical guide for... | by Soner Yıldırım | Towards Data Science | Pandas is a widely-used data analysis and manipulation library for Python. It provides numerous functions and methods that expedite the data analysis and preprocessing steps.
Due to its popularity, there are lots of articles and tutorials about Pandas. This one will be one of them but heavily focusing on the practical side. I will do examples on a customer churn dataset that is available on Kaggle.
The examples will cover almost all the functions and methods you are likely to use in a typical data analysis process.
Let’s start by reading the csv file into a pandas dataframe.
import numpy as npimport pandas as pddf = pd.read_csv("/content/churn.csv")df.shape(10000,14)df.columnsIndex(['RowNumber', 'CustomerId', 'Surname', 'CreditScore', 'Geography', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard','IsActiveMember','EstimatedSalary', 'Exited'], dtype='object')
The drop function is used to drop columns and rows. We pass the labels of rows or columns to be dropped.
df.drop(['RowNumber', 'CustomerId', 'Surname', 'CreditScore'], axis=1, inplace=True)df.shape(10000,10)
The axis parameter is set as 1 to drop columns and 0 for rows. The inplace parameter is set as True to save the changes. We dropped 4 columns so the number of columns reduced to 10 from 14.
We can read only some of the columns from the csv file. The list of columns is passed to the usecols parameter while reading. It is better than dropping later on if you know the column names beforehand.
df_spec = pd.read_csv("/content/churn.csv", usecols=['Gender', 'Age', 'Tenure', 'Balance'])df_spec.head()
The read_csv function allows reading a part of the dataframe in terms of the rows. There are two options. The first one is to read the first n number of rows.
df_partial = pd.read_csv("/content/churn.csv", nrows=5000)df_partial.shape(5000,14)
Using the nrows parameters, we created a dataframe that contains the first 5000 rows of the csv file.
We can also select rows from the end of the file by using the skiprows parameter. Skiprows=5000 means that we will skip the first 5000 rows while reading the csv file.
After creating a dataframe, we may want to draw a small sample to work. We can either use the n parameter or frac parameter to determine the sample size.
n: The number of rows in the sample
frac: The ratio of the sample size to the whole dataframe size
df_sample = df.sample(n=1000)df_sample.shape(1000,10)df_sample2 = df.sample(frac=0.1)df_sample2.shape(1000,10)
The isna function determines the missing values in a dataframe. By using the isna with the sum function, we can see the number of missing values in each column.
df.isna().sum()
There are no missing values.
I’m doing this example to practice the “loc” and “iloc”. These methods select rows and columns based on index or label.
loc: selects with label
iloc: selects with index
Let’s first create 20 random indices to select.
missing_index = np.random.randint(10000, size=20)
We will use these indices to change some values as np.nan (missing value).
df.loc[missing_index, ['Balance','Geography']] = np.nan
There are 20 missing values in the “Balance” and “Geography” columns. Let’s do another example using the indices instead of labels.
df.iloc[missing_index, -1] = np.nan
“-1” is the index of the last column which is “Exited”.
Although we’ve used different representations of columns for loc and iloc, row values have not changed. The reason is that we are using numerical index labels. Thus, both label and index for a row are the same.
The number of missing values have changed:
The fillna function is used to fill the missing values. It provides many options. We can use a specific value, an aggregate function (e.g. mean), or the previous or next value.
For the geography column, I will use the most common value.
mode = df['Geography'].value_counts().index[0]df['Geography'].fillna(value=mode, inplace=True)
Similarly, for the balance column, I will use the mean of the column to replace missing values.
avg = df['Balance'].mean()df['Balance'].fillna(value=avg, inplace=True)
The method parameter of the fillna function can be used to fill missing values based on the previous or next value in a column (e.g. method=’ffill’). It can be pretty useful for sequential data (e.g. time series).
Another way to handle missing values is to drop them. There are still missing values in the “Exited” column. The following code will drop rows that have any missing value.
df.dropna(axis=0, how='any', inplace=True)
The axis=1 is used to drop columns with missing values. We can also set a threshold value for the number of non-missing values required for a column or row to have. For instance, thresh=5 means that a row must have at least 5 non-missing values not to be dropped. The rows that have 4 or fewer missing values will be dropped.
The dataframe does not have any missing values now.
df.isna().sum().sum()0
In some cases, we need the observations (i.e. rows) that fit some conditions. For instance, the below code will select customers who live in France and have churned.
france_churn = df[(df.Geography == 'France') & (df.Exited == 1)]france_churn.Geography.value_counts()France 808
The query function provides a more flexible way of passing the conditions. We can describe them with strings.
df2 = df.query('80000 < Balance < 100000')
Let’s confirm the result by plotting a histogram of the balance column.
df2['Balance'].plot(kind='hist', figsize=(8,5))
The condition might have several values. In such cases, it is better to use the isin method instead of separately writing the values.
We just pass a list of the desired values.
df[df['Tenure'].isin([4,6,9,10])][:3]
Pandas Groupby function is a versatile and easy-to-use function that helps to get an overview of the data. It makes it easier to explore the dataset and unveil the underlying relationships among variables.
We will do several examples of the groupby function. Let’s start with a simple one. The code below will group the rows based on the geography-gender combinations and then give us the average churn rate for each group.
df[['Geography','Gender','Exited']].groupby(['Geography','Gender']).mean()
The agg function allows applying multiple aggregate functions on the groups. A list of the functions is passed as an argument.
df[['Geography','Gender','Exited']].groupby(['Geography','Gender']).agg(['mean','count'])
We can see both the count of the observations (rows) in each group and the average churn rate.
We do not have to apply the same function to all columns. For instance, we may want to see the average balance and the total number of churned customers in each country.
We will pass a dictionary that indicates which functions are to be applied to which columns.
df_summary = df[['Geography','Exited','Balance']].groupby('Geography')\.agg({'Exited':'sum', 'Balance':'mean'})df_summary.rename(columns={'Exited':'# of churned customers', 'Balance':'Average Balance of Customers'},inplace=True)df_summary
I have also renamed the columns.
Edit: Thanks Ron for the heads-up in the comment section. The NamedAgg function allows renaming the columns in the aggregation. The syntax is as follows:
df_summary = df[['Geography','Exited','Balance']].groupby('Geography')\.agg( Number_of_churned_customers = pd.NamedAgg('Exited', 'Sum'), Average_balance_of_customers = pd.NamedAgg('Balance', 'Mean'))
As you may have noticed, the index of the dataframes that the groupby returns consist of the group names. We can change it by resetting the index.
df_new = df[['Geography','Exited','Balance']]\.groupby(['Geography','Exited']).mean().reset_index()df_new
Edit: Thanks Ron for the heads-up in the comment section. If we set the as_index parameter of the groupby function as False, the group names will not be used as the index.
In some cases, we need to reset the index and get rid of the original index at the same time. Consider a case where draw a sample from a dataframe. The sample will keep the index of the original dataframe so we want to reset it.
df[['Geography','Exited','Balance']].sample(n=6).reset_index()
The index is reset but the original is kept as a new column. We can drop it while resetting the index.
df[['Geography','Exited','Balance']]\.sample(n=6).reset_index(drop=True)
We can set any column in the dataframe as the index.
df_new.set_index('Geography')
We can add a new column to a dataframe as follows:
group = np.random.randint(10, size=6)df_new['Group'] = groupdf_new
But the new column is added at the end. If you want to put the new column at a specific position, you can use the insert function.
df_new.insert(0, 'Group', group)df_new
The first parameter is the index of the location, the second one is the name of the column, and the third one is the value.
It is used to replace values in rows or columns based on a condition. The default replacement value is NaN but we can also specify the value to be put as a replacement.
Consider the dataframe in the previous step (df_new). We want to set the balance to 0 for customers who belong to a group that is less than 6.
df_new['Balance'] = df_new['Balance'].where(df_new['Group'] >= 6, 0)df_new
The values that fit the specified condition remain unchanged and the other values are replaced with the specified value.
20. The rank function
It assigns a rank to the values. Let’s create a column that ranks the customers according to their balances.
df_new['rank'] = df_new['Balance'].rank(method='first', ascending=False).astype('int')df_new
The method parameter specifies how to handle the rows that have the same values. ‘First’ means they are ranked according to their order in the array (i.e. column).
It comes in handy when working with categorical variables. We may need to check the number of unique categories.
We can either check the size of the series returned by the value counts function or use the nunique function.
It is simply done by the memory_usage function.
The values show how much memory is used in bytes.
By default, categorical data is stored with the object data type. However, it may cause unnecessary memory usage especially when the categorical variable has low cardinality.
Low cardinality means that a column has very few unique values compared to the number of rows. For instance, the geography column has 3 unique values and 10000 rows.
We can save memory by changing its data type as “category”.
df['Geography'] = df['Geography'].astype('category')
The memory consumption of the geography column is reduced by almost 8 times.
The replace function can be used to replace values in a dataframe.
The first parameter is the value to be replaced and the second one is the new value.
We can use a dictionary to do multiple replacements.
Pandas is not a data visualization library but it makes it pretty simple to create basic plots.
I find it easier to create basic plots with Pandas instead of using an additional data visualization library.
Let’s create a histogram of the balance column.
df['Balance'].plot(kind='hist', figsize=(10,6), title='Customer Balance')
I do not want to go into detail about plotting since pandas is not a data visualization library. However, the plot function is capable of creating many different plots such as line, bar, kde, area, scatter, and so on.
Pandas may display an excessive amount of decimal points for floats. We can easily adjust it using the round function.
df_new.round(1) #number of desired decimal points
Instead of adjusting the display options manually at each time, we can change the default display options for various parameters.
get_option: Returns what the current option is
set_option: Changes the option
Let’s change the display option for decimal points to 2.
pd.set_option("display.precision", 2)
Some other options you may want to change are:
max_colwidth: Maximum number of characters displayed in columns
max_columns: Maximum number of columns to display
max_rows: Maximum number of rows to display
The pct_change is used to calculate the percent change through the values in a series. It is useful when calculating the percentage of change in a time series or sequential array of elements.
The change from the first element (4) to the second element (5) is %25 so the second value is 0.25.
We may need to filter observations (rows) based on textual data such as the name of customers. I’ve added made-up names to the df_new dataframe.
Let’s select the rows in which the customer name starts with ‘Mi’.
We will use the startswith method of the str accessor.
df_new[df_new.Names.str.startswith('Mi')]
The endswith function does the same filtering based on the characters at the end of strings.
There are lots of operations that pandas can do with strings. I have a separate article on this topic if you’d like to read further.
towardsdatascience.com
We can achieve this by using the Style property which returns a styler object It provides many options for formatting and displaying dataframes. For instance, we can highlight the minimum or maximum values.
It also allows for applying custom styling functions.
df_new.style.highlight_max(axis=0, color='darkgreen')
I have a detailed post on styling pandas dataframes if you’d like to read further.
towardsdatascience.com
We have covered a great deal of the functions and methods for data analysis. There are, of course, a lot more offered by pandas but it is impossible to cover all in one article.
As you keep using pandas for your data analysis tasks, you may discover new functions and methods. As with any other subject, practice makes perfect.
I’d like to share two other posts that kind of cover different operations than the ones in this post.
20 Points to Master Pandas Time Series Analysis
Pandas Dtype-Specific Operations: Accessors
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 346,
"s": 171,
"text": "Pandas is a widely-used data analysis and manipulation library for Python. It provides numerous functions and methods that expedite the data analysis and preprocessing steps."
},
{
"code": null,
"e": 573,
"s": 346,
"text": "Due to its ... |
Video Prediction using Deep Learning | Towards Data Science | In this guide, I will show you how to code a Convolutional Long Short-Term Memory (ConvLSTM) using an autoencoder (seq2seq) architecture for frame prediction using the MovingMNIST dataset (but custom datasets can also easily be integrated).
This method was originally used for precipitation forecasting at NIPS in 2015, and has been extended extensively since then with methods such as PredRNN, PredRNN++, Eidetic 3D LSTM, and so on...
We also use the pytorch-lightning framework, which is great for removing a lot of the boilerplate code and easily integrate 16-bit training and multi-GPU training.
Before starting, we will briefly outline the libraries we are using:
python=3.6.8torch=1.1.0torchvision=0.3.0pytorch-lightning=0.7.1matplotlib=3.1.3tensorboard=1.15.0a20190708
Download the dataloader script from the following repo tychovdo/MovingMNIST.This dataset was originally developed and described here, and it contains 10000 sequences each of length 20 with frame size 64 x 64 showing 2 digits moving in various trajectories (and overlapping).
Something to note beforehand is the inherent randomness of the digit trajectories. We do expect that this will become a major hurdle for the model we are about to describe, and we also note that newer approaches such as Variational Autoencoders might be a more efficient model for this type of task.
The specific model type we will be using is called a seq2seq model, which is typically used for NLP or time-series tasks (it was actually implemented in the Google Translate engine in 2016).
The original papers on seq2seq are Sutskever et al., 2014 and Cho et al., 2014.
In its simplest configuration, the seq2seq model takes a sequence of items as input (such as words, word embeddings, letters, etc.) and outputs another sequence of items. For machine translation, the input could be a sequence of Spanish words and the output would be the English translation.
We can separate the seq2seq model into three parts, which are
a) Encoder (encodes the input list)b) Encoder embedding vector (the final embedding of the entire input sequence)c) Decoder (decodes the embedding vector into the output sequence)
For our machine translation example, this would mean:
Encoder takes the Spanish sequence as input by processing each word sequentially
The encoder outputs an embedding vector as the final representation of our input
Decoder takes the embedding vector as input and then outputs the English translation sequence
Hopefully part a) and part c) are somewhat clear to you. Arguably the most tricky part in terms of intuition for the seq2seq model is the encoder embedding vector. How do you define this vector exactly?
Before you move any further, I highly recommend the following excellent blog post on RNN/LSTM. Understanding LSTM’s intimately is an essential prerequisite for most seq2seq models!
Here are the equations for the regular LSTM cell:
where ∘ denotes the Hadamard product.
So let's assume you fully understand what an LSTM cell is and how cell states and hidden states work. Typically the encoder and decoder in seq2seq models consist of LSTM cells, such as the following figure:
The LSTM Encoder consists of 4 LSTM cells and the LSTM Decoder consists of 4 LSTM cells.
Each input (word or word embedding) is fed into a new encoder LSTM cell together with the hidden state (output) from the previous LSTM cell
The hidden state from the final LSTM encoder cell is (typically) the Encoder embedding. It can also be the entire sequence of hidden states from all encoder LSTM cells (note — this is not the same as attention)
The LSTM decoder uses the encoder state(s) as input and processes these iteratively through the various LSTM cells to produce the output. This can be unidirectional or bidirectional
Several extensions to the vanilla seq2seq model exist; the most notable being the Attention module.
Having discussed the seq2seq model, let's turn our attention to the task of frame prediction!
Frame prediction is inherently different from the original tasks of seq2seq such as machine translation. This is due to the fact, that RNN modules (LSTM) in the encoder and decoder use fully-connected layers to encode and decode word embeddings (which are represented as vectors).
Once we are dealing with frames we have 2D tensors, and to encode and decode these in a sequential nature we need an extension of the original LSTM seq2seq models.
This is where Convolutional LSTM (ConvLSTM) comes in. Presented at NIPS in 2015, ConvLSTM modifies the inner workings of the LSTM mechanism to use the convolution operation instead of simple matrix multiplication. Let's write our new equations for the ConvLSTM cells:
∗ denotes the convolution operation and ∘ denotes the Hadamard product like before.
Can you spot the subtle difference between these equations and regular LSTM? We simply replace the multiplications in the four gates between
a) weight matrices and input (Wx xt with Wx ∗ Xt) andb) weight matrices and previous hidden state (Wh ht−1 with Wh ∗ Ht−1).Otherwise, everything remains the same.
If you prefer not to dive into the above equations, the primary thing to note is the fact that we use convolutions (kernel) to process our input images to derive feature maps rather than vectors derived from fully-connected layers.
One of the most difficult things when designing frame prediction models (with ConvLSTM) is defining how to produce the frame predictions. We list two methods here (but others do also exist):
Predict the next frame and feed it back into the network for a number of n steps to produce n frame predictions (autoregressive)Predict all future time steps in one-go by having the number of ConvLSTM layers l be equal to the number of n steps. Thus, we can simply use the output from each decoder LSTM cell as our predictions.
Predict the next frame and feed it back into the network for a number of n steps to produce n frame predictions (autoregressive)
Predict all future time steps in one-go by having the number of ConvLSTM layers l be equal to the number of n steps. Thus, we can simply use the output from each decoder LSTM cell as our predictions.
In this tutorial, we will focus on number 1 — especially since it can produce any number of predictions in the future without having to change the architecture completely. Furthermore, if we are to predict many steps in the future option 2 becomes increasingly computationally expensive.
For our ConvLSTM implementation, we use the PyTorch implementation from ndrplz
It looks as follows:
Hopefully, you can see how the equations defined earlier are written in the above code for the forward pass.
The specific architecture we use looks as follows:
We use two ConvLSTM cells for both the encoder and the decoder (encoder_1_convlstm, encoder_2_convlstm, decoder_1_convlstm, decoder_2_convlstm).
Our final ConvLSTM cell (decoder_2convlstm) outputs _nf feature maps for each predicted frame (12, 10, 64, 64, 64).
As we are essentially doing regression (predicting pixel values), we need to transform these feature maps into actual predictions similar to what you do in classical image classification.
To achieve this we implement a 3D-CNN layer. The 3D CNN layer does the following:
Takes as input (nf, width, height) for each batch and time_stepIterate over all n predicted frames using 3D kernelOutputs one channel (1, width, height) per image — i.e., the predicted pixel values
Takes as input (nf, width, height) for each batch and time_step
Iterate over all n predicted frames using 3D kernel
Outputs one channel (1, width, height) per image — i.e., the predicted pixel values
Finally, as we have transformed the pixel values into [0, 1] we use a sigmoid function to turn our 3D CNN activations into [0, 1].
And that is basically it!
Now we define the python implementation for the seq2seq model:
Maybe you are already aware of the excellent library pytorch-lightning, which essentially takes all the boiler-plate engineering out of machine learning when using PyTorch, such as the following commands: optimizer.zero_grad(), optimizer.step().It also standardizes training modules and enables easy multi-GPU functionality and mixed-precision training for Volta architecture GPU cards.
There is so much functionality available in pytorch-lightning, and I will try to demonstrate the workflow I have created, which I think works fairly well.
Most of the functionality of class MovingMNISTLightning is fairly self-explanatory. Here is the overall workflow:
We instantiate our class and define all the relevant parametersWe take a training_step (for each batch)Create a prediction y_hatCalculate the MSE loss —Save a visualization of the prediction with input and ground truth every 250 global step into tensorboardSave the learning rate and loss for each batch into tensorboard
We instantiate our class and define all the relevant parameters
We take a training_step (for each batch)
Create a prediction y_hat
Calculate the MSE loss —
Save a visualization of the prediction with input and ground truth every 250 global step into tensorboard
Save the learning rate and loss for each batch into tensorboard
When we actually run our main.py script we can define several relevant parameters. For example, if we want to run with 2 GPUs, mixed-precision and batch_size = 16 we simply type:
python main.py --n_gpus=2 --use_amp=True --batch_size=16
Feel free to experiment with various configurations!
When we run the main.py script we automatically spin up a tensorboard session using multiprocessing, and here you can track the performance of our model iteratively and also see the visualization of our predictions every 250 global step.
Thanks for reading this article! I hope you enjoyed it!
Please reach out either here or on Twitter if you have any questions or comments regarding the above paper. You can also find more tutorials on my webpage https://holmdk.github.io/. | [
{
"code": null,
"e": 413,
"s": 172,
"text": "In this guide, I will show you how to code a Convolutional Long Short-Term Memory (ConvLSTM) using an autoencoder (seq2seq) architecture for frame prediction using the MovingMNIST dataset (but custom datasets can also easily be integrated)."
},
{
... |
How to clear the global variables in Postman? | We can clear the Global variables in Postman at runtime with the help of scripts. This is done with the help of the pm.* function. The script to clear the Global variables can be incorporated either in the Tests or Pre-Request Script tab
To clear the Global variable, the script should be −To clear the Global variable, the script should be −
pm.globals.unset('<name of Global variable>')
Let us try to clear the Global variable url.
Step1 − Add the below script in the Pre-request Script tab −
pm.globals.unset('url')
Step2 − Click on Send to execute a request.
Step3 − After the Response is received, click on the eye icon to the right upper corner of the Postman application. Now, it no longer shows the Global variable url which was previously available. | [
{
"code": null,
"e": 1300,
"s": 1062,
"text": "We can clear the Global variables in Postman at runtime with the help of scripts. This is done with the help of the pm.* function. The script to clear the Global variables can be incorporated either in the Tests or Pre-Request Script tab"
},
{
"... |
Curzon Numbers - GeeksforGeeks | 05 Nov, 2021
Given an integer N, check whether the given number is a Curzon Number or not.
A number N is said to be a Curzon Number if 2N + 1 is divisible by 2*N + 1.
Example:
Input: N = 5 Output: Yes Explanation: 2^5 + 1 = 33 and 2*5 + 1 = 11 Since 11 divides 33, so 5 is a curzon number.
Input: N = 10 Output: No Explanation: 2^10 + 1 = 1025 and 2*10 + 1 = 21 1025 is not divisible by 21, so 10 is not a curzon number.
Approach: The approach is to compute and check if 2N + 1 is divisible by 2*N + 1 or not.
First find the value of 2*N + 1
Then find the value of 2N + 1
Check if the second value is divisible by the first value, then it is a Curzon Number, else not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to check if a number// is a Curzon number or notvoid checkIfCurzonNumber(int N){ long int powerTerm, productTerm; // Find 2^N + 1 powerTerm = pow(2, N) + 1; // Find 2*N + 1 productTerm = 2 * N + 1; // Check for divisibility if (powerTerm % productTerm == 0) cout << "Yes\n"; else cout << "No\n";} // Driver codeint main(){ long int N = 5; checkIfCurzonNumber(N); N = 10; checkIfCurzonNumber(N); return 0;}
// Java implementation of the approachimport java.io.*;import java.util.*; class GFG { // Function to check if a number// is a Curzon number or notstatic void checkIfCurzonNumber(long N){ double powerTerm, productTerm; // Find 2^N + 1 powerTerm = Math.pow(2, N) + 1; // Find 2*N + 1 productTerm = 2 * N + 1; // Check for divisibility if (powerTerm % productTerm == 0) System.out.println("Yes"); else System.out.println("No");} // Driver codepublic static void main(String[] args){ long N = 5; checkIfCurzonNumber(N); N = 10; checkIfCurzonNumber(N);}} // This code is contributed by coder001
# Python3 implementation of the approach # Function to check if a number# is a Curzon number or notdef checkIfCurzonNumber(N): powerTerm, productTerm = 0, 0 # Find 2^N + 1 powerTerm = pow(2, N) + 1 # Find 2*N + 1 productTerm = 2 * N + 1 # Check for divisibility if (powerTerm % productTerm == 0): print("Yes") else: print("No") # Driver codeif __name__ == '__main__': N = 5 checkIfCurzonNumber(N) N = 10 checkIfCurzonNumber(N) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{ // Function to check if a number// is a curzon number or notstatic void checkIfCurzonNumber(long N){ double powerTerm, productTerm; // Find 2^N + 1 powerTerm = Math.Pow(2, N) + 1; // Find 2*N + 1 productTerm = 2 * N + 1; // Check for divisibility if (powerTerm % productTerm == 0) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver codestatic public void Main (){ long N = 5; checkIfCurzonNumber(N); N = 10; checkIfCurzonNumber(N);}} // This code is contributed by shubhamsingh10
<script> // Javascript implementation of the approach // Function to check if a number// is a Curzon number or notfunction checkIfCurzonNumber(N){ var powerTerm, productTerm; // Find 2^N + 1 powerTerm = Math.pow(2, N) + 1; // Find 2*N + 1 productTerm = 2 * N + 1; // Check for divisibility if (powerTerm % productTerm == 0) { document.write("Yes" + "</br>"); } else { document.write("No"); }} // Driver codevar N = 5;checkIfCurzonNumber(N); N = 10;checkIfCurzonNumber(N); // This code is contributed by Ankita saini </script>
Yes
No
Time complexity: O(log N)
Auxiliary Space: O(1)
mohit kumar 29
coder001
SHUBHAMSINGH10
ankita_saini
rishavmahato348
maths-power
Numbers
Mathematical
School Programming
Write From Home
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Fizz Buzz Implementation
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects | [
{
"code": null,
"e": 24327,
"s": 24299,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 24405,
"s": 24327,
"text": "Given an integer N, check whether the given number is a Curzon Number or not."
},
{
"code": null,
"e": 24481,
"s": 24405,
"text": "A number N i... |
PostgreSQL - Introduction to Stored Procedures - GeeksforGeeks | 24 Feb, 2022
PostgreSQL allows the users to extend the database functionality with the help of user-defined functions and stored procedures through various procedural language elements, which are often referred to as stored procedures.
The store procedures define functions for creating triggers or custom aggregate functions. In addition, stored procedures also add many procedural features e.g., control structures and complex calculation. These allow you to develop custom functions much easier and more effective.
It is possible to call a Procedural code block using the DO command without defining a function or stored procedure.
PostgreSQL categorizes the procedural languages into two main groups:
Safe languages can be used by any users. SQL and PL/pgSQL are safe languages.Sand-boxed languages are only used by superusers because sand-boxed languages provide the capability to bypass security and allow access to external sources. C is an example of a sandboxed language.
Safe languages can be used by any users. SQL and PL/pgSQL are safe languages.
Sand-boxed languages are only used by superusers because sand-boxed languages provide the capability to bypass security and allow access to external sources. C is an example of a sandboxed language.
By default, PostgreSQL supports three procedural languages: SQL, PL/pgSQL, and C. You can also load other procedural languages e.g., Perl, Python, and TCL into PostgreSQL using extensions.
The stored procedures bring many advantages as follows:
Reduce the number of round trips between applications and database servers. All SQL statements are wrapped inside a function stored in the PostgreSQL database server so the application only has to issue a function call to get the result back instead of sending multiple SQL statements and wait for the result between each call.
Increase application performance because the user-defined functions and stored procedures are pre-compiled and stored in the PostgreSQL database server.
Reusable in many applications. Once you develop a function, you can reuse it in any applications.
Besides the advantages of using stored procedures, there are some caveats:
Slowness in software development because stored procedure programming requires specialized skills that many developers do not possess.
Difficult to manage versions and hard to debug.
May not be portable to other database management systems e.g., MySQL or Microsoft SQL Server.
Example:
We will use the following accounts table for the demonstration:
drop table if exists accounts;
create table accounts (
id int generated by default as identity,
name varchar(100) not null,
balance dec(15, 2) not null,
primary key(id)
);
insert into accounts(name, balance)
values('Raju', 10000);
insert into accounts(name, balance)
values('Nikhil', 10000);
The following query will show the table data:
select * from accounts;
That depicts the result as shown below:
The following query creates a stored procedure named transfer that transfers a specified amount of money from one account to another.
create or replace procedure transfer(
sender int,
receiver int,
amount dec
)
language plpgsql
as $$
begin
-- subtracting the amount from the sender's account
update accounts
set balance = balance - amount
where id = sender;
-- adding the amount to the receiver's account
update accounts
set balance = balance + amount
where id = receiver;
commit;
end;$$;
To call a stored procedure, you use the CALL statement as follows:
call stored_procedure_name(argument_list);
Example:
The below statement invokes the transfer stored procedure to transfer $1, 000 from Raju’s account to Nikhil’s account:
call transfer(1, 2, 1000);
The following statement verifies the data in the accounts table after the transfer:
SELECT * FROM accounts;
Output:
mark17
postgreSQL-stored-procedures
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
How to use PostgreSQL Database in Django?
PostgreSQL - Copy Table | [
{
"code": null,
"e": 27634,
"s": 27606,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 27857,
"s": 27634,
"text": "PostgreSQL allows the users to extend the database functionality with the help of user-defined functions and stored procedures through various procedural language ... |
How to Vim. Nifty tips to become a pro Vim coder | by Richard So | Towards Data Science | Learning how to use Vim is kinda intimidating. Correction: it’s very intimidating. You’re essentially learning a different way to edit code, let alone text. Many wrongfully deem it a “waste of time” to pick up Vim.
However, I can testify that Vim has improved my coding efficiency and overall experience in the long run (I’ll explain why in the following sections). I’m not going to shove Vim down anyone’s throat, but I strongly suggest learning it as you continue your journey in programming, data science, or whatnot.
If you are longing to know if you should use Vim and/or who’s it really for, go check out this write up (watch out for the deceptive title!) or watch this YouTube video from the man himself Luke Smith.
With all that said, let's talk in more detail about what Vim really is!
For those who are asking, let me affirm this once more:
Vim is a different way of editing code, let alone text.
Vim works in “modes,” and switching between these changes the function of each key on your keyboard (e.g. pressing the W key unsurprisingly types “ w ” in INSERT mode, but moves your cursor one word forwards in NORMAL mode). This way, your keyboard also acts as an instrument to navigate through your text/code file. In other words, you don’t need your mouse when using Vim.
This is great if you have to constantly switch between editing and traversing through text, which is exactly what we programmers usually do. If you’re a non-Vim coder, you won’t believe how much time you spend reaching your mouse (or trackpad for laptop users) from your keyboard, then moving your cursor, and finally returning back to start typing. (ugh...)
Again, Vim requires some time to get used to, and it’s not an outright replacement for an IDE or something like Visual Studio Code. Yet, it arguably empowers you to edit code faster, and its more basic counterpart (Vi) is the standard terminal text editor for most UNIX-like operating systems.
With that said, let’s head onwards!
I’m not surprised that every single Vim tutorial plugs in vimtutor to start learning this text editor, and I’ll shamelessly do the exact same thing here. There’s no need for playing any “Vim games” (although they are fun) or relying on tools that’ll help you memorize redundant key bindings. Install vimtutor and run through this official Vim tutorial whenever you have around 10–15 minutes to spare. Don’t try memorizing all Vim bindings/shortcuts right off the bat; it’ll come as you continue repeating vimtutor .
NOTE: I suggest that Windows users use WSL (Windows Subsystem for Linux) for access to vimtutor and for using Vim in general. I personally have no experience using gVim on Windows, so I cannot guarantee the true Vim experience there.
Practice makes perfect.
This is the core principle of learning anything new, and Vim is no different. So while you learn Vim through vimtutor, keep on using it.
Use Vim as much as possible. Need to view a text file? Use Vim. Want to make changes to that Python script on the go? Use Vim. Looking to taking some notes? Use Vim. You get the point. And whenever you do, always think to yourself: what is the most efficient (shortest) order of keypresses I should use to accomplish this?
Oh, and cut your habit of using your mouse/trackpad.
Use Vim bindings wherever and whenever you can. Start doing everything the “Vim” way. For instance, if you use a chromium-based browser (Chrome, Brave, Edge) or Firefox, consider Vimium, an extension that ports various Vim movement keybindings (H, J, K, L, etc.) onto your browser.
github.com
If you’re currently using an IDE for development, find a Vim plugin/extension that can emulate Vim bindings for it. PyCharm (or any of Jetbrains’ IDEs) users can use ideavim, while Visual Studio Code (basically an IDE by 2021) has VSCodeVim for its user base.
github.com
github.com
Finally, Jupyterlab users can enable Vim bindings for its integrated text editor and install jupyterlab-vim for full Vim emulation within notebook cells.
github.com
Make sure Vim is mixed in well into your existing workflow. Continue on your revamped Vim lifestyle for a few weeks or so. Within a few sessions on VSCode with Vim emulation, I can testify how much more comfortable it became harnessing its power. (and how glad I was to be freed from my mouse!)
The most useless key on the best location.
This quote basically characterizes the Caps Lock key. Instead, turn Caps Lock into your Escape key! By now, you’ll learn how essential the Escape key is for switching modes in Vim. To maximize efficiency, I highly suggest you make this modification.
Windows and WSL users can use uncap, an executable that turns the Caps Lock key to Escape by default.
github.com
MacOS users are quite lucky: remapping the Caps Lock key is a breeze through System Preferences.
vim.fandom.com
For Linux, StackOverflow and Google are really your best friends. Personally (as an elite Arch Linux user😏), I use setxkbmap to switch Caps Lock as another Escape key, and autorun this following command on startup:
setxkbmap -option caps:escape
After getting used to basic-to-intermediate Vim usage, it’s time to become even more efficient with this tool. Below, I’ve compiled below the most useful/unique Vim commands (on NORMAL mode) I’ve ever learned:
ZZ — save+exit Vim the cool way
zz, zt, zb — move line of your cursor to middle, top, and bottom of your view, respectively
Ctrl+u, Ctrl+d — moves your view up/down half one page
ciw — deletes the word you’re hovering and automatically puts you in INSERT mode (change inside word)
C — deletes from cursor to end of line and puts you in INSERT mode
dt<char> — deletes from your cursor to the next instance of the character you specify (delete to <character>)
~ — toggles the case [upper/lower] on the character hovered or selected (tilde; key below Esc for standard keyboards)
. — repeat your last Vim command (period)
ggvG= — auto-indent the entire file (goto beginning, enter VISUAL mode, go/select to end of file, and indent lines [==] selected)
Again, these might seem overwhelming to you at first. Remember, strive to learn by practice, not memorization. At another perspective, these Vim commands go to show how amazingly powerful this text editor can be without your mouse or any context menu.
Vim is unbelievably powerful, given it doesn’t use any mouse input or context menus.
If you are looking for more Vim command tricks, take a look at this amazing and nerdy 1-hour vimtutor playthrough by Vim Diesel (just kidding, it’s still Luke 😛). He packs a lot of time-saving advice on Vim, so make sure you check it out!
By this time, you’re comfortable enough to use Vim to edit code significantly faster than before. Finally, you can flex your sleek code editing on reddit and your colleagues without ever leaving your home row keys! At this point, you can consider the following:
Install and experiment with Neovim (a refactored fork of Vim for hyper-extensibility and GUI support)
Pimp your Vim on the terminal/command line with Vim-Airline
Try out some popular Vim plugins
With all this said, enjoy a future filled with Vim goodness (and devoid of your mouse/trackpad)! | [
{
"code": null,
"e": 387,
"s": 172,
"text": "Learning how to use Vim is kinda intimidating. Correction: it’s very intimidating. You’re essentially learning a different way to edit code, let alone text. Many wrongfully deem it a “waste of time” to pick up Vim."
},
{
"code": null,
"e": 693... |
Feature Selection Using Regularisation | by Akash Dubey | Towards Data Science | Regularisation consists in adding a penalty to the different parameters of the machine learning model to reduce the freedom of the model and in other words to avoid overfitting. In linear model regularisation, the penalty is applied over the coefficients that multiply each of the predictors. From the different types of regularisation, Lasso or L1 has the property that is able to shrink some of the coefficients to zero. Therefore, that feature can be removed from the model.
In this post I will demonstrate how to select features using the Lasso regularisation classification problem. For classification I will use the Paribas claims dataset from Kaggle.
Importing important libraries
Importing important libraries
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import Lasso, LogisticRegressionfrom sklearn.feature_selection import SelectFromModelfrom sklearn.preprocessing import StandardScaler
2. Loading the dataset
data = pd.read_csv(‘paribas.csv’, nrows=50000)data.shape
data.head()
3. Selecting Numerical Columns
In practice, feature selection should be done after data pre-processing, so ideally, all the categorical variables are encoded into numbers, and then we can assess how deterministic they are of the target, here for simplicity I will use only numerical variables to select numerical columns:
numerics = ['int16','int32','int64','float16','float32','float64']numerical_vars = list(data.select_dtypes(include=numerics).columns)data = data[numerical_vars]data.shape
4. Separating the data into training and tests set
X_train, X_test, y_train, y_test = train_test_split( data.drop(labels=['target', 'ID'], axis=1), data['target'], test_size=0.3, random_state=0)X_train.shape, X_test.shape
5. Scaling the data, as linear models benefits from feature scaling
scaler = StandardScaler()scaler.fit(X_train.fillna(0))
6. Selecting features using Lasso regularisation using SelectFromModel
Here I will do the model fitting and feature selection, altogether in one line of code. First I specify the Logistic Regression model, and I make sure I select the Lasso (L1) penalty.Then I use the selectFromModel object from sklearn, which will select in theory the features which coefficients are non-zero.
sel_ = SelectFromModel(LogisticRegression(C=1, penalty='l1'))sel_.fit(scaler.transform(X_train.fillna(0)), y_train)
7. Visualising features that were kept by the lasso regularisation
sel_.get_support()
In the above output, the output labels are index wise. So Trueis for the features that lasso thought is important (non-zero features) while False is for the features whose weights were shrinked to zero and are not important according to Lasso.
8. Make a list of with the selected features.
selected_feat = X_train.columns[(sel_.get_support())]print('total features: {}'.format((X_train.shape[1])))print('selected features: {}'.format(len(selected_feat)))print('features with coefficients shrank to zero: {}'.format( np.sum(sel_.estimator_.coef_ == 0)))
Number of features which coefficient was shrank to zero :
np.sum(sel_.estimator_.coef_ == 0)
9. Identifying the removed features
removed_feats = X_train.columns[(sel_.estimator_.coef_ == 0).ravel().tolist()]removed_feats
10. Removing the features from training an test set
X_train_selected = sel_.transform(X_train.fillna(0))X_test_selected = sel_.transform(X_test.fillna(0))X_train_selected.shape, X_test_selected.shape
L2 regularisation does not shrink coefficients to zero
# Separating the data into train and test set X_train, X_test, y_train, y_test = train_test_split( data.drop(labels=['target', 'ID'], axis=1), data['target'], test_size=0.3, random_state=0)X_train.shape, X_test.shape
For comparison, I will fit a logistic regression with a Ridge regularisation, and evaluate the coefficients :
l1_logit = LogisticRegression(C=1, penalty='l2')l1_logit.fit(scaler.transform(X_train.fillna(0)), y_train)
Now, Lets count the number of coefficients with zero values :
np.sum(l1_logit.coef_ == 0)
So, Now number of coefficients with zero values is zero. So, now it is clear that Ridge regularisation (L2 Regularisation) does not shrink the coefficients to zero.
As we can see, the logistic regression we used for the Lasso regularisation to remove non-important features from the dataset. Keep in mind that increasing the penalisation c will increase the number of features removed. Therefore, we will need to keep an eye and monitor that we don’t set a penalty too high so that to remove even important features, or too low and then not remove non-important features.
For feature selection using Random forest : | [
{
"code": null,
"e": 649,
"s": 171,
"text": "Regularisation consists in adding a penalty to the different parameters of the machine learning model to reduce the freedom of the model and in other words to avoid overfitting. In linear model regularisation, the penalty is applied over the coefficients ... |
Business Analysis in R. A complete and detailed analysis of a... | by Hamza Rafiq | Towards Data Science | You will find a lot of great articles on people doing analyses of different datasets but it is difficult to find material related to business analysis in R. This was one of the main reasons why I have started this Business Analysis in R series so that I can share some of the useful ways you can analyze your data at work more efficiently. Before we move on, I would recommend that you have a basic understanding of the Tidyverse set of packages in R.
In this dataset, I will try to replicate some of the tasks that I do at work and you will find these really useful. you will get to see how powerful R is compared to Excel.
Loading the following libraries that we will be using for our data munging and analysis
library(tidyverse) ## A set of tools for Data manipulation and visualizationlibrary(lubridate) ## for date time manipulationlibrary(scales) ## Formatting numbers and valueslibrary(hrbrthemes)# For changing ggplot themelibrary(extrafont) # More font options
I use the read_csv function to read in the data. Just copy the path of the file wherever it lies on your machine and replace the ‘\’ with ‘\\’. I always set the trim_ws argument to TRUE in case there is any whitespace in the data. If it is saved as an excel file, you can just the read_excel function from the readxl package and basically follow the same principles
supermarket_sales <- read_csv("C:\\Users\\Hamza\\Downloads\\supermarket_sales - Sheet1.csv",trim_ws = TRUE)
Viewing the data
View() is a very handy function which allows you to look at your data in an excel spreadsheet like format as shown below. I am also going to use the glimpse function to check the datatypes
supermarket_sales %>% View()glimpse(supermarket_sales)
Looks like I need to fix my Date and Time columns and convert them to the right format. I am going to round the Time column to the nearest hour and convert the Date column to a date format. After that, we will create a new column which shows the day of the week.
supermarket_sales <- supermarket_sales %>% mutate(Time=as.POSIXct(Time),Time=hour(Time), Date=mdy(Date),weekday = wday(Date,label = TRUE))
I first changed the Time column to a date-time type and extracted just the hour from it. The mdy function in the Lubridate package allowed me to format the Date column as a date type from which I extracted the weekday
Let's get started with some exploratory data analysis. While we will be uncovering different insights in the data, the main focus here is to give you an understanding of how to get desired results in R. Once you have an understanding on how the code works, you can analyze and explore it any way you want.
We will be plotting some bar charts to get an insight into total sales relative to the day of the week and time
## Creating a summarysales_by_day <- supermarket_sales %>% group_by(weekday) %>% summarise(Total_Sales=sum(Total)) %>% ungroup##Visualizing summary datasales_by_day %>% ggplot(aes(reorder(weekday,Total_Sales),Total_Sales,fill=weekday))+ geom_col(show.legend = FALSE,color="black")+geom_text(aes(label=comma(Total_Sales)),size=3,hjust=1,color="black")+ scale_y_comma()+ scale_fill_brewer(palette = "Paired")+ coord_flip()+ theme_classic()+ labs(title = "Total Sales breakdown by Weekday and Time",x="Hour of the day",y= "Total sales")
## Summarizing by day and hoursales_by_day_hour <- supermarket_sales %>% group_by(weekday,Time) %>% summarise(Total_Sales=sum(Total)) %>% ungroup()## Visualizingsales_by_day_hour %>% mutate(Time=fct_reorder(Time,Total_Sales)) %>% ggplot(aes(Time,Total_Sales,fill=weekday))+ geom_col(show.legend = FALSE,color="black")+ geom_text(aes(label=comma(Total_Sales)),size=3,hjust=1,color="black")+ scale_y_comma()+ scale_fill_brewer(palette = "Paired")+ facet_wrap(~weekday,scales="free_y")+ coord_flip()+ theme_classic()+ labs(title = "Total Sales breakdown by Weekday and Time",x="Hour of the day",y= "Total sales")
We will now explore how the sales have changed over time for the different genders.
supermarket_sales %>% group_by(Monthly=floor_date(Date,unit = "1 weeks"),Gender) %>% summarise(Total_Sales=sum(Total)) %>% ggplot(aes(Monthly,Total_Sales))+ geom_line(aes(color=Gender),size=1)+ theme_light()+ scale_y_comma()+ labs(title = "Total Sales over time by Gender",subtitle = "Sales for men increased over time",y="Total Sales",x="")
R has some really powerful data filtering options that other tools like Excel do not have. For example, I want to filter for sales that are greater than the average sale of women.
supermarket_sales %>% filter(Total > mean(Total[Gender=="Female"]))
You can even take this further. Lets filter for sales that are greater than the average sale of health and beauty products sold to females.
supermarket_sales %>% filter(Total > mean(Total[Gender=="Female"&`Product line`=="Health and beauty"]))
It is pretty simple. All I had to was add an additional filter context for Product line when calculating the mean.
Sometimes you do not know the exact strings in your character based columns and it can be a real pain to type each one specifically. This is where you can use regular expressions to make things easier.
supermarket_sales %>% filter(str_detect(`Product line`,regex("sport|beauty",ignore_case = TRUE)))
Basically, I am filtering for data which contains the following strings in the Product line column. There is also a negate argument which you can set to TRUE and it will only show results that do not contain these strings.
supermarket_sales %>% filter(str_detect(`Product line`,regex("sport|beauty",ignore_case = TRUE),negate = TRUE))
Group by and Summarizing
This is probably the functions that you will be using the most. You might have seen a lot of tutorials in R where people use these functions but they only show the basics like sum, mean, or count. But in reality, you have to calculate a lot of conditional calculation that I have rarely seen any tutorial cover. I will start with a basic calculation then move to conditional calculations.
Let's take a look at our sales by city.
supermarket_sales %>% group_by(City) %>% summarise(Total_Sales= sum(Total)) %>% arrange(desc(Total_Sales))
This is a simple calculation. I just grouped the data by city and calculated the sum of the Total sales and arranged by the largest sale.
Now if we wanted to calculate sales in Branch A for each city, this is how we will do it.
supermarket_sales %>% group_by(City) %>% summarise(Total_Sales= sum(Total[Branch=="A"])) %>% arrange(desc(Total_Sales))
We use the [] to add a filter context, the same way we filtered our data previously. This is how I calculate all my conditional calculations. Let's do another one for different products and payment types
supermarket_sales %>% group_by(City) %>% summarise(Total_Sales= sum(Total[Payment %in%c("Cash","Credit card")& str_detect(`Product line`,regex("sport|beauty",ignore_case = TRUE))])) %>% arrange(desc(Total_Sales))
This might seem a little complicated but when we break it down, it is pretty simple. I did a conditional sum of where Payments were equal to Cash or Credit card and products that contained sport or beauty in their name. I used str_detect, combined with regex as before to get the products I wanted because I couldn't be bothered with typing their long names.
The possibilities with these conditional calculations are endless and I use them at work all the time. Sometimes you also have to make time-based calculations at work. For example, Sales this YTD and Sales same period last year. We can do that by following the same principles as above combined with the help of the Lubridate package which allows us to manipulate date values.
supermarket_sales %>% group_by(City) %>% summarise(Total_Sales= sum(Total[Date %within% interval("2019-01-01","2019-03-31")]), Same_period_LY=sum(Total[Date %within% interval("2018-01-01","2018-03-31")]))
Here, I used the %within% and Interval functions to specify which dates I want to aggregate by. Don't worry if there is no data for 2018 as there is none but I just wanted you to understand the concept. I really like these “time intelligence” calculations because these functions allow me to be as specific as I want.
These were some of the functions I use at work for analyzing data. I will keep continuing my Business Analysis in R series to share some really cool and useful ways on how you can analyze your business data more efficiently in R. | [
{
"code": null,
"e": 624,
"s": 172,
"text": "You will find a lot of great articles on people doing analyses of different datasets but it is difficult to find material related to business analysis in R. This was one of the main reasons why I have started this Business Analysis in R series so that I c... |
Different ways to format long with Java System.out.format | The System.out.format is used in Java to format output. Here, let’s say the following is our long.
long val = 787890;
To format, we have considered the following that justifies the output.
System.out.format("%d%n", val);
System.out.format("%9d%n", val);
System.out.format("%+9d%n", val);
System.out.format("%08d%n", val);
System.out.format("%,9d%n", val);
The following is the complete example that displays the difference in output as well.
Live Demo
import java.util.Locale;
public class Demo {
public static void main(String []args) {
long val = 787890;
System.out.format("%d%n", val);
System.out.format("%9d%n", val);
System.out.format("%+9d%n", val);
System.out.format("%08d%n", val);
System.out.format("%,9d%n", val);
}
}
Here is the output. You can easily notice the differences in format.
787890
787890
+787890
00787890
787,890 | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "The System.out.format is used in Java to format output. Here, let’s say the following is our long."
},
{
"code": null,
"e": 1181,
"s": 1161,
"text": "long val = 787890;\n"
},
{
"code": null,
"e": 1252,
"s": 1181,
... |
Using Lambda Function with Scheduled Events | Scheduled events are suppose to happen at regular intervals based on a rule set. Scheduled events are used to execute Lambda function after an interval which is defined in cloudwatch services. They are best used for working on cron jobs along with AWS Lambda. This chapter will explain with simple example how to send mail after every 5 minutes using scheduled events and AWS Lambda.
The requirements for using Lambda function with Scheduled events are as follows −
Verify email id using AWS SES
Create Role to use AWS SES, Cloudwatch and AWS Lambda
Create Lambda Function to send email
Add rule for scheduled events from AWS CloudWatch
The example that we are going to consider will add CloudWatch event to the AWS Lambda function. Cloudwatch will trigger AWS Lambda based on the time pattern attached to it. For Example, in the example below we have used 5 minutes as the trigger. It means for every 5 minutes, AWS Lambda will be triggered and AWS Lambda will send mail whenever triggered.
The basic block diagram for the same is shown below −
Log in to AWS and go to AWS SES service as shown below −
Now, click Simple Email Service as shown −
Click Email Addresses on left side as shown −
It displays a button Verify a New Email Address. Click it.
Enter Email Address you want to verify. Click Verify This Email Address button. You will receive mail from AWS on that email id with email subject: Amazon Web Services – Email Address Verification Request in region US East (N. Virginia)
Click the link given in the mail to verify email address. Once verified, it will display the email id as follows −
You can also create a role which gives permission to use the services. For this, go to IAM and select Role. Add the required policies and create the role. Observe that the role created here is events with lambda.
You will have to follow the steps to create Lambda function using runtime as nodejs.
Now, add trigger to Lambda as shown −
Add details to CloudWatch Events Trigger as shown below −
Note that the event will be triggered after every 5 minutes as per the rule trigger created.
The Lambda code for sending an email is given below −
var aws = require('aws-sdk');
var ses = new aws.SES({
region: 'us-east-1'
});
exports.handler = function(event, context, callback) {
var eParams = {
Destination: {
ToAddresses: ["xxxxxxxt12@gmail.com"]
},
Message: {
Body: {
Text: {
Data: "this mail comes from aws lambda event scheduling"
}
},
Subject: {
Data: "Event scheduling from aws lambda"
}
},
Source: "coxxxxxx@gmail.com"
};
console.log('===SENDING EMAIL===');
var email = ses.sendEmail(eParams, function(err, data) {
if (err) console.log(err);
else {
console.log("===EMAIL SENT===");
console.log("EMAIL CODE END");
console.log('EMAIL: ', email);
context.succeed(event);
callback(null, "email is send");
}
});
};
Now, we need the AWS SES service. You can add this using the code shown as follows −
var aws = require('aws-sdk');
var ses = new aws.SES({
region: 'us-east-1'
});
To send mail from nodejs, we have created eParams object which has details like the example mail, to mail id and the body with message as follows −
var eParams = {
Destination: {
ToAddresses: ["xxxxxxxx12@gmail.com"]
},
Message: {
Body: {
Text: {
Data: "this mail comes from aws lambda event scheduling"
}
},
Subject: {
Data: "Event scheduling from aws lambda"
}
},
Source: "coxxxxxx@gmail.com"
};
The Lambda code to send email is as follows −
var email = ses.sendEmail(eParams, function(err, data) {
if (err) console.log(err);
else {
console.log("===EMAIL SENT===");
console.log("EMAIL CODE END");
console.log('EMAIL: ', email);
context.succeed(event);
callback(null, "email is send");
}
});
Now, let us save this Lambda function and check the email id for mails. The screenshot shown below shows that the mail is sent from AWS Lambda after every 5 minutes.
35 Lectures
7.5 hours
Mr. Pradeep Kshetrapal
30 Lectures
3.5 hours
Priyanka Choudhary
44 Lectures
7.5 hours
Eduonix Learning Solutions
51 Lectures
6 hours
Manuj Aggarwal
41 Lectures
5 hours
AR Shankar
14 Lectures
1 hours
Zach Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2790,
"s": 2406,
"text": "Scheduled events are suppose to happen at regular intervals based on a rule set. Scheduled events are used to execute Lambda function after an interval which is defined in cloudwatch services. They are best used for working on cron jobs along with AWS L... |
Static blocks in Java with example | The static block executes when classloader loads the class. A static block is invoked before main()
method. Let us see an example −
Live Demo
class Demo{
static int val_1;
int val_2;
static{
val_1 = 67;
System.out.println("The static block has been called.");
}
}
public class Main{
public static void main(String args[]){
System.out.println(Demo.val_1);
}
}
The static block has been called.
67
A class named Demo contains a static integer value and a normal integer value. In a static block, a
value is defined, and in the main class, an instance of the Demo class is created and the static integer
is accessed from there. | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "The static block executes when classloader loads the class. A static block is invoked before main()\nmethod. Let us see an example −"
},
{
"code": null,
"e": 1205,
"s": 1194,
"text": " Live Demo"
},
{
"code": null,
"e": 1... |
How to download any file and save it to the desired location using Selenium Webdriver? | We can download any file and save it to the desired location with Selenium. This can be done by creating an instance of the FirefoxOptions class. Then with the help of the addPreference method, we have to set the browser preferences.
We shall also specify the path where the file has to be downloaded with the help of the addPreference method.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class FileDwnload{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
// create object of FirefoxOptions class
FirefoxOptions profile = new FirefoxOptions();
// adding browser preferences with addPreference method
profile.addPreference("browser.download.folderList", 2);
// location of downloaded file
profile.addPreference("browser.download.dir", "C:\\Users\\ghs6kor\\Documents\\Download");
profile.addPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x-msexcel,application/excel," + "application/x-excel,application/vnd.ms-excel," + "image/png,image/jpeg,text/html,text/plain," + "application/msword,application/xml");
profile.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel," + "application/excel," + "application/x-excel," +"application/vnd.ms- excel,image/png,image/jpeg,text/html," +"text/plain,application/msword,application/xml");
profile.addPreference("browser.helperApps.alwaysAsk.force", false);
profile.addPreference
("browser.download.manager.alertOnEXEOpen", false);
profile.addPreference("browser.download.manager.focusWhenStarting", false);
profile.addPreference("browser.download.manager.useWindow", false);
profile.addPreference("browser.download.manager.showAlertOnComplete", false);
profile.addPreference("browser.download.manager.closeWhenDone", false);
// connecting browser options to webdriver
WebDriver driver = new FirefoxDriver(profile);
driver.get("https://the-internet.herokuapp.com/download");
//maximize window
driver.manage().window().maximize();
// identify element and start download
driver.findElement(By.linkText("xls-sample1.xls")).click();
}
}
Also, the file gets downloaded at the specified location. | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "We can download any file and save it to the desired location with Selenium. This can be done by creating an instance of the FirefoxOptions class. Then with the help of the addPreference method, we have to set the browser preferences."
},
{
"code... |
How to return an array from a method in Java? | We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class ReturningAnArray {
public int[] createArray() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created:: ");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
return myArray;
}
public static void main(String args[]) {
ReturningAnArray obj = new ReturningAnArray();
int arr[] = obj.createArray();
System.out.println("Array created is :: "+Arrays.toString(arr));
}
}
Enter the size of the array that is to be created::
5
Enter the elements of the array ::
23
47
46
58
10
Array created is :: [23, 47, 46, 58, 10] | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array."
},
{
"code": null,
"e": 1266,
"s": 1255,
... |
Extract the month and year in the following format: “mm-yyyy” (month year) along with all columns in MySQL? | For month and year in a specific format, use DATE_FORMAT() along with STR_TO_DATE(). Let us first create a table −
mysql> create table DemoTable1931
(
ShippingDate varchar(40)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1931 values('10-11-2017');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('31-01-2019');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('02-02-2018');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('10-06-2013');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1931;
This will produce the following output −
+--------------+
| ShippingDate |
+--------------+
| 10-11-2017 |
| 31-01-2019 |
| 02-02-2018 |
| 10-06-2013 |
+--------------+
4 rows in set (0.00 sec)
Following is the query to extract the month and year in the format “mm-yyyy”, along with all columns −
mysql> select date_format(str_to_date(ShippingDate,'%d-%m-%Y'),'%m-%Y') from DemoTable1931;
This will produce the following output −
+-----------------------------------------------------------+
| date_format(str_to_date(ShippingDate,'%d-%m-%Y'),'%m-%Y') |
+-----------------------------------------------------------+
| 11-2017 |
| 01-2019 |
| 02-2018 |
| 06-2013 |
+-----------------------------------------------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "For month and year in a specific format, use DATE_FORMAT() along with STR_TO_DATE(). Let us first create a table −"
},
{
"code": null,
"e": 1287,
"s": 1177,
"text": "mysql> create table DemoTable1931\n (\n ShippingDate varchar(40... |
Closest Pair of Points using Divide and Conquer algorithm - GeeksforGeeks | 25 Apr, 2022
We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for distance between two points p and q.The Brute force solution is O(n^2), compute the distance between each pair and return the smallest. We can calculate the smallest distance in O(nLogn) time using Divide and Conquer strategy. In this post, a O(n x (Logn)^2) approach is discussed. We will be discussing a O(nLogn) approach in a separate post.
Algorithm Following are the detailed steps of a O(n (Logn)^2) algorithm. Input: An array of n points P[] Output: The smallest distance between two points in the given array.As a pre-processing step, the input array is sorted according to x coordinates.1) Find the middle point in the sorted array, we can take P[n/2] as middle point. 2) Divide the given array in two halves. The first subarray contains points from P[0] to P[n/2]. The second subarray contains points from P[n/2+1] to P[n-1].3) Recursively find the smallest distances in both subarrays. Let the distances be dl and dr. Find the minimum of dl and dr. Let the minimum be d.
4) From the above 3 steps, we have an upper bound d of minimum distance. Now we need to consider the pairs such that one point in pair is from the left half and the other is from the right half. Consider the vertical line passing through P[n/2] and find all points whose x coordinate is closer than d to the middle vertical line. Build an array strip[] of all such points.
5) Sort the array strip[] according to y coordinates. This step is O(nLogn). It can be optimized to O(n) by recursively sorting and merging. 6) Find the smallest distance in strip[]. This is tricky. From the first look, it seems to be a O(n^2) step, but it is actually O(n). It can be proved geometrically that for every point in the strip, we only need to check at most 7 points after it (note that strip is sorted according to Y coordinate). See this for more analysis.7) Finally return the minimum of d and distance calculated in the above step (step 6)
Implementation Following is the implementation of the above algorithm.
C++
C
Java
Python3
// A divide and conquer program in C++// to find the smallest distance from a// given set of points. #include <bits/stdc++.h>using namespace std; // A structure to represent a Point in 2D planeclass Point{ public: int x, y;}; /* Following two functions are needed for library function qsort().Refer: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ // Needed to sort array of points// according to X coordinateint compareX(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x - p2->x);} // Needed to sort array of points according to Y coordinateint compareY(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->y - p2->y);} // A utility function to find the// distance between two pointsfloat dist(Point p1, Point p2){ return sqrt( (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );} // A Brute Force method to return the// smallest distance between two points// in P[] of size nfloat bruteForce(Point P[], int n){ float min = FLT_MAX; for (int i = 0; i < n; ++i) for (int j = i+1; j < n; ++j) if (dist(P[i], P[j]) < min) min = dist(P[i], P[j]); return min;} // A utility function to find// minimum of two float valuesfloat min(float x, float y){ return (x < y)? x : y;} // A utility function to find the// distance between the closest points of// strip of given size. All points in// strip[] are sorted according to// y coordinate. They all have an upper// bound on minimum distance as d.// Note that this method seems to be// a O(n^2) method, but it's a O(n)// method as the inner loop runs at most 6 timesfloat stripClosest(Point strip[], int size, float d){ float min = d; // Initialize the minimum distance as d qsort(strip, size, sizeof(Point), compareY); // Pick all points one by one and try the next points till the difference // between y coordinates is smaller than d. // This is a proven fact that this loop runs at most 6 times for (int i = 0; i < size; ++i) for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) if (dist(strip[i],strip[j]) < min) min = dist(strip[i], strip[j]); return min;} // A recursive function to find the// smallest distance. The array P contains// all points sorted according to x coordinatefloat closestUtil(Point P[], int n){ // If there are 2 or 3 points, then use brute force if (n <= 3) return bruteForce(P, n); // Find the middle point int mid = n/2; Point midPoint = P[mid]; // Consider the vertical line passing // through the middle point calculate // the smallest distance dl on left // of middle point and dr on right side float dl = closestUtil(P, mid); float dr = closestUtil(P + mid, n - mid); // Find the smaller of two distances float d = min(dl, dr); // Build an array strip[] that contains // points close (closer than d) // to the line passing through the middle point Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(P[i].x - midPoint.x) < d) strip[j] = P[i], j++; // Find the closest points in strip. // Return the minimum of d and closest // distance is strip[] return min(d, stripClosest(strip, j, d) );} // The main function that finds the smallest distance// This method mainly uses closestUtil()float closest(Point P[], int n){ qsort(P, n, sizeof(Point), compareX); // Use recursive function closestUtil() // to find the smallest distance return closestUtil(P, n);} // Driver codeint main(){ Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; int n = sizeof(P) / sizeof(P[0]); cout << "The smallest distance is " << closest(P, n); return 0;} // This is code is contributed by rathbhupendra
// A divide and conquer program in C/C++ to find the smallest distance from a// given set of points. #include <stdio.h>#include <float.h>#include <stdlib.h>#include <math.h> // A structure to represent a Point in 2D planestruct Point{ int x, y;}; /* Following two functions are needed for library function qsort(). Refer: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ // Needed to sort array of points according to X coordinateint compareX(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x - p2->x);}// Needed to sort array of points according to Y coordinateint compareY(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->y - p2->y);} // A utility function to find the distance between two pointsfloat dist(Point p1, Point p2){ return sqrt( (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );} // A Brute Force method to return the smallest distance between two points// in P[] of size nfloat bruteForce(Point P[], int n){ float min = FLT_MAX; for (int i = 0; i < n; ++i) for (int j = i+1; j < n; ++j) if (dist(P[i], P[j]) < min) min = dist(P[i], P[j]); return min;} // A utility function to find a minimum of two float valuesfloat min(float x, float y){ return (x < y)? x : y;} // A utility function to find the distance between the closest points of// strip of a given size. All points in strip[] are sorted according to// y coordinate. They all have an upper bound on minimum distance as d.// Note that this method seems to be a O(n^2) method, but it's a O(n)// method as the inner loop runs at most 6 timesfloat stripClosest(Point strip[], int size, float d){ float min = d; // Initialize the minimum distance as d qsort(strip, size, sizeof(Point), compareY); // Pick all points one by one and try the next points till the difference // between y coordinates is smaller than d. // This is a proven fact that this loop runs at most 6 times for (int i = 0; i < size; ++i) for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) if (dist(strip[i],strip[j]) < min) min = dist(strip[i], strip[j]); return min;} // A recursive function to find the smallest distance. The array P contains// all points sorted according to x coordinatefloat closestUtil(Point P[], int n){ // If there are 2 or 3 points, then use brute force if (n <= 3) return bruteForce(P, n); // Find the middle point int mid = n/2; Point midPoint = P[mid]; // Consider the vertical line passing through the middle point // calculate the smallest distance dl on left of middle point and // dr on right side float dl = closestUtil(P, mid); float dr = closestUtil(P + mid, n-mid); // Find the smaller of two distances float d = min(dl, dr); // Build an array strip[] that contains points close (closer than d) // to the line passing through the middle point Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(P[i].x - midPoint.x) < d) strip[j] = P[i], j++; // Find the closest points in strip. Return the minimum of d and closest // distance is strip[] return min(d, stripClosest(strip, j, d) );} // The main function that finds the smallest distance// This method mainly uses closestUtil()float closest(Point P[], int n){ qsort(P, n, sizeof(Point), compareX); // Use recursive function closestUtil() to find the smallest distance return closestUtil(P, n);} // Driver program to test above functionsint main(){ Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; int n = sizeof(P) / sizeof(P[0]); printf("The smallest distance is %f ", closest(P, n)); return 0;}
import java.text.DecimalFormat;import java.util.Arrays;import java.util.Comparator; // A divide and conquer program in Java// to find the smallest distance from a// given set of points. // A structure to represent a Point in 2D planeclass Point { public int x; public int y; Point(int x, int y) { this.x = x; this.y = y; } // A utility function to find the // distance between two points public static float dist(Point p1, Point p2) { return (float) Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) ); } // A Brute Force method to return the // smallest distance between two points // in P[] of size n public static float bruteForce(Point[] P, int n) { float min = Float.MAX_VALUE; float currMin = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { currMin = dist(P[i], P[j]); if (currMin < min) { min = currMin; } } } return min; } // A utility function to find the // distance between the closest points of // strip of given size. All points in // strip[] are sorted according to // y coordinate. They all have an upper // bound on minimum distance as d. // Note that this method seems to be // a O(n^2) method, but it's a O(n) // method as the inner loop runs at most 6 times public static float stripClosest(Point[] strip, int size, float d) { float min = d; // Initialize the minimum distance as d Arrays.sort(strip, 0, size, new PointYComparator()); // Pick all points one by one and try the next points till the difference // between y coordinates is smaller than d. // This is a proven fact that this loop runs at most 6 times for (int i = 0; i < size; ++i) { for (int j = i + 1; j < size && (strip[j].y - strip[i].y) < min; ++j) { if (dist(strip[i], strip[j]) < min) { min = dist(strip[i], strip[j]); } } } return min; } // A recursive function to find the // smallest distance. The array P contains // all points sorted according to x coordinate public static float closestUtil(Point[] P, int startIndex, int endIndex) { // If there are 2 or 3 points, then use brute force if ((endIndex - startIndex) <= 3) { return bruteForce(P, endIndex); } // Find the middle point int mid = startIndex + (endIndex - startIndex) / 2; Point midPoint = P[mid]; // Consider the vertical line passing // through the middle point calculate // the smallest distance dl on left // of middle point and dr on right side float dl = closestUtil(P, startIndex, mid); float dr = closestUtil(P, mid, endIndex); // Find the smaller of two distances float d = Math.min(dl, dr); // Build an array strip[] that contains // points close (closer than d) // to the line passing through the middle point Point[] strip = new Point[endIndex]; int j = 0; for (int i = 0; i < endIndex; i++) { if (Math.abs(P[i].x - midPoint.x) < d) { strip[j] = P[i]; j++; } } // Find the closest points in strip. // Return the minimum of d and closest // distance is strip[] return Math.min(d, stripClosest(strip, j, d)); } // The main function that finds the smallest distance // This method mainly uses closestUtil() public static float closest(Point[] P, int n) { Arrays.sort(P, 0, n, new PointXComparator()); // Use recursive function closestUtil() // to find the smallest distance return closestUtil(P, 0, n); } } // A structure to represent a Point in 2D planeclass PointXComparator implements Comparator<Point> { // Needed to sort array of points // according to X coordinate @Override public int compare(Point pointA, Point pointB) { return Integer.compare(pointA.x, pointB.x); } } class PointYComparator implements Comparator<Point> { // Needed to sort array of points // according to Y coordinate @Override public int compare(Point pointA, Point pointB) { return Integer.compare(pointA.y, pointB.y); } } public class ClosestPoint { // Driver code public static void main(String[] args) { Point[] P = new Point[]{ new Point(2, 3), new Point(12, 30), new Point(40, 50), new Point(5, 1), new Point(12, 10), new Point(3, 4) }; DecimalFormat df = new DecimalFormat("#.######"); System.out.println("The smallest distance is " + df.format(Point.closest(P, P.length))); } } // This code is contributed by sanjay sharma 1
# A divide and conquer program in Python3# to find the smallest distance from a# given set of points.import mathimport copy# A class to represent a Point in 2D planeclass Point(): def __init__(self, x, y): self.x = x self.y = y # A utility function to find the# distance between two pointsdef dist(p1, p2): return math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)) # A Brute Force method to return the# smallest distance between two points# in P[] of size ndef bruteForce(P, n): min_val = float('inf') for i in range(n): for j in range(i + 1, n): if dist(P[i], P[j]) < min_val: min_val = dist(P[i], P[j]) return min_val # A utility function to find the# distance between the closest points of# strip of given size. All points in# strip[] are sorted according to# y coordinate. They all have an upper# bound on minimum distance as d.# Note that this method seems to be# a O(n^2) method, but it's a O(n)# method as the inner loop runs at most 6 timesdef stripClosest(strip, size, d): # Initialize the minimum distance as d min_val = d # Pick all points one by one and # try the next points till the difference # between y coordinates is smaller than d. # This is a proven fact that this loop # runs at most 6 times for i in range(size): j = i + 1 while j < size and (strip[j].y - strip[i].y) < min_val: min_val = dist(strip[i], strip[j]) j += 1 return min_val # A recursive function to find the# smallest distance. The array P contains# all points sorted according to x coordinatedef closestUtil(P, Q, n): # If there are 2 or 3 points, # then use brute force if n <= 3: return bruteForce(P, n) # Find the middle point mid = n // 2 midPoint = P[mid] #keep a copy of left and right branch Pl = P[:mid] Pr = P[mid:] # Consider the vertical line passing # through the middle point calculate # the smallest distance dl on left # of middle point and dr on right side dl = closestUtil(Pl, Q, mid) dr = closestUtil(Pr, Q, n - mid) # Find the smaller of two distances d = min(dl, dr) # Build an array strip[] that contains # points close (closer than d) # to the line passing through the middle point stripP = [] stripQ = [] lr = Pl + Pr for i in range(n): if abs(lr[i].x - midPoint.x) < d: stripP.append(lr[i]) if abs(Q[i].x - midPoint.x) < d: stripQ.append(Q[i]) stripP.sort(key = lambda point: point.y) #<-- REQUIRED min_a = min(d, stripClosest(stripP, len(stripP), d)) min_b = min(d, stripClosest(stripQ, len(stripQ), d)) # Find the self.closest points in strip. # Return the minimum of d and self.closest # distance is strip[] return min(min_a,min_b) # The main function that finds# the smallest distance.# This method mainly uses closestUtil()def closest(P, n): P.sort(key = lambda point: point.x) Q = copy.deepcopy(P) Q.sort(key = lambda point: point.y) # Use recursive function closestUtil() # to find the smallest distance return closestUtil(P, Q, n) # Driver codeP = [Point(2, 3), Point(12, 30), Point(40, 50), Point(5, 1), Point(12, 10), Point(3, 4)]n = len(P)print("The smallest distance is", closest(P, n)) # This code is contributed# by Prateek Gupta (@prateekgupta10)
Output:
The smallest distance is 1.414214
Time Complexity Let Time complexity of above algorithm be T(n). Let us assume that we use a O(nLogn) sorting algorithm. The above algorithm divides all points in two sets and recursively calls for two sets. After dividing, it finds the strip in O(n) time, sorts the strip in O(nLogn) time and finally finds the closest points in strip in O(n) time. So T(n) can expressed as follows T(n) = 2T(n/2) + O(n) + O(nLogn) + O(n) T(n) = 2T(n/2) + O(nLogn) T(n) = T(n x Logn x Logn)
Notes 1) Time complexity can be improved to O(nLogn) by optimizing step 5 of the above algorithm. We will soon be discussing the optimized solution in a separate post. 2) The code finds smallest distance. It can be easily modified to find the points with the smallest distance. 3) The code uses quick sort which can be O(n^2) in the worst case. To have the upper bound as O(n (Logn)^2), a O(nLogn) sorting algorithm like merge sort or heap sort can be used
YouTubeGeeksforGeeks502K subscribersClosest Pair of Points | Divide and Conquer | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0W_m46Q4qMc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: http://www.cs.umd.edu/class/fall2013/cmsc451/Lects/lect10.pdf http://www.youtube.com/watch?v=vS4Zn1a9KUc http://www.youtube.com/watch?v=T3T7T8Ym20M http://en.wikipedia.org/wiki/Closest_pair_of_points_problem
rathbhupendra
Akanksha_Rai
PrateekGupta10
kjs9
rleecharlie
sumitgumber28
varshagumber28
sanjay sharma 1
Closest Pair of Points
Divide and Conquer
Geometric
Divide and Conquer
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi
Program for distance between two points on earth
Find if two rectangles overlap
Check whether triangle is valid or not if sides are given
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Polygon Clipping | Sutherland–Hodgman Algorithm | [
{
"code": null,
"e": 34594,
"s": 34566,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 35284,
"s": 34594,
"text": "We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applicat... |
ML Design Pattern #2: Checkpoints | by Lak Lakshmanan | Towards Data Science | An occasional series of design patterns for ML engineers. Full list here.
The key steps of a machine learning pipeline are to train the model (using model.fit() in Keras), evaluate the model (using model.evaluate()), export it (using model.save()), deploy it (using gcloud ai-platform versions create), and use it for predictions by accessing the model’s REST API. However, it can sometimes be better to take a bit more control over the training and evaluation loop using checkpoints.
A checkpoint is an intermediate dump of a model’s entire internal state (its weights, current learning rate, etc.) so that the framework can resume the training from this point whenever desired. With checkpoints included, the ML pipeline becomes:
In other words, you train for a few iterations, then evaluate the model, checkpoint it, then fit some more. When you are done, save the model and deploy it as normal.
Saving intermediate checkpoints gives you a few benefits:
Resilience: If you are training for a very long time, or doing distributed training on many machines, the likelihood of machine failure increases. If a machine fails, TensorFlow can resume from the last saved checkpoint instead of having to start from scratch. This behavior is automatic — TensorFlow looks for checkpoints and resumes from the last checkpoint.
Generalization: In general, the longer you train, the lower the loss on the training dataset. However, at some point, the error on the held-out, evaluation dataset might stop decreasing. If you have a very large model, and you are not doing sufficient regularization, the error on the evaluation dataset might even start to increase. If this happens, it can be helpful to go back and export the model that had the best validation error. This is also called early stopping because you could stop if you see the validation error start to increase. (A better idea is, of course, to decrease model complexity or increase the regularization so that this scenario doesn’t happen). The only way you can go back to the best validation error or do early stopping is if you have been periodically evaluating and checkpointing the model.
Tuneability: In a well-behaved training loop, gradient descent behaves such that you get to the neighborhood of the optimal error quickly on the basis of the majority of your data and then slowly converge towards the lowest error by optimizing on the corner cases. Now, imagine that you need to periodically retrain the model on fresh data. You typically want to emphasize the fresh data, not the corner cases from last month. You are often better off resuming your training, not from the last checkpoint, but the checkpoint marked by the blue line:
To checkpoint a model in Keras, provide a callback:
trainds = load_dataset('taxi-train*', TRAIN_BATCH_SIZE, tf.estimator.ModeKeys.TRAIN)evalds = load_dataset('taxi-valid*', 1000, tf.estimator.ModeKeys.EVAL).take(NUM_EVAL_EXAMPLES)steps_per_epoch = NUM_TRAIN_EXAMPLES // (TRAIN_BATCH_SIZE * NUM_EVALS)shutil.rmtree('{}/checkpoints/'.format(OUTDIR), ignore_errors=True)checkpoint_path = '{}/checkpoints/taxi'.format(OUTDIR)cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1)history = model.fit(trainds, validation_data=evalds, epochs=NUM_EVALS, steps_per_epoch=steps_per_epoch, verbose=2, # 0=silent, 1=progress bar, 2=one line per epoch callbacks=[cp_callback]) | [
{
"code": null,
"e": 246,
"s": 172,
"text": "An occasional series of design patterns for ML engineers. Full list here."
},
{
"code": null,
"e": 657,
"s": 246,
"text": "The key steps of a machine learning pipeline are to train the model (using model.fit() in Keras), evaluate the m... |
PHP | DateTime modify() Function - GeeksforGeeks | 10 Oct, 2019
The DateTime::modify() function is an inbuilt function in PHP which is used to modify or can alter the timestamp of a DateTime object.
Syntax:
Object oriented style:DateTime DateTime::modify( string $modify )
DateTime DateTime::modify( string $modify )
Procedural style:DateTime date_modify( DateTime $object, string $modify )
DateTime date_modify( DateTime $object, string $modify )
Parameters: This function uses two parameters as mentioned above and described below:
$object: It specifies the DateTime object returned by date_create() function. This object is modified by DateTime::modify() function.
$modify: It specifies the date/time string. It is incremented or decremented to modify the DateTime object.
Return Value: This function returns the modified DateTime object on success or False on failure.
Below programs illustrate the DateTime::modify() function in PHP:
Program 1 :
<?php// PHP program to illustrate // DateTime::modify() function // Creating a DateTime object$datetime = new DateTime('2019-09-30'); // Calling of date DateTime::modify() function// with the increment of 5 days as parameters$datetime->modify('+5 day'); // Getting the modified date in "y-m-d" formatecho $datetime->format('Y-m-d'); ?>
2019-10-05
Program 2:
<?php// PHP program to illustrate the// DateTime::modify() function // Creating a DateTime object$datetime = new DateTime('2019-09-30'); // Calling of date DateTime::modify() function// with the increment of 5 months as parameters$datetime->modify('+5 month'); // Getting the modified date in "y-m-d" formatecho $datetime->format('Y-m-d'); ?>
2020-03-01
Reference: https://www.php.net/manual/en/datetime.modify.php
PHP-date-time
PHP-function
PHP
Web Technologies
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 ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n10 Oct, 2019"
},
{
"code": null,
"e": 24716,
"s": 24581,
"text": "The DateTime::modify() function is an inbuilt function in PHP which is used to modify or can alter the timestamp of a DateTime object."
},
{
"code": null,
... |
Weather Data Collection: Web Scraping using Python | by Somesh Routray | Towards Data Science | In this blog, I will be discussing how to scrape data from a website. Hopefully, you have already visited my data collection technique using an API. In the real-world scenario, we may come across different data sources like databases, log files, Structured files, Services or API, etc. These sources may contain data in the form of records, graphs, or texts. Hence the data is available everywhere and to perform different innovative data science techniques we need to parse those data. We know Wikipedia is one of the biggest sources of data in the form of texts.
How to parse these kinds of textual data?
Here web scraping comes into the picture! It is a technique to extract the data using HTML tags. Here I will discuss this technique to scrape the weather data from the EstesPark Weather website. This website was primarily created as a public service for residents of Estes Park, Colorado, and Vicinity. Below is the screenshot of the website. You can follow the link to get the website.
Some useful information about the website
The website contains date wise weather data like average temperature, average humidity, average dewpoint, etc. These data are store in the HTML web table.There is a drop-down where you will get the liberty to choose the month and year to see the weather data.Each time you change the drop-down selection, the date value will change according to the selected month and year but in yyyymm format. Refer to the image above as I choose May 2020 , in the link, date value is changed to 202005.
The website contains date wise weather data like average temperature, average humidity, average dewpoint, etc. These data are store in the HTML web table.
There is a drop-down where you will get the liberty to choose the month and year to see the weather data.
Each time you change the drop-down selection, the date value will change according to the selected month and year but in yyyymm format. Refer to the image above as I choose May 2020 , in the link, date value is changed to 202005.
https://www.estesparkweather.net/archive_reports.php?date=202005
First import all required libraries for the case study
import bs4from bs4 import BeautifulSoupimport requestsimport pandas as pdfrom datetime import datetime
Let’s understand the piece of code.
url=‘https://www.estesparkweather.net/archive_reports.phpdate=202005'page = requests.get(url)print(page)soup = BeautifulSoup(page.content,'html.parser')print(soup)
The requests library allows you to send HTTP requests easily and there’s no need to manually add query strings to your url, or to form-encode your POST data. The urllib3 module inside the requests module makes the url in keep-alive state and you can pool the data continuously.
A working url will give you a status code 200. Which means the url is working fine.
BeautifulSoup library helps you to parse the HTML content on a webpage and XML content in XML file. The docstring of the BeautifulSoup is below.
Most of the methods you’ll call on a BeautifulSoup object are inherited fromPageElement or Tag.
Internally, this class defines the basic interface called by thetree builders when converting an HTML/XML document into a datastructure. The interface abstracts away the differences betweenparsers. To write a new tree builder, you’ll need to understandthese methods as a whole.
These methods will be called by the BeautifulSoup constructor: * reset() * feed(markup)
The tree builder may call these methods from its feed() implementation: * handle_starttag(name, attrs) # See note about return value * handle_endtag(name) * handle_data(data) # Appends to the current data node * endData(containerClass) # Ends the current data node
End of the show, you should be able to build a tree using ‘start tag’ events, ‘end tag’ events, ‘data’ events, and “done with data” events.
Inside BeautifulSoup constructor I entered the HTML content of the url and given command as ‘html.parser’. This will give me the HTML content of the webpage. For XML , you can use ‘lxml’.
What is the soup then?
It is a BeautifulSoup object that has methods designed specifically to work with HTML content.
As I mentioned earlier the weather data on the website is in the HTML web table form. So we look for the table in the HTML content and analyze the rows and columns.
table = soup.find_all(‘table’)raw_data = [row.text.splitlines() for row in table]raw_data = raw_data[:-9]for i in range(len(raw_data)): raw_data[i] = raw_data[i][2:len(raw_data[i]):3]print(raw_data)
In the drop-down when we select May 2020, it will give you separate tables with all the weather attribute values for each day. So we will split the rows in the table and append in a list. And finally, you will get a list of lists. Noteworthy, each sub-lists contain weather attributes and their values for a particular month.
How to get weather data of other months ?
As mentioned earlier, the link contains the page value equals to drop-down value but in yyyymm format. So you make a date range and strip the dates into the required format and concatenate with the string urls.
Dates_r = pd.date_range(start = ‘1/1/2009’,end = ‘08/05/2020’,freq = ‘M’)dates = [str(i)[:4] + str(i)[5:7] for i in Dates_r]dates[0:5]for k in range(len(dates)): url = "http://www.estesparkweather.net/archive_reports.php?date=" url += dates[k]
Now, you can perform string stripping techniques to create a data set. An example is below.
for u in url: for i in range(len(raw_data)): c = [‘.’.join(re.findall(“\d+”,str(raw_data[i][j].split()[:5])))for j in range(len(raw_data[i]))] df_list.append(c) index.append(dates[k] + c[0]) f_index = [index[i] for i in range(len(index)) if len(index[i]) > 6] data = [df_list[i][1:] for i in range(len(df_list)) if len(df_list[i][1:]) == 19]
To make the dates as an index to the dataset you can use the below code.
final_index = [datetime.strptime(str(f_index[i]), ‘%Y%m%d’).strftime(‘%Y-%m-%d’) for i in range(len(f_index))]
You can make a list of the weather attributes such as humidity, temperature, rainfall for column names or you can choose custom column names for your data.
Congratulations !!! You are at a PANDAS touch far from creating a DataFrame.
In DataFrame() you will give data value as the data you have made for all the weather attribute values, columns equals to the list variable containing custom column names and finally the index value will be the list variable of dates.
This is not an end rather a beginning. You can use the concept to scrape the data e-newspaper, song websites, etc.
In the next blog, I will come up with different techniques for data collections. I hope you have enjoyed the Natural Language Processing Part-I & Part-2.
I’d love to hear any comments about the above analysis — feel free to leave a message below, or reach out to me through LinkedIn and twitter @RoutraySomesh!!! | [
{
"code": null,
"e": 736,
"s": 171,
"text": "In this blog, I will be discussing how to scrape data from a website. Hopefully, you have already visited my data collection technique using an API. In the real-world scenario, we may come across different data sources like databases, log files, Structure... |
RxJava - Filtering Operators | Following are the operators which are used to selectively emit item(s) from an Observable.
Debounce
Emits items only when timeout occurs without emiting another item.
Distinct
Emits only unique items.
ElementAt
emit only item at n index emitted by an Observable.
Filter
Emits only those items which pass the given predicate function.
First
Emits the first item or first item which passed the given criteria.
IgnoreElements
Do not emits any items from Observable but marks completion.
Last
Emits the last element from Observable.
Sample
Emits the most recent item with given time interval.
Skip
Skips the first n items from an Observable.
SkipLast
Skips the last n items from an Observable.
Take
takes the first n items from an Observable.
TakeLast
takes the last n items from an Observable.
Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import io.reactivex.Observable;
//Using take operator to filter an Observable
public class ObservableTester {
public static void main(String[] args) {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
final StringBuilder result = new StringBuilder();
Observable<String> observable = Observable.fromArray(letters);
observable
.take(2)
.subscribe( letter -> result.append(letter));
System.out.println(result);
}
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java
Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester
It should produce the following output −
ab
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2492,
"s": 2401,
"text": "Following are the operators which are used to selectively emit item(s) from an Observable."
},
{
"code": null,
"e": 2501,
"s": 2492,
"text": "Debounce"
},
{
"code": null,
"e": 2568,
"s": 2501,
"text": "Emits items... |
How to remove the redundant elements from an ArrayList object in java? | The interface set does not allow duplicate elements. The add() method of this interface accepts elements and adds to the Set object, if the addition is successful it returns true if you try to add an existing element using this method, the addition operations fails to return false.
Therefore, to remove redundant elements of an ArrayList object −
Get/create the required ArrayList.
Get/create the required ArrayList.
Create an empty set object.
Create an empty set object.
Try to add all the elements of the ArrayList object to set objectives.
Try to add all the elements of the ArrayList object to set objectives.
Clear the contents of the ArrayList using the clear() method.
Clear the contents of the ArrayList using the clear() method.
Now, using the addAll() method add the contents of the set object to the ArrayList again.
Now, using the addAll() method add the contents of the set object to the ArrayList again.
Live Demo
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class RemovingDuplicates {
public static void main(String[] args){
//Instantiating an ArrayList object
ArrayList<String> list = new ArrayList<String>();
list.add("JavaFX");
list.add("Java");
list.add("JavaFX");
list.add("OpenCV");
list.add("Java");
list.add("JOGL");
list.add("JOGL");
list.add("HBase");
list.add("Flume");
list.add("HBase");
list.add("Impala");
System.out.println("Contents of the Array List : \n"+list);
//Retrieving Iterator object of the ArrayList class
Iterator<String> it = list.iterator();
//Creating an empty Set object
Set<String> set = new HashSet<String>();
//Adding elements of the ArrayList to the Set object
while(it.hasNext()) {
set.add(it.next());
}
//Removing all the elements from the ArrayList
list.clear();
//Adding elements of the set back to the list
list.addAll(set);
System.out.println("Contents of the Array List after removing duplicate elements: \n"+list);
}
}
Contents of the Array List :
[JavaFX, Java, JavaFX, OpenCV, Java, JOGL, JOGL, HBase, Flume, HBase, Impala]
Contents of the Array List after removing duplicate elements:
[JavaFX, Java, OpenCV, JOGL, Flume, Impala, HBase] | [
{
"code": null,
"e": 1345,
"s": 1062,
"text": "The interface set does not allow duplicate elements. The add() method of this interface accepts elements and adds to the Set object, if the addition is successful it returns true if you try to add an existing element using this method, the addition oper... |
Print JSON nested object in JavaScript? | To print JSON nested object in JavaScript, use for loop along with JSON.parse(). Following is
the code −
var details = [
{
"studentId": 101,
"studentName": "John",
"countryName": "US",
"subjectDetails": "{\"0\":\"JavaScript\",\"1\":\"David\"}"
},
{
"studentId": 102,
"studentName": "Bob",
"countryName": "UK",
"subjectDetails": "{\"0\":\"Java\",\"1\":\"Carol\"}"
},
{
"studentId": 103,
"studentName": "Mike",
"countryName": "AUS",
"subjectDetails": "{\"0\":\"MongoDB\",\"1\":\"Adam\"}"
}
]
for (const detailsObject of details) {
const subjectDetailsObject =
JSON.parse(detailsObject.subjectDetails);
console.log(subjectDetailsObject[0]);
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo145.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo145.js
JavaScript
Java
MongoDB | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "To print JSON nested object in JavaScript, use for loop along with JSON.parse(). Following is\nthe code −"
},
{
"code": null,
"e": 1801,
"s": 1167,
"text": "var details = [\n {\n \"studentId\": 101,\n \"studentName\": \"J... |
Program to count how many ways we can divide the tree into two trees in Python | Suppose we have a binary tree containing values 0, 1 and 2. The root has at least one 0 node and one 1 node. Now suppose there is an operation where we delete an edge in the tree and the tree becomes two different trees. We have to find the number of ways we can delete one edge such that none of the two trees contain both a 0 node and a 1 node.
So, if the input is like
then the output will be 1 as we can only delete the 0 to 2 edge.
To solve this, we will follow these steps −
count := [0, 0, 0]
Define a function dfs() . This will take node
if node is not null, thenpre := countdfs(left of node)dfs(right of node)count[value of node] := count[value of node] + 1node.count := a list of (count[i] - pre[i]) for i is 0 and 1
pre := count
dfs(left of node)
dfs(right of node)
count[value of node] := count[value of node] + 1
node.count := a list of (count[i] - pre[i]) for i is 0 and 1
Define a function dfs2() . This will take node, par
if node is not null, thenif par is not null, then(a0, a1) := count of node(b0, b1) := (count[0] - a0, count[1] - a1)if (a0 is same as 0 or a1 is same as 0) and (b0 is same as 0 or b1 is same as 0), thenans := ans + 1dfs2(left of node, node)dfs2(right of node, node)
if par is not null, then(a0, a1) := count of node(b0, b1) := (count[0] - a0, count[1] - a1)if (a0 is same as 0 or a1 is same as 0) and (b0 is same as 0 or b1 is same as 0), thenans := ans + 1
(a0, a1) := count of node
(b0, b1) := (count[0] - a0, count[1] - a1)
if (a0 is same as 0 or a1 is same as 0) and (b0 is same as 0 or b1 is same as 0), thenans := ans + 1
ans := ans + 1
dfs2(left of node, node)
dfs2(right of node, node)
From the main method, do the following −
dfs(root)
ans := 0
dfs2(root)
return ans
Let us see the following implementation to get better understanding −
Live Demo
class TreeNode:
def __init__(self, data, left = None, right = None):
self.val = data
self.left = left
self.right = right
class Solution:
def solve(self, root):
count = [0, 0, 0]
def dfs(node):
if node:
pre = count[:]
dfs(node.left)
dfs(node.right)
count[node.val] += 1
node.count = [count[i] - pre[i] for i in range(2)]
dfs(root)
def dfs2(node, par=None):
if node:
if par is not None:
a0, a1 = node.count
b0, b1 = count[0] - a0, count[1] - a1
if (a0 == 0 or a1 == 0) and (b0 == 0 or b1 == 0):
self.ans += 1
dfs2(node.left, node)
dfs2(node.right, node)
self.ans = 0
dfs2(root)
return self.ans
ob = Solution()
root = TreeNode(0)
root.left = TreeNode(0)
root.right = TreeNode(2)
root.right.left = TreeNode(1)
root.right.right = TreeNode(1)
print(ob.solve(root))
root = TreeNode(0)
root.left = TreeNode(0)
root.right = TreeNode(2)
root.right.left = TreeNode(1)
root.right.right = TreeNode(1)
1 | [
{
"code": null,
"e": 1409,
"s": 1062,
"text": "Suppose we have a binary tree containing values 0, 1 and 2. The root has at least one 0 node and one 1 node. Now suppose there is an operation where we delete an edge in the tree and the tree becomes two different trees. We have to find the number of wa... |
How to change the position of modal close button in bootstrap? - GeeksforGeeks | 16 Jul, 2021
The Modal component is a dialog box or a popup window that displays on top of the page. Modals can be used as alert windows as well as for accepting some input values.
Example of a basic modal: For changing the position of the close button, we need to create a modal element. The below code will create a very basic modal.
HTML
<!DOCTYPE html><html> <head> <title>Modal Closing Button</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> <meta content="utf-8" http-equiv="encoding" /> <!-- Jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" /> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <!-- Personalized Includes --> <!-- CSS --> <style> .center { margin: 0 auto; text-align: center; justify-content: center; } .btn-div { margin-top: 20px; } </style> </head> <body> <div class="modal fade" id="main-modal"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header" id="modal-header"> <h4 class="modal-title" id="modal-title"> Modal Heading </h4> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <!-- Modal body --> <div class="modal-body" id="modal-body"> Modal Body </div> <!-- Modal footer --> <div class="modal-footer" id="modal-footer"> Modal Footer </div> </div> </div> </div> <div class="center btn-div"> <div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/GeeksforGeeksLogoHeader.png" class="img-fluid" /> </div> <br /> <button class="btn btn-success" data-toggle="modal" data-target="#main-modal"> Open Modal </button> </div> </body></html>
Output:
Approach: In the above, you can observe a button with class = “close” inside the modal header. This button is used for closing the modal element. data-dismiss property is used to switch the display style of the modal element.
<button type="button" class="close" data-dismiss="modal">
×
</button>
× gives the cross icon.
data-dismiss switches the display property of modal element from “block” to “none”.
You can shift this button description from header to any location inside the entire modal division to move the close button, or you can declare your own extra close button.
Below are the implementation methods for the above steps.
Method 1: Move the button description.
HTML
<!DOCTYPE html><html> <head> <title>Modal Closing Button</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> <meta content="utf-8" http-equiv="encoding" /> <!-- Jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <!-- Personalized Includes --> <!-- CSS --> <style> .center { margin: 0 auto; text-align: center; justify-content: center; } .btn-div { margin-top: 20px; } </style> </head> <body> <div class="modal fade" id="main-modal"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header" id="modal-header"> <h4 class="modal-title" id="modal-title"> Modal Heading </h4> <!--Button shifted from here...--> </div> <!-- Modal body --> <div class="modal-body" id="modal-body"> Modal Body <!--Button shifted to this place...--> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <!-- Modal footer --> <div class="modal-footer" id="modal-footer"> Modal Footer </div> </div> </div> </div> <div class="center btn-div"> <div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/GeeksforGeeksLogoHeader.png" class="img-fluid" /> </div> <br /> <button class="btn btn-success" data-toggle="modal" data-target="#main-modal"> Open Modal </button> </div> </body></html>
Output: The button appears in the body section of the modal element since it is moved to the body section.
Method 2: Define your own close button using the data-dismiss property.
HTML
<!DOCTYPE html><html> <head> <title>Modal Closing Button</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> <meta content="utf-8" http-equiv="encoding" /> <!-- Jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"/> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <!-- Personalized Includes --> <!-- CSS --> <style> .center { margin: 0 auto; text-align: center; justify-content: center; } .btn-div { margin-top: 20px; } </style> </head> <body> <div class="modal fade" id="main-modal"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header" id="modal-header"> <h4 class="modal-title" id="modal-title"> Modal Heading </h4> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <!-- Modal body --> <div class="modal-body" id="modal-body"> Modal Body </div> <!-- Modal footer --> <div class="modal-footer" id="modal-footer"> Modal Footer <!--New Button declared here...--> <button class="btn btn-danger" data-dismiss="modal"> Close Modal </button> </div> </div> </div> </div> <div class="center btn-div"> <div> <img src="https://www.geeksforgeeks.org/wp-content/uploads/GeeksforGeeksLogoHeader.png" class="img-fluid" /> </div> <br /> <button class="btn btn-success" data-toggle="modal" data-target="#main-modal"> Open Modal </button> </div> </body></html>
Output: A new close button is available in the modal footer section.
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
Bootstrap-Misc
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to align navbar items to the right in Bootstrap 4 ?
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 28049,
"s": 28021,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 28217,
"s": 28049,
"text": "The Modal component is a dialog box or a popup window that displays on top of the page. Modals can be used as alert windows as well as for accepting some input val... |
Java finally Keyword | ❮ Java Keywords
Execute code, after try...catch, regardless of the result:
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
Try it Yourself »
The finally keyword is used to execute code (used with exceptions
- try..catch statements) no matter if there is an exception or not.
Read more about exceptions in our Java Try..Catch Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 77,
"s": 18,
"text": "Execute code, after try...catch, regardless of the result:"
},
{
"code": null,
"e": 291,
"s": 77,
"text": "try {\n int[] myNumbers = {1, 2, 3};\n Sys... |
DataTables paging Option - GeeksforGeeks | 31 May, 2021
DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed.
The paging option is used to specify whether the paging of the DataTable is enabled or not. The DataTable splits the records being shown in multiple pages so that only a certain number of records are shown on a page. The number of records to show can be selected using the dropdown menu. A true value enables paging and a false value disables it.
Syntax:
{ paging: value }
Option Value: This option has a single value as mentioned above and described below:
value: This is a boolean value that specifies whether paging of the DataTable is enabled or not. The default value is true.
The below example illustrates the use of this option.
Example 1: This example disables the paging functionality of the DataTable.
HTML
<html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables Paging Option</h3> <!-- HTML table with student data --> <table id="tableID" class="display"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam</td> <td>35</td> </tr> <tr> <td>2</td> <td>Sam</td> <td>30</td> </tr> <tr> <td>3</td> <td>Sameer</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rob</td> <td>4</td> </tr> <tr> <td>5</td> <td>Robber</td> <td>68</td> </tr> <tr> <td>6</td> <td>Mikasa</td> <td>25</td> </tr> <tr> <td>7</td> <td>Eren</td> <td>23</td> </tr> <tr> <td>8</td> <td>Jean</td> <td>35</td> </tr> <tr> <td>9</td> <td>Walter</td> <td>65</td> </tr> <tr> <td>10</td> <td>Jessie</td> <td>28</td> </tr> <tr> <td>11</td> <td>Gabi</td> <td>20</td> </tr> <tr> <td>12</td> <td>Tim</td> <td>30</td> </tr> <tr> <td>13</td> <td>Max</td> <td>35</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Disable paging // of the DataTable paging: false }); }); </script></body></html>
Output:
Example 2: This example enables the paging functionality of the DataTable.
HTML
<html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head><body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables Paging Option</h3> <!-- HTML table with student data --> <table id="tableID" class="display"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam</td> <td>35</td> </tr> <tr> <td>2</td> <td>Sam</td> <td>30</td> </tr> <tr> <td>3</td> <td>Sameer</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rob</td> <td>4</td> </tr> <tr> <td>5</td> <td>Robber</td> <td>68</td> </tr> <tr> <td>6</td> <td>Mikasa</td> <td>25</td> </tr> <tr> <td>7</td> <td>Eren</td> <td>23</td> </tr> <tr> <td>8</td> <td>Jean</td> <td>35</td> </tr> <tr> <td>9</td> <td>Walter</td> <td>65</td> </tr> <tr> <td>10</td> <td>Jessie</td> <td>28</td> </tr> <tr> <td>11</td> <td>Gabi</td> <td>20</td> </tr> <tr> <td>12</td> <td>Tim</td> <td>30</td> </tr> <tr> <td>13</td> <td>Max</td> <td>35</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable paging // of the DataTable paging: true }); }); </script></body></html>
Output:
jQuery-DataTables
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25389,
"s": 25361,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 25727,
"s": 25389,
"text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to... |
Rock Paper Scissor in C - GeeksforGeeks | 15 Jun, 2021
Rock Paper Scissor (which is also called Stone Paper Scissor) is a hand game and played between two people, in which each player simultaneously forms one of three shapes. The winner of the game is decided as per the below rules:
Rock vs Paper -> Paper wins.
Rock vs Scissor -> Rock wins.
Paper vs Scissor -> Scissor wins.
In this game, the user will be asked to make choice and according to the choice of user and computer and then the result will be displayed along with the choices of both computer and user.
Approach: Below is the functionality that needed to be implemented in the program:
main() function:
It consists of the declaration of the variables.
printf() and scanf() functions for displaying the content and taking input from the user. It also contains two predefined functions:srand() and rand() which are used to generate random numbers in the range [0, RAND_MAX) and srand() especially will help to generate a random number at each time.Take modulo of random number generated with 100 to make its range between (0 and 100).As the range is up to 100 only, the distribution among all the options i.e., stone, paper, and scissors is equal as all of them have an equal probability of coming.
srand() and rand() which are used to generate random numbers in the range [0, RAND_MAX) and srand() especially will help to generate a random number at each time.
Take modulo of random number generated with 100 to make its range between (0 and 100).
As the range is up to 100 only, the distribution among all the options i.e., stone, paper, and scissors is equal as all of them have an equal probability of coming.
Note: This random number will decide the choice of computer as:
If the number is between 0-33 then the choice will be Stone.
If the number is between 33-66 then the choice will be Paper.
If the number is between 66-100 then the choice will be Scissors.
game() function: This function consists of if-else statements that will compare the choice of user and computer. If the user wins then it will return 1. Otherwise, if the computer wins then it will return 0. If it is a tie, it will return -1.
Below is the implementation of the above approach:
C
// C program for the above approach#include <math.h>#include <stdio.h>#include <stdlib.h>#include <time.h> // Function to implement the gameint game(char you, char computer){ // If both the user and computer // has chose the same thing if (you == computer) return -1; // If user's choice is stone and // computer's choice is paper if (you == 's' && computer == 'p') return 0; // If user's choice is paper and // computer's choice is stone else if (you == 'p' && computer == 's') return 1; // If user's choice is stone and // computer's choice is scissor if (you == 's' && computer == 'z') return 1; // If user's choice is scissor and // computer's choice is stone else if (you == 'z' && computer == 's') return 0; // If user's choice is paper and // computer's choice is scissor if (you == 'p' && computer == 'z') return 0; // If user's choice is scissor and // computer's choice is paper else if (you == 'z' && computer == 'p') return 1;} // Driver Codeint main(){ // Stores the random number int n; char you, computer, result; // Chooses the random number // every time srand(time(NULL)); // Make the random number less // than 100, divided it by 100 n = rand() % 100; // Using simple probability 100 is // roughly divided among stone, // paper, and scissor if (n < 33) // s is denoting Stone computer = 's'; else if (n > 33 && n < 66) // p is denoting Paper computer = 'p'; // z is denoting Scissor else computer = 'z'; printf("\n\n\n\n\t\t\t\tEnter s for STONE, p for PAPER and z for SCISSOR\n\t\t\t\t\t\t\t"); // input from the user scanf("%c", &you); // Function Call to play the game result = game(you, computer); if (result == -1) { printf("\n\n\t\t\t\tGame Draw!\n"); } else if (result == 1) { printf("\n\n\t\t\t\tWow! You have won the game!\n"); } else { printf("\n\n\t\t\t\tOh! You have lost the game!\n"); } printf("\t\t\t\tYOu choose : %c and Computer choose : %c\n",you, computer); return 0;}
Output:
Firstly the user will be asked about the choice:
When the user enters the choice then the result is displayed:
sofiadnan92
Technical Scripter 2020
C Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Regular expressions in C
How to store words in an array in C?
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Conditional wait and signal in multi-threading
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 | [
{
"code": null,
"e": 24565,
"s": 24537,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 24794,
"s": 24565,
"text": "Rock Paper Scissor (which is also called Stone Paper Scissor) is a hand game and played between two people, in which each player simultaneously forms one of three ... |
Gson - Class | Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.
Following is the declaration for com.google.gson.Gson class:
public final class Gson
extends Object
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say C:/> GSON_WORKSPACE
File: GsonTester.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonTester {
public static void main(String[] args){
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
Student student = gson.fromJson(jsonString, Student.class);
System.out.println(student);
jsonString = gson.toJson(student);
System.out.println(jsonString);
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\GSON_WORKSPACE>javac GsonTester.java
Now run the GsonTester to see the result:
C:\GSON_WORKSPACE>java GsonTester
Verify the Output
Student [ name: Mahesh, age: 21 ]
{
"name" : "Mahesh",
"age" : 21
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2224,
"s": 1932,
"text": "Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods a... |
Minkowski distance in Python - GeeksforGeeks | 16 Sep, 2021
Minkowski distance is a metric in a normed vector space. Minkowski distance is used for distance similarity of vector. Given two or more vectors, find distance similarity of these vectors.
Mainly, Minkowski distance is applied in machine learning to find out distance similarity.
Examples :
Input : vector1 = 0 2 3 4
vector2 = 2, 4, 3, 7
p = 3
Output : distance1 = 3.5033
Input : vector1 = 1, 4, 7, 12, 23
vector2 = 2, 5, 6, 10, 20
p = 2
Output : distance2 = 4.0
Note : Here distance1 and distance2 are almost same so it will be in same near region.
Python3
# Python3 program to find Minkowski distance # import math libraryfrom math import *from decimal import Decimal # Function distance between two points# and calculate distance value to given# root value(p is root value)def p_root(value, root): root_value = 1 / float(root) return round (Decimal(value) ** Decimal(root_value), 3) def minkowski_distance(x, y, p_value): # pass the p_root function to calculate # all the value of vector parallelly return (p_root(sum(pow(abs(a-b), p_value) for a, b in zip(x, y)), p_value)) # Driver Codevector1 = [0, 2, 3, 4]vector2 = [2, 4, 3, 7]p = 3print(minkowski_distance(vector1, vector2, p))
Output :
3.503
Reference : https://en.wikipedia.org/wiki/Minkowski_distance
ruhelaa48
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary | [
{
"code": null,
"e": 23926,
"s": 23898,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 24115,
"s": 23926,
"text": "Minkowski distance is a metric in a normed vector space. Minkowski distance is used for distance similarity of vector. Given two or more vectors, find distance sim... |
How to Combine Two String Columns in Pandas | Towards Data Science | Creating new columns by concatenating other columns is a fairly common task. In today’s short guide we will showcase how to concatenate the content of string DataFrame columns into a new column. We will explore a few different options that you should always consider based on the dataset size you are working on.
Some of these approaches tend to be more efficient when applied to small datasets whilst other approaches may be faster to execute when applied over larger datasets.
Additionally, we will also explore how to concatenate string with non-string (e.g. integer) columns.
First, let’s create an example DataFrame that we’ll reference throughout this article in order to demonstrate a few concepts.
import pandas as pddf = pd.DataFrame( [ (1, '2017', 10, 'Q1'), (2, '2017', 20, 'Q2'), (3, '2016', 35, 'Q4'), (4, '2019', 25, 'Q2'), (5, '2020', 44, 'Q3'), (6, '2021', 51, 'Q3'), ], columns=['colA', 'colB', 'colC', 'colD'])print(df) colA colB colC colD0 1 2017 10 Q11 2 2017 20 Q22 3 2016 35 Q43 4 2019 25 Q24 5 2020 44 Q35 6 2021 51 Q3
For relatively small datasets (up to 100–150 rows) you can use pandas.Series.str.cat() method that is used to concatenate strings in the Series using the specified separator (by default the separator is set to '').
For example, if we wanted to concatenate columns colB and colD and then store the output into a new column called colE, the following statement would do the trick:
df['colE'] = df.colB.str.cat(df.colD) print(df) colA colB colC colD colE0 1 2017 10 Q1 2017Q11 2 2017 20 Q2 2017Q22 3 2016 35 Q4 2016Q43 4 2019 25 Q2 2019Q24 5 2020 44 Q3 2020Q35 6 2021 51 Q3 2021Q3
Now if we wanted to specify a separator that will be placed between the concatenated columns, then we simply need to pass sep argument:
df['colE'] = df.colB.str.cat(df.colD, sep='-')print(df) colA colB colC colD colE0 1 2017 10 Q1 2017-Q11 2 2017 20 Q2 2017-Q22 3 2016 35 Q4 2016-Q43 4 2019 25 Q2 2019-Q24 5 2020 44 Q3 2020-Q35 6 2021 51 Q3 2021-Q3
Alternatively, you can also use a list comprehension which is a bit more verbose but slightly faster:
df['colE'] = [''.join(i) for i in zip(df['colB'], df['colD'])]print(df) colA colB colC colD colE0 1 2017 10 Q1 2017Q11 2 2017 20 Q2 2017Q22 3 2016 35 Q4 2016Q43 4 2019 25 Q2 2019Q24 5 2020 44 Q3 2020Q35 6 2021 51 Q3 2021Q3
Now if you are working with large datasets, the more efficient way to concatenate two columns is using the + operator.
df['colE'] = df['colB'] + df['colD']print(df) colA colB colC colD colE0 1 2017 10 Q1 2017Q11 2 2017 20 Q2 2017Q22 3 2016 35 Q4 2016Q43 4 2019 25 Q2 2019Q24 5 2020 44 Q3 2020Q35 6 2021 51 Q3 2021Q3
If you want to include a separator then simply place it as a string in-between the two columns:
df['colE'] = df['colB'] + '-' + df['colD']
Now let’s assume that one of the columns you are trying to concatenate is not in string format:
import pandas as pddf = pd.DataFrame( [ (1, 2017, 10, 'Q1'), (2, 2017, 20, 'Q2'), (3, 2016, 35, 'Q4'), (4, 2019, 25, 'Q2'), (5, 2020, 44, 'Q3'), (6, 2021, 51, 'Q3'), ], columns=['colA', 'colB', 'colC', 'colD'])print(df.dtypes)colA int64colB int64colC int64colD objectdtype: object
In this case, you can simply cast the column using pandas.DataFrame.astype() or map() methods.
# Option 1df['colE'] = df.colB.astype(str).str.cat(df.colD)# Option 2df['colE'] = df['colB'].astype(str) + '-' + df['colD']# Option 3df['colE'] = [ ''.join(i) for i in zip(df['colB'].map(str), df['colD'])]
In today’s short guide we discussed about concatenating string columns in pandas DataFrames. Depending on the size of the dataset you are working with, you may have to select the most appropriate method that will be executed more efficiently.
Furthermore, we also showcased how to concatenate string with non-string columns by making use of the astype() method in pandas.
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
gmyrianthous.medium.com
You may also like | [
{
"code": null,
"e": 484,
"s": 171,
"text": "Creating new columns by concatenating other columns is a fairly common task. In today’s short guide we will showcase how to concatenate the content of string DataFrame columns into a new column. We will explore a few different options that you should alwa... |
Convert string dictionary to dictionary in Python | In this article we'll see how to convert a given dictionary containing strings into a normal dictionary of key value pairs.
The json.loads can pass a given string and give us the result as normal strings preserving the structure of the data. So we pass the given string dictionary into this function as a parameter and get our result.
Live Demo
import json
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = json.loads(stringA)
# Result
print("The converted dictionary : \n",res)
Running the above code gives us the following result −
Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Mon': 3, 'Wed': 5, 'Fri': 7}
This method from ast module works similar to the above approach. The dictionary containing string gets parsed as normal values and produces the normal dictionary.
Live Demo
import ast
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = ast.literal_eval(stringA)
# Result
print("The converted dictionary : \n",res)
Running the above code gives us the following result −
Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Fri': 7, 'Mon': 3, 'Wed': 5} | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "In this article we'll see how to convert a given dictionary containing strings into a normal dictionary of key value pairs."
},
{
"code": null,
"e": 1397,
"s": 1186,
"text": "The json.loads can pass a given string and give us the res... |
Guava - Overview | Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.
Standardized − The Guava library is managed by Google.
Standardized − The Guava library is managed by Google.
Efficient − It is a reliable, fast, and efficient extension to the Java standard library.
Efficient − It is a reliable, fast, and efficient extension to the Java standard library.
Optimized − The library is highly optimized.
Optimized − The library is highly optimized.
Functional Programming − It adds functional processing capability to Java.
Functional Programming − It adds functional processing capability to Java.
Utilities − It provides many utility classes which are regularly required in programming application development.
Utilities − It provides many utility classes which are regularly required in programming application development.
Validation − It provides a standard failsafe validation mechanism.
Validation − It provides a standard failsafe validation mechanism.
Best Practices − It emphasizes on best practices.
Best Practices − It emphasizes on best practices.
Consider the following code snippet.
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();
Integer a = null;
Integer b = new Integer(10);
System.out.println(guavaTester.sum(a,b));
}
public Integer sum(Integer a, Integer b) {
return a + b;
}
}
Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at GuavaTester.sum(GuavaTester.java:13)
at GuavaTester.main(GuavaTester.java:9)
Following are the problems with the code.
sum() is not taking care of any of the parameters to be passed as null.
sum() is not taking care of any of the parameters to be passed as null.
caller function is also not worried about passing a null to the sum() method accidently.
caller function is also not worried about passing a null to the sum() method accidently.
When the program runs, NullPointerException occurs.
When the program runs, NullPointerException occurs.
In order to avoid the above problems, null check is to be made in each and every place where such problems are present.
Let's see the use of Optional, a Guava provided Utility class, to solve the above problems in a standardized way.
import com.google.common.base.Optional;
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();
Integer invalidInput = null;
Optional<Integer> a = Optional.of(invalidInput);
Optional<Integer> b = Optional.of(new Integer(10));
System.out.println(guavaTester.sum(a,b));
}
public Integer sum(Optional<Integer> a, Optional<Integer> b) {
return a.get() + b.get();
}
}
Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210)
at com.google.common.base.Optional.of(Optional.java:85)
at GuavaTester.main(GuavaTester.java:8)
Let's understand the important concepts of the above program.
Optional − A utility class, to make the code use the null properly.
Optional − A utility class, to make the code use the null properly.
Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’.
Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’.
Optional.get − It gets the value of the input stored in the Optional class.
Optional.get − It gets the value of the input stored in the Optional class.
Using the Optional class, you can check whether the caller method is passing a proper parameter or not.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2238,
"s": 1885,
"text": "Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, cac... |
How to compare only date part without comparing time in JavaScript? | To compare only date part without comparing time, set the hours using the setHours() method. This will restrict the time to be compared while comparing both and time −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var date1, date2;
date1 = new Date();
date1.setHours(0,0,0,0);
document.write(date1);
date2 = new Date( "Jan 01, 2018" );
document.write("<br>" +date2);
if (date1.getTime() === date2.getTime()) {
document.write("<br>Both the dates are equal.");
} else {
document.write("<br>Both the dates aren't equal.");
}
</script>
</body>
</html>
Fri May 25 2018 00:00:00 GMT+0530 (India Standard Time)
Mon Jan 01 2018 00:00:00 GMT+0530 (India Standard Time)
Both the dates aren't equal. | [
{
"code": null,
"e": 1230,
"s": 1062,
"text": "To compare only date part without comparing time, set the hours using the setHours() method. This will restrict the time to be compared while comparing both and time −"
},
{
"code": null,
"e": 1240,
"s": 1230,
"text": "Live Demo"
}... |
What is greater-than sign (>) selector in CSS? | 30 Jul, 2021
The greater than sign (>) selector in CSS is used to select the element with a specific parent. It is called as element > element selector. It is also known as the child combinator selector which means that it selects only those elements which are direct children of a parent. It looks only one level down the markup structure and not further deep down. Elements which are not the direct child of the specified parent is not selected.
Syntax:
element > element {
// CSS Property
}
Example-1: This example describes the greater than > selector.
<!DOCTYPE html> <html> <head> <title> CSS element > element Selector </title> <style> ul > li { color:white; background: green; } </style> </head> <body> <h2 style = "color:green;"> CSS element > element Selector </h2> <div>Searching algorithms</div> <ul> <li>Binary search</li> <li>Linear search</li> </ul> <p>Sorting Algorithms</p> <ul> <li>Merge sort</li> <li>Quick sort</li> </ul> </body> </html>
Output:
Example 2: This example describes the greater than > selector.
<!DOCTYPE html> <html> <head> <title> CSS element > element Selector </title> <!-- style to set element > element selector --> <style> li > div { color:white; background: green; } ul > li { color: green; } </style> </head> <body> <h2 style = "color:green;"> CSS element > element Selector </h2> <ul> <li> <div>Searching algorithms</div> <ul> <li>Binary search</li> <li>Linear search</li> </ul> </li> <li> <div>Sorting Algorithms</div> <ul> <li>Merge sort</li> <li>Quick sort</li> </ul> </li> </ul> </body> </html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 463,
"s": 28,
"text": "The greater than sign (>) selector in CSS is used to select the element with a specific parent. It is called as element > element selector. It is also known as the child combi... |
How to use SVG with :before or :after pseudo element ? | 04 Aug, 2021
The :before and :after pseudo-elements allow one to add styling to the webpage without adding unnecessary markup. SVG content can be added using these pseudo-elements by following the methods described below:
Method 1: Using the background-image property: The background-image property is used to set one or more background images to an element. We can also add the SVG content using this property and leaving the content property empty. The other CSS properties help to position and size the content properly.
Example:
HTML
<!DOCTYPE html><html> <head> <style> .svg-demo { text-align: center; font-weight: bold; font-size: 20px; } .text { text-align: center; } /* Using the :before pseudo-element to add the SVG content */ .svg-demo:before { display: inline-flex; content: ''; /* Using the background-image and its related properties to add the SVG content */ background-image: url('gfg_logo.svg'); background-size: 40px 40px; height: 40px; width: 40px; } /* Using the :after pseudo-element to add the SVG content */ .svg-demo:after { display: inline-flex; content: ''; /* Using the background-image and its related properties to add the SVG content */ background-image: url('gfg_logo.svg'); background-size: 40px 40px; height: 40px; width: 40px; } </style></head> <body> <p class="svg-demo"> This is the normal content </p> <p class="text"> The SVG images are added before and after the line using :before and :after pseudo-elements </p> </body> </html>
Output:
Method 2: Using the content property: The content property in CSS is used to conveniently generate content dynamically on a page. We can add the SVG content using this property on an empty pseudo-element. The other CSS properties help to position and size the content properly.
Example:
HTML
<!DOCTYPE html><html> <head> <style> .svg-demo { text-align: center; font-weight: bold; font-size: 20px; } .text { text-align: center; } /* Using the :before pseudo-element to add the SVG content */ .svg-demo:before { /* Using the content property to set the background image */ content: url('gfg_logo.svg'); /* Using the zoom property to control the size of the SVG */ zoom: 25%; } /* Using the :after pseudo-element to add the SVG content */ .svg-demo:after { /* Using the content property to set the background image */ content: url('gfg_logo.svg'); /* Using the zoom property to control the size of the SVG */ zoom: 25%; } </style></head> <body> <p class="svg-demo"> This is the normal content </p> <p class="text"> The SVG images are added before and after the line using :before and :after pseudo-elements </p> </body> </html>
Output:
sumitgumber28
CSS-Misc
CSS-Selectors
HTML-Misc
Picked
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "The :before and :after pseudo-elements allow one to add styling to the webpage without adding unnecessary markup. SVG content can be added using these pseudo-elements by follo... |
How to disable HTML links using JavaScript / jQuery ? | 29 May, 2019
Given an HTML link and the task is to disable the link by using JavaScript/jQuery.
Disable HTML link using JavaScript
createAttribute() Method: This method creates an attribute with the defined name and returns the attribute as an attribute object.Syntax:document.createAttribute(attrName)Parameters: This method accepts single parameter attrName which is required. It specifies the name of the created attribute.Return value: It returns a node object, denoting the created attribute.
Syntax:
document.createAttribute(attrName)
Parameters: This method accepts single parameter attrName which is required. It specifies the name of the created attribute.
Return value: It returns a node object, denoting the created attribute.
setAttribute() Method: This method adds the defined attribute to an element and gives it to the passed value. In case of the specified attribute already exists, the value is set/changed.Syntax:element.setAttribute(attrName, attrValue)Parameters:attrName: This parameter is required. It specifies the name of the attribute to add.attrValue: This parameter is required. It specifies the value of the attribute to add.
Syntax:
element.setAttribute(attrName, attrValue)
Parameters:
attrName: This parameter is required. It specifies the name of the attribute to add.
attrValue: This parameter is required. It specifies the value of the attribute to add.
setAttributeNode() Method: This method adds the specified attribute node to an element. In case of the specified attribute already exists, this method replaces it.Syntax:element.setAttributeNode(attributeNode)Parameters: This method accepts single parameter attributeNode which is required. It specifies the attribute node to be added.
Syntax:
element.setAttributeNode(attributeNode)
Parameters: This method accepts single parameter attributeNode which is required. It specifies the attribute node to be added.
Example 1: This example adds the class disabled to the <a> element with the help of setAttribute() method.
<!DOCTYPE HTML> <html> <head> <title> How to disable HTML links using JavaScript </title> <style> a.disabled { pointer-events: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <a href = "#" id = "GFG_UP"> LINK </a> <br><br> <button onclick = "gfg_Run()"> disable </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var link = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); function gfg_Run() { link.setAttribute("class", "disabled"); link.setAttribute("style", "color: black;"); down.innerHTML = "Link disabled"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example adds the class disable to the <a> element with the help of setAttributeNode() method by first creating an attribute using createAttribute() method and then adding it to the <a> element.
<!DOCTYPE HTML> <html> <head> <title> How to disable HTML links using JavaScript </title> <style> a.disabled { pointer-events: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <a href = "#" id = "GFG_UP"> LINK </a> <br><br> <button onclick = "gfg_Run()"> disable </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var link = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); function gfg_Run() { var attr = document.createAttribute("class"); attr.value = "disabled"; link.setAttributeNode(attr); link.setAttribute("style", "color: black;"); down.innerHTML = "Link disabled"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Disable HTML link using jQuery
jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements.Syntax:Return the value of an property:$(selector).prop(property)
Set the property and value:$(selector).prop(property,value)
Set property and value using a function:$(selector).prop(property,function(index,currentvalue))
Set multiple properties and values:$(selector).prop({property:value, property:value,...})
Parameters:property: This parameter specifies the name of the property.value: This parameter specifies the value of the property.function(index,currentvalue): This parameter specifies a function that returns the property value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current property value of selected elements.
Syntax:
Return the value of an property:$(selector).prop(property)
$(selector).prop(property)
Set the property and value:$(selector).prop(property,value)
$(selector).prop(property,value)
Set property and value using a function:$(selector).prop(property,function(index,currentvalue))
$(selector).prop(property,function(index,currentvalue))
Set multiple properties and values:$(selector).prop({property:value, property:value,...})
$(selector).prop({property:value, property:value,...})
Parameters:
property: This parameter specifies the name of the property.
value: This parameter specifies the value of the property.
function(index,currentvalue): This parameter specifies a function that returns the property value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current property value of selected elements.
index: This parameter receives the index position of element in the set.
currentValue: This parameter receives the current property value of selected elements.
addClass() Method: This method adds one or more than one class names to the specified elements. This method does not do anything with existing class attributes, it adds one or more than one class names to the class attribute.Syntax:$(selector).addClass(className,function(index,currentClass))
Parameters:className: This parameter is required. It specifies one or more than one class names to add.function(index,currentClass): This parameter is optional. It specifies a function that returns one or more class names to add.index: It returns the index position of the element in the set.className: It returns the current class name of the selected element.
Syntax:
$(selector).addClass(className,function(index,currentClass))
Parameters:
className: This parameter is required. It specifies one or more than one class names to add.
function(index,currentClass): This parameter is optional. It specifies a function that returns one or more class names to add.index: It returns the index position of the element in the set.className: It returns the current class name of the selected element.
index: It returns the index position of the element in the set.
className: It returns the current class name of the selected element.
Example 1: This example adds the class(‘disabled’) to the <a> element with the help of addClass() method.
<!DOCTYPE HTML> <html> <head> <title> How to disable HTML links using jQuery </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> a.disabled { pointer-events: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <a href = "#" id = "GFG_UP"> LINK </a> <br><br> <button onclick = "gfg_Run()"> disable </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> function gfg_Run() { $('a').addClass("disabled"); $('a').css('color', 'black'); $('#GFG_DOWN').text("Link disabled"); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example adds the class(‘disabled’) to the <a> element with the help of prop() method.
<!DOCTYPE HTML> <html> <head> <title> How to disable HTML links using jQuery </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> a.disabled { pointer-events: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <a href = "#" id = "GFG_UP"> LINK </a> <br><br> <button onclick = "gfg_Run()"> disable </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> function gfg_Run() { $('a').prop("class","disabled"); $('a').css('color', 'black'); $('#GFG_DOWN').text("Link disabled"); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
jQuery-Misc
JavaScript
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "Given an HTML link and the task is to disable the link by using JavaScript/jQuery."
},
{
"code": null,
"e": 146,
"s": 111,
"text": "Disable HTML link using... |
How HTTP POST request work in Node.js? | 07 Oct, 2021
POST is a request method supported by HTTP used by the World Wide Web. The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header. We use Express.js in order to create a server and to make requests (GET, POST, etc).
npm i express
Note: The npm in the above commands stands for node package manager, a place from where we install all the dependencies.
So in order to use Express to address POST requests on our server, we use the app.post method and then we specify the route, and we have a callback.
app.post(route, function(req, res){
//this is a callback function
})
Note: If you are going to make GET, POST request frequently in NodeJS, then use Postman , Simplify each step of building an API.
In this syntax, the route is where you have to post your data that is fetched from the HTML. For fetching data you can use bodyparser package.
Web Server: Create app.js in the root folder. Create your server as shown in the below example.
javascript
const express = require("express");const app = express(); // Define routes here ... app.listen(3000, function(){ console.log("server is running on port 3000");})
Handle Post Request: Here you will learn how to handle HTTP POST request and get data from the submitted form.
Create index.html in the root folder of your application and write following HTML code in it.
Filename: index.html
html
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Calculator</title></head> <body> <h1>Simple Calculator.</h1> <form action="/" method="post"> <input type="text" name="num1" placeholder="First Number"> <input type="text" name="num2" placeholder="Second Number"> <button type="submit" name="submit"> calculator </button> </form></body> </html>
Output:
Handle POST Route in Express.js: Filename: app.js
javascript
const express = require("express");const bodyParser = require("body-parser") // New app using express moduleconst app = express();app.use(bodyParser.urlencoded({ extended:true})); app.get("/", function(req, res) { res.sendFile(__dirname + "/index.html");}); app.post("/", function(req, res) { var num1 = Number(req.body.num1); var num2 = Number(req.body.num2); var result = num1 + num2 ; res.send("Addition - " + result);}); app.listen(3000, function(){ console.log("server is running on port 3000");})
Steps To Run:
npm init
npm install express
npm install body-parser
node app.js
go to http://localhost:3000 in your browser.
Output:
mridulmanochagfg
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 308,
"s": 28,
"text": "POST is a request method supported by HTTP used by the World Wide Web. The HTTP POST method sends data to the server. The type of the body of the request is indicated by the C... |
Python Program for Find minimum sum of factors of number | 22 Jun, 2022
Given a number, find minimum sum of its factors.Examples:
Input : 12
Output : 7
Explanation:
Following are different ways to factorize 12 and
sum of factors in different ways.
12 = 12 * 1 = 12 + 1 = 13
12 = 2 * 6 = 2 + 6 = 8
12 = 3 * 4 = 3 + 4 = 7
12 = 2 * 2 * 3 = 2 + 2 + 3 = 7
Therefore minimum sum is 7
Input : 105
Output : 15
Python3
# Python program to find minimum# sum of product of number # To find minimum sum of# product of numberdef findMinSum(num): sum = 0 # Find factors of number # and add to the sum i = 2 while(i * i <=num): while(num % i == 0): sum += i num //= i i += 1 sum += num # Return sum of numbers # having minimum product return sum # Driver Codenum = 12print (findMinSum(num)) # This code is contributed by Sachin Bisht
Output:
7
Time Complexity: O(n1/2 * log n)
Auxiliary Space: O(1)
Please refer complete article on Find minimum sum of factors of number for more details!
amartyaghoshgfg
amanjhaa15915
chandramauliguptach
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Iterate over characters of a string in Python
Python program to find second largest number in a list
Python program to interchange first and last elements in a list
Python | Convert set into a list
Appending to list in Python dictionary
Python program to find sum of elements in list | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 112,
"s": 52,
"text": "Given a number, find minimum sum of its factors.Examples: "
},
{
"code": null,
"e": 386,
"s": 112,
"text": "Input : 12\nOutput : 7\nExplanation: \nFollow... |
Python – turtle.Screen().setup() method | 20 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set the size and position of the main window.
Syntax : turtle.Screen().setup(width=0.5, height=0.75, startx=None, starty=None)
Parameters: This method has following parameters:
width: as integer a size in pixels, as float a fraction of the screen. Default is 50% of screen.
height: as integer the height in pixels, as float a fraction of the screen. Default is 75% of screen.
startx: if positive, starting position in pixels from the left edge of the screen, if negative from the right edge. Default, startx=None is to center window horizontally.
starty: if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge. Default, starty=None is to center window vertically.
Below is the implementation of above method with some examples :
Example 1: Change the configuration of the window.
Python3
# import turtle packageimport turtle # making turtle objectsc = turtle.Screen() # setup the screen sizesc.setup(400,400) # set the background colorsc.bgcolor("blue") # This code is contributed# by Deepanshu Rustagi.
Output :
Example 2: Change the position of the window by setting up the ‘startx’ and ‘starty’ in setup() method.
Python3
# import turtle packageimport turtle # making turtle objectsc = turtle.Screen() # set the screen size 400x400 pixels# set the screen position by# startx to 50# starty to-200sc.setup(400, 400, startx = 50, starty = -200) # set the background colorsc.bgcolor("blue") # This code is contributed # by Deepanshu Rustagi.
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a ver... |
PostgreSQL – DROP TABLESPACE | 08 Feb, 2021
In PostgreSQL, the DROP TABLESPACE statement is used to remove a tablespace.
Syntax: DROP TABLESPACE [IF EXISTS] tablespace_name;
Let’s analyze the above syntax:
First, specify the name of the tablespace that is to be deleted after the DROP TABLESPACE keywords.
Second, use the IF EXISTS option to handle errors in case the tablespace doesn’t exists.
Note: It is important to note that only tablespace owners or superusers can execute the DROP TABLESPACE statement.
Example:
First, we create a new tablespace named gfg and map it to the C:\data\gfg directory:
CREATE TABLESPACE gfg
LOCATION 'C:\data\gfg';
Now create a database named db_gfg and set its tablespace to gfg:
CREATE DATABASE db_gfg
TABLESPACE = gfg;
Now create a new table named test in the db_gfg and set it tablespace to gfg:
CREATE TABLE test (
ID serial PRIMARY KEY,
title VARCHAR (255) NOT NULL
) TABLESPACE gfg;
The following statement returns all objects in the gfg tablespace:
SELECT
table_space.spcname,
class.relname
FROM
pg_class class
JOIN pg_tablespace table_space
ON class.reltablespace = table_space.oid
WHERE
table_space.spcname = 'gfg';
This will lead to the following:
Now if you try to drop the gfgtablespace:
DROP TABLESPACE gfg;
This will raise the following error:
As the gfg tablespace is not empty,it is not possible to drop the tablespace. Now, login to the Postgres database and drop the db_gfg database:
DROP DATABASE db_gfg;
Now delete the gfg tablespace again:
DROP TABLESPACE gfg;
Now check for the tablespace using the below command to verify:
\db+
Output:
postgreSQL-administration
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - EXISTS Operator
PostgreSQL - CREATE SCHEMA
PostgreSQL - LEFT JOIN
PostgreSQL - SELECT | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "In PostgreSQL, the DROP TABLESPACE statement is used to remove a tablespace."
},
{
"code": null,
"e": 158,
"s": 105,
"text": "Syntax: DROP TABLESPACE [IF E... |
How to get font properties of particular element in JavaScript ? | 18 Jun, 2019
Give a string element and the task is to get the font properties of a particular element using JavaScript.
Approach:
Store a string to the variable.
Then use element.style.property to get the propertyValue of that element property.
Example 1: This example gets the font-family of the element [id = ‘GFG_UP’].
<!DOCTYPE HTML> <html> <head> <title> How to get the font family property of a particular element in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px; font-family: sans-serif; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 30px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "click on button to get the font property"; el_up.innerHTML = str; function gfg_Run() { el_down.innerHTML = "font-style is '" + el_up.style.fontFamily + "'"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example gets the font-weight of the element [id = ‘GFG_UP’].
<!DOCTYPE HTML> <html> <head> <title> How to get the font weight property of a particular element in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px; font-family: sans-serif; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 30px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "click on button to get the font property"; el_up.innerHTML = str; function gfg_Run() { el_down.innerHTML = "font-weight is '"+el_up.style.fontWeight + "'"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "Give a string element and the task is to get the font properties of a particular element using JavaScript."
},
{
"code": null,
"e": 145,
"s": 135,
"text": ... |
Python | Timing and Profiling the program | 12 Jun, 2019
Problems – To find where the program spends its time and make timing measurements.
To simply time the whole program, it’s usually easy enough to use something like the Unix time command as shown below.
Code #1 : Command to time the whole program
bash % time python3 someprogram.pyreal 0m13.937suser 0m12.162ssys 0m0.098sbash %
On the other extreme, to have a detailed report showing what the program is doing, cProfile module is used.
bash % python3 -m cProfile someprogram.py
Output :
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
263169 0.080 0.000 0.080 0.000 someprogram.py:16(frange)
513 0.001 0.000 0.002 0.000 someprogram.py:30(generate_mandel)
262656 0.194 0.000 15.295 0.000 someprogram.py:32()
1 0.036 0.036 16.077 16.077 someprogram.py:4()
262144 15.021 0.000 15.021 0.000 someprogram.py:4(in_mandelbrot)
1 0.000 0.000 0.000 0.000 os.py:746(urandom)
1 0.000 0.000 0.000 0.000 png.py:1056(_readable)
1 0.000 0.000 0.000 0.000 png.py:1073(Reader)
1 0.227 0.227 0.438 0.438 png.py:163()
512 0.010 0.000 0.010 0.000 png.py:200(group)
More often than not, profiling the code lies somewhere in between these two extremes. For example, if one already knows that the code spends most of its time in a few selected functions. For selected profiling of functions, a short decorator can be useful. Code #3: Using short decorator for selected profiling of functions
# abc.py import timefrom functools import wraps def timethis(func): @wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() r = func(*args, **kwargs) end = time.perf_counter() print('{}.{} : {}'.format(func.__module__, func.__name__, end - start)) return r return wrapper
To use the decorator, simply place it in front of a function definition to get timings from it as shown in the code below.Code #4 :
@abcdef countdown(n): while n > 0: n -= 1 countdown(10000000)
Output :
__main__.countdown : 0.803001880645752
Code #5: Defining a context manager to time a block of statements.
from contextlib import contextmanager def timeblock(label): start = time.perf_counter() try: yield finally: end = time.perf_counter() print('{} : {}'.format(label, end - start))
Code #6: How the context manager works
with timeblock('counting'): n = 10000000 while n > 0: n -= 1
Output :
counting : 1.5551159381866455
Code #7 : Using timeit module to study the performance of small code fragments
from timeit import timeitprint (timeit('math.sqrt(2)', 'import math'), "\n") print (timeit('sqrt(2)', 'from math import sqrt'))
Output :
0.1432319980012835
0.10836604500218527
timeit works by executing the statement specified in the first argument a million times and measuring the time.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "Problems – To find where the program spends its time and make timing measurements."
},
{
"code": null,
"e": 230,
"s": 111,
"text": "To simply time the whol... |
Efficient way to initialize a priority queue | 22 Jun, 2022
STL Priority Queue is the implementation of Heap Data Structure. By default, it’s a max heap, and can be easily for primitive data types. There are some important applications of it which can be found in this article.
Priority queue can be initialized in two ways either by pushing all elements one by one or by initializing using their constructor. In this article, we will discuss both methods and examine their time complexities.
Method 1: The simplest approach is to traverse the given array and push each element one by one in the priority queue. In this method, the push method in the priority queue takes O(log N) time. Where N is the number of elements in the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to initialize the// priority queue#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int arr[] = { 15, 25, 6, 54, 45, 26, 12 }; int N = sizeof(arr) / sizeof(arr[0]); // Initialize priority_queue priority_queue<int> pq; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Push the element arr[i] pq.push(arr[i]); } cout << "The elements in priority" << " Queue are: "; // Traverse until pq is non-empty while (!pq.empty()) { // Print the element in pq cout << pq.top() << " "; // Pop the top element pq.pop(); } return 0;}
// Java program to initialize the// priority queueimport java.util.*;public class GFG{ public static void main(String[] args) { int[] arr = { 15, 25, 6, 54, 45, 26, 12 }; int N = arr.length; // Initialize priority_queue Vector<Integer> pq = new Vector<Integer>(); // Traverse the array arr[] for (int i = 0; i < N; i++) { // Push the element arr[i] pq.add(arr[i]); } Collections.sort(pq); Collections.reverse(pq); System.out.print("The elements in priority" + " Queue are: "); // Traverse until pq is non-empty while (pq.size() > 0) { // Print the element in pq System.out.print(pq.get(0) + " "); // Pop the top element pq.remove(0); } }} // This code is contributed by divyesh072019.
# Python3 program to initialize the# priority queue # Driver Codeif __name__ == '__main__': arr = [15, 25, 6, 54, 45, 26, 12] N = len(arr) # Initialize priority_queue pq = [] # Traverse the array arr[] for i in range(N): # Push the element arr[i] pq.append(arr[i]) print("The elements in priority Queue are: ", end = "") pq = sorted(pq) # Traverse until pq is non-empty while (len(pq) > 0): # Print the element in pq print(pq[-1], end = " ") # Pop the top element del pq[-1] # This code is contributed by mohit kumar 29.
// C# program to initialize the// priority queueusing System;using System.Collections.Generic;class GfG{ public static void Main() { int[] arr = { 15, 25, 6, 54, 45, 26, 12 }; int N = arr.Length; // Initialize priority_queue List<int> pq = new List<int>(); // Traverse the array arr[] for (int i = 0; i < N; i++) { // Push the element arr[i] pq.Add(arr[i]); } pq.Sort(); pq.Reverse(); Console.Write("The elements in priority" + " Queue are: "); // Traverse until pq is non-empty while (pq.Count > 0) { // Print the element in pq Console.Write(pq[0] + " "); // Pop the top element pq.RemoveAt(0); } }} // This code is contributed by divyeshrabadiya07.
<script> // Javascript program to initialize the priority queue let arr = [ 15, 25, 6, 54, 45, 26, 12 ]; let N = arr.length; // Initialize priority_queue let pq = []; // Traverse the array arr[] for (let i = 0; i < N; i++) { // Push the element arr[i] pq.push(arr[i]); } pq.sort(function(a, b){return a - b}); pq.reverse(); document.write("The elements in priority" + " Queue are: "); // Traverse until pq is non-empty while (pq.length > 0) { // Print the element in pq document.write(pq[0] + " "); // Pop the top element pq.shift(); } // This code is contributed by suresh07.</script>
The elements in priority Queue are: 54 45 26 25 15 12 6
Time Complexity: O(N*log N), where N is the total number of elements in the array.Auxiliary Space: O(N)
Method 2: In this method, copy all the array elements into the priority queue while initializing it (this copying will be happened using the copy constructor of priority_queue). In this method, the priority_queue will use the build heap method internally. So the build heap method is taking O(N) time.
Syntax:
priority_queue<int> pq(address of the first element, address of the next of the last element);
Syntax for the array:
priority_queue<int> pq (arr, arr + N)where arr is the array and N is the size of the array.
Syntax for the vector:
priority_queue<int> pq(v.begin(), v.end()); where v is the vector.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to initialize the// priority queue#include <iostream>#include <queue>using namespace std; // Driver Codeint main(){ int arr[] = { 15, 25, 6, 54, 45, 26, 12 }; int N = sizeof(arr) / sizeof(arr[0]); // By this type of initialization // the priority_queue is using // build heap to make the max heap cout << "The elements in priority" << " Queue are: "; // Initialize priority_queue priority_queue<int> pq(arr, arr + N); // Iterate until pq is non empty while (!pq.empty()) { // Print the element cout << pq.top() << " "; pq.pop(); } return 0;}
// Java program for the above approachimport java.util.*; class GFG { public static void main(String[] args) { Integer[] arr = { 15, 25, 6, 54, 45, 26, 12 }; int N = arr.length; // By this type of initialization // the priority_queue is using // build heap to make the max heap System.out.println("The elements in priority" + " Queue are: "); // Initialize priority_queue ArrayList<Integer> l = new ArrayList<Integer>(); Collections.addAll(l, arr); Collections.sort(l); // Iterate until pq is non empty while (l.size() != 0) { // Print the element System.out.print(l.get(l.size() - 1) + " "); l.remove(l.size() - 1); } }} // This code is contributed by phasing17
# Python3 program to initialize the# priority queue # Driver Codeif __name__=='__main__': arr = [ 15, 25, 6, 54, 45, 26, 12 ] N = len(arr) # By this type of initialization # the priority_queue is using # build heap to make the max heap print("The elements in priority Queue are: ", end = '') # Initialize priority_queue pq = arr pq.sort() # Iterate until pq is non empty while (len(pq) != 0): # Print the element print(pq[-1], end = ' ') pq.pop() # This code is contributed by rutvik_56.
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Driver Codepublic static void Main(string[] args){ int []arr= { 15, 25, 6, 54, 45, 26, 12 }; int N = arr.Length; // By this type of initialization // the priority_queue is using // build heap to make the max heap Console.Write("The elements in priority" + " Queue are: "); // Initialize priority_queue List<int> l = new List<int>(arr); l.Sort(); // Iterate until pq is non empty while (l.Count!=0) { // Print the element Console.Write(l[l.Count-1]+ " "); l.RemoveAt(l.Count-1); }}} // This code is contributed by noob2000.
<script>// JAvaScript program to initialize the// priority queuelet arr = [ 15, 25, 6, 54, 45, 26, 12 ];let N = arr.length; // By this type of initialization// the priority_queue is using// build heap to make the max heapdocument.write("The elements in priority Queue are: ") // Initialize priority_queuelet pq = arr;pq.sort(function(a, b){return a - b;}); // Iterate until pq is non emptywhile(pq.length != 0) // Print the element document.write(pq.pop()+" "); // This code is contributed by unknown2108</script>
The elements in priority Queue are: 54 45 26 25 15 12 6
Time Complexity: O(N), where N is the total number of elements in the array.Auxiliary Space: O(N)
mohit kumar 29
divyeshrabadiya07
divyesh072019
rutvik_56
suresh07
Akanksha_Rai
simranarora5sos
unknown2108
pankajsharmagfg
noob2000
surindertarika1234
phasing17
cpp-priority-queue
priority-queue
Data Structures
Heap
Data Structures
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "STL Priority Queue is the implementation of Heap Data Structure. By default, it’s a max heap, and can be easily for primitive data types. There are some important applications... |
Python | shutil.copytree() method | 25 Jun, 2019
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying. Permissions and times of directories are copied with copystat() and individual files are copied using shutil.copy2().
Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)Parameters:src: A string representing the path of the source directory.dest: A string representing the path of the destination.symlinks (optional) : This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.ignore (optional) : If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy() for this parameter.igonre_dangling_symlinks (optional) : This parameter value when set to True is used to put a silence on the exception raised if the file pointed by the symlink doesn’t exist.Return Value: This method returns a string which represents the path of newly created directory.
Example #1 :Using shutil.copytree() method to copy file from source to destination
# Python program to explain shutil.copytree() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users / Rajnish / Desktop / GeeksforGeeks' # List files and directories # in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' print("Before copying file:") print(os.listdir(path)) # Source path src = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / source' # Destination path dest = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / destination' # Copy the content of # source to destination destination = shutil.copytree(src, dest) # List files and directories # in "C:/Users / Rajnish / Desktop / GeeksforGeeks" print("After copying file:") print(os.listdir(path)) # Print path of newly # created file print("Destination path:", destination)
Before copying file:
['source']
After copying file:
['destination', 'source']
Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination
Example #2 :Using shutil.copytree() method to copy file by using shutil.copy() method.
# Python program to explain shutil.copytree() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users / Rajnish / Desktop / GeeksforGeeks' # List files and directories # in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' print("Before copying file:") print(os.listdir(path)) # Source path src = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / source' # Destination path dest = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / destination' # Copy the content of # source to destination # using shutil.copy() as parameterdestination = shutil.copytree(src, dest, copy_function = shutil.copy) # List files and directories # in "C:/Users / Rajnish / Desktop / GeeksforGeeks" print("After copying file:") print(os.listdir(path)) # Print path of newly # created file print("Destination path:", destination)
Before copying file:
['source']
After copying file:
['destination', 'source']
Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination
Python-shutil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 615,
"s": 28,
"text": "Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps... |
Maximum value of unsigned long long int in C++ | 03 Dec, 2020
In this article, we will discuss the unsigned long long int data type in C++. It is the largest (64 bit) integer data type in C++.
Some properties of the unsigned long long int data type are:
An unsigned data type stores only positive values.
It takes a size of 64 bits.
A maximum integer value that can be stored in an unsigned long long int data type is 18, 446, 744, 073, 709, 551, 615, around 264 – 1(but is compiler dependent).
The maximum value that can be stored in unsigned long long int is stored as a constant in <climits> header file whose value can be used as ULLONG_MAX.
The minimum value that can be stored in unsigned long long int is zero.
In case of overflow or underflow of data type, the value is wrapped around. For example, if 0 is stored in an unsigned long long int data type and 1 is subtracted from it, the value in that variable will become equal to 18, 446, 744, 073, 709, 551, 615. Similarly, in the case of overflow, the value will round back to 0.
Below is the program to get the highest value that can be stored in unsigned long long int in C++:
C++
// C++ program to obtain the maximum// value stored in unsigned long long int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file unsigned long long int valueFromLimits = ULLONG_MAX; cout << "Value from climits " << "constant: "; cout << valueFromLimits << "\n"; // Using the wrap around property // of data types // Initialize a variable with value 0 unsigned long long int value = 0; // Subtract 1 from value since an // unsigned data type cannot store // negative number, the value will // wrap around and stores maximum // value stored in it value = value - 1; cout << "Value using the wrap" << " around property: " << value << "\n"; return 0;}
Value from climits constant: 18446744073709551615
Value using the wrap around property: 18446744073709551615
Data Type
Data Types
large-numbers
C++
C++ Programs
Data Type
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "In this article, we will discuss the unsigned long long int data type in C++. It is the largest (64 bit) integer data type in C++. "
},
{
"code": null,
"e": 221,
... |
ISRO | ISRO CS 2013 | Question 25 | 10 May, 2018
Consider the following dependencies and the BOOK table in a relational database design. Determine the normal form of the given relation.
ISBN → Title
ISBN → Publisher
Publisher → Address
(A) First Normal Form(B) Second Normal Form(C) Third Normal Form(D) BCNFAnswer: (B)Explanation: Candidate key = ISBNFor a relation having functional dependencies of the form α → β, a relation is in 2-NF if:i) α should not be a proper subset of the candidate key, or,ii) β – α should be a prime attribute.
First condition satisfies as the candidate key contains only one attribute.
So, this relation is in 2-NFQuiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2018"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "Consider the following dependencies and the BOOK table in a relational database design. Determine the normal form of the given relation."
},
{
"code": null,
"e": 2... |
Add 2 hours to current time in MySQL? | We can get the current time with the help of now() and adding 2 hours is done by giving the interval as 2. Firstly, collect information of the current time in the system with the help of now(). The current time is .
The following is the query to get the current date and time.
mysql> select now();
Here is the output.
+---------------------+
| now() |
+---------------------+
| 2018-11-01 12:58:40 |
+---------------------+
1 row in set (0.00 sec)
To add 2 hours in the current time, we will use the DATE_ADD() function.
mysql> select DATE_ADD(now(),interval 2 hour);
The following is the output that displays.
+---------------------------------+
| DATE_ADD(now(),interval 2 hour) |
+---------------------------------+
| 2018-11-01 14:58:31 |
+---------------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "We can get the current time with the help of now() and adding 2 hours is done by giving the interval as 2. Firstly, collect information of the current time in the system with the help of now(). The current time is ."
},
{
"code": null,
"e": ... |
Explicit Type Casting in Python Language | All of us can declare and work with data types. Have we ever wondered about their interconversion? In this article, we learn about how we can convert these data types using inbuilt functions in Python a.k.a Type Casting. Type Casting is of two types: Implicit & Explicit. In this module, we are going to discuss about Explicit type casting only.
Now let’s have a look at some basic & type conversions
The int() function allows us to convert any data type to integer. It accepts exactly two parameters namely Base and Number where Base signifies the base of which integer value belongs to ( binary[2], octal[8], hexadecimal[16]).
The float() function allows us to convert any data type to a floating point number. It accepts exactly one parameter i.e. the value of data type that needs to be converted.
#Type casting
value = "0010110"
# int base 2
p = int(value,2)
print ("integer of base 2 format : ",p)
# default base
d=int(value)
print ("integer of default base format : ",d)
# float
e = float(value)
print ("corresponding float : ",e)
integer of base 2 format : 22
integer of default base format : 10110
corresponding float : 10110.0
In the above code, we have also converted integer with base in Python
The tuple() function allows us to convert to a tuple. It accepts exactly one parameter either a string or a list.
The list() function allows us to convert any data type to a list type. It accepts exactly one parameter.
The dict() function is used to convert a tuple of order (key, value) into a dictionary. Key must be unique in nature otherwise duplicate value gets overridden.
#Type casting
str_inp = 'Tutorialspoint'
# converion to list
j = list(str_inp)
print ("string to list : ")
print (j)
# conversion to tuple
i = tuple(str_inp)
print ("string to tuple : ")
print (i)
# nested tuple
tup_inp = (('Tutorials', 0) ,('Point', 1))
# conversion to dictionary
c = dict(tup_inp)
print ("list to dictionary : ",c)
# nested list
list_inp = [['Tutorials', 0] ,['Point', 1]]
# conversion to dictionary
d = dict(list_inp)
print ("list to dictionary : ",d)
string to list :
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
string to tuple :
('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
list to dictionary : {'Tutorials': 0, 'Point': 1}
list to dictionary : {'Tutorials': 0, 'Point': 1}
The str() function is used to convert integer or float into a string. It accepts exactly one argument.
chr()-This function is used to convert a integer type to character type.
ord()-This function is used to convert a character type to integer type.
#Type casting
char_inp = 'T'
#converting character to corresponding integer value
print ("corresponding ASCII VALUE: ",ord(char_inp))
int_inp=92
#converting integer to corresponding Ascii Equivalent
print ("corresponding ASCII EQUIVALENT: ",chr(int_inp))
#integer and float value
inp_i=231
inp_f=78.9
# string equivalent
print ("String equivalent",str(inp_i))
print ("String equivalent",str(inp_f))
corresponding ASCII VALUE: 84
corresponding ASCII EQUIVALENT: \
String equivalent 231
String equivalent 78.9
In this article, we learnt about explicit type casting in Python 3.x. Or earlier. | [
{
"code": null,
"e": 1408,
"s": 1062,
"text": "All of us can declare and work with data types. Have we ever wondered about their interconversion? In this article, we learn about how we can convert these data types using inbuilt functions in Python a.k.a Type Casting. Type Casting is of two types: Im... |
How to Ace the In Person Data Science Interview | by Kristen Kehrer | Towards Data Science | I’ve written previously about my recent job hunt, but this article is solely devoted to the in-person interview. That full-day, try to razzle-dazzle em’, cross your fingers and hope you’re well prepared for what gets thrown at you. After attending a ton of these interviews, I’ve found that they tend to follow some pretty standard schedules.
You may meet with 3–7 different people, and throughout the span of meeting with these different people, you’ll probably cover:
Tell me about yourself
Behavioral questions
“White boarding” SQL
“White boarding” code
Talking about items on your resume
Simple analysis questions
Asking questions of your own
I’ve mentioned this before when talking about phone screens. The way I approach this never changes. People just want to hear that you can speak to who you are and what you’re doing. Mine was some variation of:
I am a Data Scientist with 8 years of experience using statistical methods and analysis to solve business problems across various industries. I’m skilled in SQL, model building in R, and I’m currently learning Python.
Almost every company I spoke with asked questions that should be answered in the STAR format. The most prevalent STAR questions I’ve seen in Data Science interviews are:
Tell me about a time you explained technical results to a non-technical person
Tell me about a time you improved a process
Tell me about a time with a difficult stakeholder, and how was it resolved
The goal here is to concisely and clearly explain the Situation, Task, Action and Result.
My response to the “technical results” questions would go something like this:
Vistaprint is a company that sells marketing materials for small businesses online (always give context, the interviewer may not be familiar with the company). I had the opportunity to do a customer behavioral segmentation using k-means. This involved creating 54 variables, standardizing the data, plenty of analysis, etc. When it was time to share my results with stakeholders, I had really taken this information up a level and built out the story. Instead of talking about the methodology, I spoke to who the customer segments were and how their behaviors were different. I also stressed that this segmentation was actionable! We could identify these customers in our database, develop campaigns to target them, and I gave examples of specific campaigns we might try. This is an example of when I explained technical results to non-technical stakeholders. (always restate the question afterwards).
For me, these questions required some preparation time. I gave some real thought to my best examples from my experience, and practiced saying the answer. This time paid-off. I was asked these same questions over and over throughout my interviewing.
This is when the interviewer has you stand at the whiteboard an answer some SQL questions. If a job description asks for SQL, this is fair game. In most scenarios, they’ll tape a couple pieces of paper up on the whiteboard. One will be a table with (for example) ids and names (lets call this NamesTable), the other paper might include ids, dates, and purchases (lets call this PurchasesTable). You get the idea, you’re about to write SQL queries to answer their questions.
They’ll ask a series of questions such as:
Write a query to get all of the names —
select names from NamesTable
Write a query to get the names and purchases —
select names, purchasesfrom NamesTable as njoin PurchasesTable as pon n.id = p.id
Write a query to get the names and purchases for purchases made after some date (that they randomly pick, here is December 2017)
select names, purchasesfrom NamesTable as njoin PurchasesTable as pon n.id = p.id where p.dates > ‘2017–12–31’
Write a query to get the names and count of purchases for those having at least 2 purchases
select names, count(purchases) as cntfrom NamesTable as njoin PurchasesTable as pon n.id = p.idgroup by nameshaving count(purchases) ≥ 2
You get the idea. An interviewer once asked me a query that required joining back to the same table, but I haven’t experienced it being much more complex than this.
As mentioned in my previous article. I was asked FizzBuzz two days in a row by two different companies. A possible way to write the solution in Python (just took a screenshot of my computer) is below:
The coding problem will most likely involve some loops, logic statements and may have you define a function. If a specific language is mentioned on the job description, they may want to see the answer in that language. The hiring manager wants to be sure that when you say you can code, you at least have some basic programming knowledge.
I’ve been asked about all the methods I mention on my resume at one point or another (regression, classification, time-series analysis, MVT testing, etc). I don’t mention my thesis from my Master’s Degree on my resume, but casually referenced it when asked if I had previously had experience with Bayesian methods. The interviewer followed up with a question on the prior distributions used in my thesis.
I had finished my thesis 9 years ago, couldn’t remember the priors and told him I’d need to follow up. I did follow up and sent him the answer to his question. They did offer me a job, but it’s not a scenario you want to find yourself in. If you are going to reference something, be able to speak to it. Even if it means refreshing your memory by looking at wikipedia ahead of the interview. Things on your resume and projects you mention should be a home run.
Some basic questions will be asked to make sure that you have an understanding of how numbers work. The question may require you to draw a graph or use some algebra to get at an answer, and it’ll show that you have some business context and can explain what is going on. Questions around changes in conversion, average sale price, why is revenue down in this scenario? What model would you choose in this scenario? Typically I’m asked two or three questions of this type.
I was asked a probability question at one interview. They asked what the expected value was of rolling a fair die. I was then asked if the die was weighted in a certain way, what would the expected value of that die be. I wasn’t allowed to use a calculator.
Tell me about the behaviors of a person that you would consider a high-performing/high-potential employee.
Honestly, I used the question above to try and get at whether you needed to work 60 hours a week and work on the weekends to be someone who stood out. I pretty frequently work on the weekends because I enjoy what I do, I wouldn’t enjoy it if it was expected.
What software are you using?
Really, I like to get this question out of the way during the phone screen. I’m not personally interested in working for a SAS shop, so I’d want to know that upfront. My favorite response to this question is “you can use whatever open source tools you’d like as long as it’s appropriate for the problem.”
Is there anything else I can tell you about my skills and qualifications to let you know that I am a good fit for this job?
This is your opportunity to let them tell you if there is anything that you haven’t covered yet, or that they might be concerned about. You don’t want to leave an interview with them feeling like they didn’t get EVERYTHING they needed to make a decision on whether or not to hire you.
When can I expect to hear from you?
I also ask about the reporting structure, and I certainly ask about what type of projects I’d be working on soon after starting (if that is not already clear).
I wish you so much success in your data science interviews. Hopefully you meet a lot of great people, and have a positive experience. After each interview, remember to send your thank you notes! If you do not receive an offer, or do not accept an offer from a given company, still go on LinkedIn and send them connection requests. You never know when timing might be better in the future and your paths might cross.
If you liked this article, visit my website! Here | [
{
"code": null,
"e": 515,
"s": 172,
"text": "I’ve written previously about my recent job hunt, but this article is solely devoted to the in-person interview. That full-day, try to razzle-dazzle em’, cross your fingers and hope you’re well prepared for what gets thrown at you. After attending a ton o... |
How to remove Ttk Notebook Tab Dashed Line? (tkinter) | In order to work with Tabs and separate your workflow in an application, Tkinter provides a Notebook widget. We can use the Notebook widget to create Tabs in an application. Tabs are useful to isolate one particular frame or event from another.
Generally, Notebook widget can be configured and styled using the ttk themed widget. So, to style a Notebook widget, we pass TNotebook and TNotebook.Tab parameters in the configuration. If we click on a particular Tab, there may appear some rectangular dashed line which can be removed.
# Import the required library
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
win.geometry("700x350")
# Create an instance of ttk
style = ttk.Style()
# Define Style for Notebook widget
style.layout("Tab", [('Notebook.tab', {'sticky': 'nswe', 'children':
[('Notebook.padding', {'side': 'top', 'sticky': 'nswe', 'children':
[('Notebook.label', {'side': 'top', 'sticky': ''})],
})],
})]
)
# Use the Defined Style to remove the dashed line from Tabs
style.configure("Tab", focuscolor=style.configure(".")["background"])
# Create a Notebook widget
my_notebook= ttk.Notebook(win)
my_notebook.pack(expand=1,fill=BOTH)
# Creating Tabs
tab1 = ttk.Frame(my_notebook)
my_notebook.add(tab1, text= "Tab 1")
tab2 = ttk.Frame(my_notebook)
my_notebook.add(tab2, text= "Tab2")
# Create a Label in Tabs
Label(tab1, text= "Hello, Howdy?",
font = ('Helvetica 20 bold')).pack()
Label(tab2, text= "This is a New Tab Context",
font = ('Helvetica 20 bold')).pack()
win.mainloop()
Executing the above code will display a window containing multiple tabs.
When we switch tabs from the window, it will display its content | [
{
"code": null,
"e": 1307,
"s": 1062,
"text": "In order to work with Tabs and separate your workflow in an application, Tkinter provides a Notebook widget. We can use the Notebook widget to create Tabs in an application. Tabs are useful to isolate one particular frame or event from another."
},
... |
How to implement a Gaussian Naive Bayes Classifier in Python from scratch? | by Vasile Păpăluță | Towards Data Science | Did you ever ask yourself what is the oldest Machine Learning algorithm?
Today we have a lot of Machine Learning algorithms, from simple KNN to ensemble algorithms one and even neural networks. Sometimes they look so complicated that you can think that they were developed in the latest years, and Machine Learning, in general, is something new. But the first algorithms appeared earlier than you think.
Naive Bayes algorithm is one of the oldest forms of Machine Learning. The Bayes Theory (on which is based this algorithm) and the basics of statistics were developed in the 18th century. Since them until in 50' al the computations were done manually until appeared the first computer implementation of this algorithm.
But what does this algorithm so simple that it could be used to manually?
The simplest form of this algorithm is formed from 2 main parts:
The Naive Bayes formula (Theorem).
And a distribution (in this case Gaussian one).
The Naive Bayes Theorey in the most cases can be reduced to a formula:
This formula means that the probability of happening of the event A knowing that event B happened already..
Somehow the explanation of how Naive Bayes Theory is out of the scope of this article, that’s why I highly recommend you to read this article on NB theory.
Distribution, basically show how values are dispersed in series, and how frequently they appear in this series. Here is an example:
How you can see in the plot above, the Gaussian or Normal Distribution depends on 2 parameters of a series — The mean and the standard Deviation. Knowing these 2 parameters of the series we can find it’s distribution function. It has the next form:
But, why do we need this function? Very simple, the majority of data in the world is represented as continuous values, but guess what, you can’t calculate the probability of the value X to get the value v. It would be 0. Why? Technically when you divide something by infinity you get what? correct — zero.
So, how we can solve this problem? Of course, using the Gaussian Distribution Function, illustrated above. Imputing instead of x their value from a series, the mean value of the series and its standard deviation you can find out the probability that the value x will occur. Voila.
I don’t know why, but personally for me sometimes was easier to understand how an algorithm work by implimenting it in code. So let’s start:
Firstly let’s import all dempendencies:
Firstly let’s import all dempendencies:
# Importing all needed librariesimport numpy as npimport math
That’s all, yeah we need the pure numpy and math library.
2. Now let’s create a class that will have the implimentation of the algorithm and first function that will separate our data set by class.
# gaussClf will be the class that will have the Gaussian naive bayes classifier implimentationclass gaussClf: def separate_by_classes(self, X, y): ''' This function separates our dataset in subdatasets by classes ''' self.classes = np.unique(y) classes_index = {} subdatasets = {} cls, counts = np.unique(y, return_counts=True) self.class_freq = dict(zip(cls, counts)) print(self.class_freq) for class_type in self.classes: classes_index[class_type] = np.argwhere(y==class_type) subdatasets[class_type] = X[classes_index[class_type], :] self.class_freq[class_type] = self.class_freq[class_type]/sum(list(self.class_freq.values())) return subdatasets
separate_by_classes function separates out dataset by classes to calculate the mean and standart deviations for every column, separatly for every class.
3. The fit function.
def fit(self, X, y): ''' The fitting function ''' separated_X = self.separate_by_classes(X, y) self.means = {} self.std = {} for class_type in self.classes: # Here we calculate the mean and the standart deviation from datasets self.means[class_type] = np.mean(separated_X[class_type], axis=0)[0] self.std[class_type] = np.std(separated_X[class_type], axis=0)[0]
Next goes the fit function, where we just calculate for every class the mean and the standart deviation for every column.
4. The Gaussian Distribution Function.
def calculate_probability(self, x, mean, stdev): ''' This function calculates the class probability using gaussian distribution ''' exponent = math.exp(-((x - mean) ** 2 / (2 * stdev ** 2))) return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent
The calculate_probability function calculates using the mean and standart deviation of a series the probability that a functions will accur in a series.
5. The predict_function.
def predict_proba(self, X): ''' This function predicts the probability for every class ''' self.class_prob = {cls:math.log(self.class_freq[cls], math.e) for cls in self.classes} for cls in self.classes: for i in range(len(self.means)): print(X[i]) self.class_prob[cls]+=math.log(self.calculate_probability(X[i], self.means[cls][i], self.std[cls][i]), math.e) self.class_prob = {cls: math.e**self.class_prob[cls] for cls in self.class_prob} return self.class_prob
Here is the function that returns a dictionary with probabilities of the sample to belong to a class. In classic sklearn estimators predict_proba function gets a list of samples and return a list of labels. To make it more easy to use I decided to impliment it only for one sample.
Also in this funtion I don’t compute the prior probability, to get read of useless computatuion, because for every class estiamtion you need to divide to the same value getted value above.
6. The predict function.
def predict(self, X): ''' This funtion predicts the class of a sample ''' pred = [] for x in X: pred_class = None max_prob = 0 for cls, prob in self.predict_proba(x).items(): if prob>max_prob: max_prob = prob pred_class = cls pred.append(pred_class) return pred
Here I decided to use the classic method of it’s implimentation. List in, list out.
You can see the code on my github repository.
Now let’s compare our implementation with sklearn one. In sklearn library, the Gaussian Naive Bayse is implemented as GaussianNB class, and to import it you should write this piece of code:
from sklearn.naive_bayes import GaussianNB
The implementation we will let on you, you can find how to do it there. So what are the results, on the iris dataset?
Our implimentation: 0.868421052631579 accuracy
Sklearn implimentation: 1.0 accuaracy.
That happened because the sklearn model uses a little other implementation of this model than we used, you can read more on the sklearn website.
So in this article, I showed you how to implement the most simple form of practically the oldest Machine Learning algorithm, Gaussian Naive Bayes algorithm and shortly how it works. I highly recommend you to learn how works the sklearn implementation and try to implement the BernoulliNB on your own. | [
{
"code": null,
"e": 245,
"s": 172,
"text": "Did you ever ask yourself what is the oldest Machine Learning algorithm?"
},
{
"code": null,
"e": 576,
"s": 245,
"text": "Today we have a lot of Machine Learning algorithms, from simple KNN to ensemble algorithms one and even neural ne... |
Detect Loop in linked list | Practice | GeeksforGeeks | Given a linked list of N nodes. The task is to check if the linked list has a loop. Linked list can contain self loop.
Example 1:
Input:
N = 3
value[] = {1,3,4}
x = 2
Output: True
Explanation: In above test case N = 3.
The linked list with nodes N = 3 is
given. Then value of x=2 is given which
means last node is connected with xth
node of linked list. Therefore, there
exists a loop.
Example 2:
Input:
N = 4
value[] = {1,8,3,4}
x = 0
Output: False
Explanation: For N = 4 ,x = 0 means
then lastNode->next = NULL, then
the Linked list does not contains
any loop.
Your Task:
The task is to complete the function detectloop() which contains reference to the head as only argument. This function should return true if linked list contains loop, else return false.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 104
1 ≤ Data on Node ≤ 103
0
laxmankohar714 hours ago
Java Solution Using Two Pointer Technique
public static boolean detectLoop(Node head){ Node slow_ptr = head; Node fast_ptr = head; while(slow_ptr != null && fast_ptr != null && fast_ptr.next != null){ slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next.next; if(slow_ptr == fast_ptr){ return true; } } return false; }
0
yuvrajranabtcse201 day ago
c++ ans...time o(n) space o(1)...
Node *dub=head->next;; Node *sing=head; while((sing!=NULL)&&(dub!=NULL)){ if(dub==sing)return true; dub=dub->next; if(dub!=NULL)dub=dub->next; sing=sing->next; } return false; }
0
hardik200404
This comment was deleted.
+2
pankaj0064 days ago
what sort of explanation is given, don't understand this x concept. Not mentioned anywhere
0
thatspykid5 days ago
Simple C++ Solution using two poniters method:
bool detectLoop(Node* head) { // your code here Node* slow = head; Node* fast = head; while(slow && fast && fast->next) { slow = slow->next; fast = fast->next->next; if(slow == fast) { return true; } } return false; }
// @ that_spy_kid
0
ksbsbisht1376 days ago
bool detectLoop(Node* head) { //False = No Cycle and True= Cycle if(head==NULL) return false; Node* tor=head; Node* rab=head->next; if(rab==NULL) return false; while(rab!=NULL) { if(tor==rab) return true; tor=tor->next; rab=rab->next; if(rab!=NULL) rab=rab->next; else break; } return false; }
-1
sureshbscsses211 week ago
java solution
public class Solution {public boolean hasCycle(ListNode head) {ListNode s=head;if(s==null){return false;}ListNode f=head.next;while(s!=null){if(s==null || f==null){return false;}if(s==f){return true;}s=s.next;if(s==null || f.next==null){return false;}f=f.next.next;}return false;}}
0
akaashhardha1 week ago
bool detectLoop(Node* head) { Node *fast = head; Node *slow = head; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; if(slow == fast) return true; } return false; }
0
harshscode2 weeks ago
if(!head) return false; Node *slow=head; Node *fast=head; while(fast and fast->next) { slow=slow->next; fast=fast->next->next; if(slow==fast) return true; } return false;
-1
kumharashvin2042 weeks ago
{ public: //Function to check if the linked list has a loop. bool detectLoop(Node* head) { Node* slow = head; Node* fast = head; while(fast && fast->next){ slow = slow->next; fast=fast->next->next; if(slow==fast){ return true; } } return false; }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 357,
"s": 238,
"text": "Given a linked list of N nodes. The task is to check if the linked list has a loop. Linked list can contain self loop."
},
{
"code": null,
"e": 368,
"s": 357,
"text": "Example 1:"
},
{
"code": null,
"e": 624,
"s": 368,
... |
Commonly Asked C Programming Interview Questions | 28 Jun, 2021
What is the difference between declaration and definition of a variable/functionAns: Declaration of a variable/function simply declares that the variable/function exists somewhere in the program but the memory is not allocated for them. But the declaration of a variable/function serves an important role. And that is the type of the variable/function. Therefore, when a variable is declared, the program knows the data type of that variable. In case of function declaration, the program knows what are the arguments to that functions, their data types, the order of arguments and the return type of the function. So that’s all about declaration. Coming to the definition, when we define a variable/function, apart from the role of declaration, it also allocates memory for that variable/function. Therefore, we can think of definition as a super set of declaration. (or declaration as a subset of definition).
// This is only declaration. y is not allocated memory by this statementextern int y;
// This is both declaration and definition, memory to x is allocated by this statement.int x;
What are different storage class specifiers in C?Ans: auto, register, static, extern
What is scope of a variable? How are variables scoped in C?Ans: Scope of a variable is the part of the program where the variable may directly be accessible. In C, all identifiers are lexically (or statically) scoped. See this for more details.
How will you print “Hello World” without semicolon?Ans:
#include <stdio.h>int main(void){ if (printf("Hello World")) { }}
See print “Geeks for Geeks” without using a semicolon for answer.
When should we use pointers in a C program?1. To get address of a variable2. For achieving pass by reference in C: Pointers allow different functions to share and modify their local variables.3. To pass large structures so that complete copy of the structure can be avoided.4. To implement “linked” data structures like linked lists and binary trees.
What is NULL pointer?Ans: NULL is used to indicate that the pointer doesn’t point to a valid location. Ideally, we should initialize pointers as NULL if we don’t know their value at the time of declaration. Also, we should make a pointer NULL when memory pointed by it is deallocated in the middle of a program.
What is Dangling pointer?Ans: Dangling Pointer is a pointer that doesn’t point to a valid memory location. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. Following are examples.
// EXAMPLE 1int* ptr = (int*)malloc(sizeof(int));..........................free(ptr); // ptr is a dangling pointer now and operations like following are invalid*ptr = 10; // or printf("%d", *ptr);
// EXAMPLE 2int* ptr = NULL{ int x = 10; ptr = &x;}// x goes out of scope and memory allocated to x is free now.// So ptr is a dangling pointer now.
What is memory leak? Why it should be avoidedAns: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
/* Function with memory leak */#include <stdlib.h> void f(){ int* ptr = (int*)malloc(sizeof(int)); /* Do some work */ return; /* Return without freeing ptr*/}
What are local static variables? What is their use?Ans:A local static variable is a variable whose lifetime doesn’t end with a function call where it is declared. It extends for the lifetime of complete program. All calls to the function share the same copy of local static variables. Static variables can be used to count the number of times a function is called. Also, static variables get the default value as 0. For example, the following program prints “0 1”
#include <stdio.h>void fun(){ // static variables get the default value as 0. static int x; printf("%d ", x); x = x + 1;} int main(){ fun(); fun(); return 0;}// Output: 0 1
What are static functions? What is their use?Ans:In C, functions are global by default. The “static” keyword before a function name makes it static. Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files. See this for examples and more details.
Commonly Asked C Programming Interview Questions | Set 2
Practices Quizzes on C
C articles
You may also like:
Commonly Asked C Programming Interview Questions | Set 2Commonly Asked Java Programming Interview Questions | Set 1Amazon’s most asked interview questionsMicrosoft’s most asked interview questionsAccenture’s most asked Interview QuestionsCommonly Asked OOP Interview QuestionsCommonly Asked C++ Interview QuestionsCommonly asked DBMS interview questions | Set 1Commonly asked DBMS interview questions | Set 2Commonly Asked Operating Systems Interview Questions | Set 1Commonly Asked Data Structure Interview Questions.Commonly Asked Algorithm Interview QuestionsCommonly asked Computer Networks Interview QuestionsTop 10 algorithms in Interview Questions
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
moosavi001
balajiwanole
interview-preparation
placement preparation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Different methods to reverse a string in C/C++
Command line arguments in C/C++
fork() in C
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Substring in C++ | [
{
"code": null,
"e": 24470,
"s": 24442,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25381,
"s": 24470,
"text": "What is the difference between declaration and definition of a variable/functionAns: Declaration of a variable/function simply declares that the variable/function ... |
Empty string in not-null column in MySQL? | In PHP, the empty string equals to a NULL value, but in MySQL, the case is the different i.e. empty string is not equal to NULL value. To understand the above syntax, let us create a column with NOT NULL constraint while you can insert an empty string.
Let us create a table. The query to create a table is as follows −
mysql> create table EmptyStringNotNullDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(10) not null,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.83 sec)
Now you can insert some records in the table to check the empty string is null or not null. The query to insert record is as follows −
mysql> insert into EmptyStringNotNullDemo(Name) values('John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into EmptyStringNotNullDemo(Name) values('');
Query OK, 1 row affected (0.43 sec)
mysql> insert into EmptyStringNotNullDemo(Name) values('Carol');
Query OK, 1 row affected (0.12 sec)
mysql> insert into EmptyStringNotNullDemo(Name) values('');
Query OK, 1 row affected (0.13 sec)
mysql> insert into EmptyStringNotNullDemo(Name) values('');
Query OK, 1 row affected (0.16 sec)
mysql> insert into EmptyStringNotNullDemo(Name) values('Larry');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from EmptyStringNotNullDemo;
The following is the output −
+----+-------+
| Id | Name |
+----+-------+
| 1 | John |
| 2 | |
| 3 | Carol |
| 4 | |
| 5 | |
| 6 | Larry |
+----+-------+
6 rows in set (0.00 sec)
Now check the empty string is NULL or NOT NULL in MySQL. If you get a 0 that would mean the empty string is not equal to a NULL otherwise empty string is NULL. The query is as follows −
mysql> select Name, Name IS NULL as EmptyValueIsNotNULL from EmptyStringNotNullDemo;
The following is the output −
+-------+---------------------+
| Name | EmptyValueIsNotNULL |
+-------+---------------------+
| John | 0 |
| | 0 |
| Carol | 0 |
| | 0 |
| | 0 |
| Larry | 0 |
+-------+---------------------+
6 rows in set (0.00 sec)
You can achieve with the help of user-defined variable. The syntax is as follows −
SET @anyVariableName=” ”;
UPDATE yourTableName SET yourColumnName= @anyVariableName;
Implement the above syntax for the given table. The query is as follows to declare and define a user variable.
mysql> set @emptyStringValue="";
Query OK, 0 rows affected (0.00 sec)
Update the table with an empty string. The query is as follows −
mysql> update EmptyStringNotNullDemo set Name=@emptyStringValue;
Query OK, 3 rows affected (0.25 sec)
Rows matched: 6 Changed: 3 Warnings: 0
Display all records from the table once again. The query is as follows −
mysql> select *from EmptyStringNotNullDemo;
The following is the output −
+----+------+
| Id | Name |
+----+------+
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
+----+------+
6 rows in set (0.00 sec)
The column ‘Name’ has been updated. | [
{
"code": null,
"e": 1315,
"s": 1062,
"text": "In PHP, the empty string equals to a NULL value, but in MySQL, the case is the different i.e. empty string is not equal to NULL value. To understand the above syntax, let us create a column with NOT NULL constraint while you can insert an empty string."... |
Spring Boot PostgreSQL DB CRUD Example - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see the Spring Boot PostgreSQL DB CRUD example application.
Spring Boot 2.5.0
Java 14
PostgreSQL 13.3
Spring Boot 2.5.0
Java 14
PostgreSQL 13.3
Spring JPA 2.5.2
This tutorial, assuming that you have installed and configure PostgreSQL on your machine.
Here is the final application structure, as part of this example we are going to go complete CRUD operations with PostgreSQL.
Add the PostgreSQL dependency in the pom.xmlfile.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Complete pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>Spring-Boot-PostgresSQL-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Boot-PostgresSQL-Example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>14</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
In the above pom.xmlfile you may be noticed that I have included the spring-boot-data-jpadependency, the intention of this is to avoid the bare hibernate/jdbc and take advantage of Spring Data JPA
Connect to your local PostgreSQL DB and run the below commands to create a new DB.
% psql postgres -U otp # connecting postgres
psql (13.3)
Type "help" for help.
postgres=> create database products; # creating products db
CREATE DATABASE
postgres=>\connect products # switch to products db
You are now connected to database "products" as user "otp".
products->
Now we are ready with products database, now let’s configure this DB in the application.
We can configure the DB properties within the application either with .properties file or .yamlnow I am going with the application.properties file, here it is.
spring.datasource.url=jdbc:postgresql://localhost:5432/products
spring.datasource.username=otp
spring.datasource.password=123456
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
Create a database model class
package com.onlinetutorialspoint.model;
import javax.persistence.*;
@Entity
@Table(name = "items")
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name="item_name")
private String itemName;
@Column(name="item_category")
private String category;
public Item() {
}
public Item(String itemName, String category) {
this.itemName = itemName;
this.category = category;
}
public long getId() {
return id;
}
public String getItemName() {
return itemName;
}
public String getCategory() {
return category;
}
}
The above Item class is an ORM representation of item table in the database.
Crate rest controller that provides all CRUD operations for itemtable
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.repos.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
public class ItemController {
@Autowired
ItemRepository itemRepo;
@RequestMapping("/items")
@ResponseBody
public ResponseEntity<List<Item>> getAllItems(){
List<Item> items = itemRepo.findAll();
return new ResponseEntity<List<Item>>(items, HttpStatus.OK);
}
@GetMapping("/item/{itemId}")
@ResponseBody
public ResponseEntity<Item> getItem(@PathVariable Long itemId){
Optional<Item> item = itemRepo.findById(itemId);
return new ResponseEntity<Item>(item.get(), HttpStatus.OK);
}
@PostMapping(value = "/add",consumes = {"application/json"},produces = {"application/json"})
@ResponseBody
public ResponseEntity<Item> addItem(@RequestBody Item item, UriComponentsBuilder builder){
itemRepo.save(item);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/addItem/{id}").buildAndExpand(item.getId()).toUri());
return new ResponseEntity<Item>(headers, HttpStatus.CREATED);
}
@PutMapping("/update")
@ResponseBody
public ResponseEntity<Item> updateItem(@RequestBody Item item){
if(item != null){
itemRepo.save(item);
}
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@DeleteMapping("/delete/{id}")
@ResponseBody
public ResponseEntity<Void> deleteItem(@PathVariable Long id){
Optional<Item> item = itemRepo.findById(id);
itemRepo.delete(item.get());
return new ResponseEntity<Void>(HttpStatus.ACCEPTED);
}
}
The ItemRepository is a JPA repository, which provides all necessary CRUD methods, to make this happen we need to extend the repository class from JpaRepository class
package com.onlinetutorialspoint.repos;
import com.onlinetutorialspoint.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ItemRepository extends JpaRepository<Item, Long> {
}
This class act as the main class of the Spring Boot.
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootPostgresSqlExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootPostgresSqlExampleApplication.class, args);
}
}
Done!
Run the application:
Spring-Boot-PostgresSQL-Example % mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------< com.onlinetutorialspoint:Spring-Boot-PostgresSQL-Example >------
[INFO] Building Spring-Boot-PostgresSQL-Example 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ Spring-Boot-PostgresSQL-Example ---
[INFO] Deleting /Users/chandra/Work/MyWork/Spring-Boot-PostgresSQL-Example/target
[INFO] ....
.....
Run
Spring-Boot-PostgresSQL-Example % mvn spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------< com.onlinetutorialspoint:Spring-Boot-PostgresSQL-Example >------
[INFO] Building Spring-Boot-PostgresSQL-Example 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.5.0:run (default-cli) > test-compile @ Spring-Boot-PostgresSQL-Example >>>
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ Spring-Boot-PostgresSQL-Example ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
...
...
2021-07-21 19:32:31.928 INFO 56034 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-07-21 19:32:31.936 INFO 56034 --- [ main] .SpringBootPostgresSqlExampleApplication : Started SpringBootPostgresSqlExampleApplication in 3.16 seconds (JVM running for 3.47)
2021-07-21 19:32:31.937 INFO 56034 --- [ main] o.s.b.a.ApplicationAvailabilityBean : Application availability state LivenessState changed to CORRECT
2021-07-21 19:32:31.938 INFO 56034 --- [ main] o.s.b.a.ApplicationAvailabilityBean : Application availability state ReadinessState changed to ACCEPTING_TRAFFIC
You can see the spring boot application port in the server logs above, try to add some items into the PostgreSQL database now.
Adding Items:
Adding Item 2:
List All items:
Updating Item id 2
After Update:
Deleting Item 2:
After deleting item 2:
Final PostgreSQL DB:
postgres=> \connect products
You are now connected to database "products" as user "otp".
products=> select * from items;
id | item_category | item_name
----+---------------+------------------
1 | Books | Spring in Action
(1 row)
Done!
Install PostgreSQL on Mac
Hibernate Dialects
PostgreSQL
Happy Learning 🙂
Spring Boot JdbcTemplate CRUD Operations Mysql
How to set Spring Boot SetTimeZone
Spring Boot Redis Data Example CRUD Operations
Spring boot exception handling rest service (CRUD) operations
Spring Boot How to change the Tomcat to Jetty Server
How to use Spring Boot Random Port
How to change Spring Boot Tomcat Port Number
Spring Boot H2 Database + JDBC Template Example
Spring Boot MockMvc JUnit Test Example
How To Change Spring Boot Context Path
Spring Boot MongoDB + Spring Data Example
Simple Spring Boot Example
Spring Boot Lazy Loading Beans Example
Spring Boot Kafka Producer Example
Spring Boot In Memory Basic Authentication Security
Spring Boot JdbcTemplate CRUD Operations Mysql
How to set Spring Boot SetTimeZone
Spring Boot Redis Data Example CRUD Operations
Spring boot exception handling rest service (CRUD) operations
Spring Boot How to change the Tomcat to Jetty Server
How to use Spring Boot Random Port
How to change Spring Boot Tomcat Port Number
Spring Boot H2 Database + JDBC Template Example
Spring Boot MockMvc JUnit Test Example
How To Change Spring Boot Context Path
Spring Boot MongoDB + Spring Data Example
Simple Spring Boot Example
Spring Boot Lazy Loading Beans Example
Spring Boot Kafka Producer Example
Spring Boot In Memory Basic Authentication Security
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
... |
Swift - Optionals | Swift 4 also introduces Optionals type, which handles the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn't a value at all".
An Optional is a type on its own, actually one of Swift 4’s new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift 4.
Here’s an optional Integer declaration −
var perhapsInt: Int?
Here’s an optional String declaration −
var perhapsStr: String?
The above declaration is equivalent to explicitly initializing it to nil which means no value −
var perhapsStr: String? = nil
Let's take the following example to understand how optionals work in Swift 4 −
var myString:String? = nil
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
When we run the above program using playground, we get the following result −
myString has nil value
Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.
If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable.
Let's take a simple example −
var myString:String?
myString = "Hello, Swift 4!"
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
When we run the above program using playground, we get the following result −
Optional("Hello, Swift 4!")
Now let's apply unwrapping to get the correct value of the variable −
var myString:String?
myString = "Hello, Swift 4!"
if myString != nil {
print( myString! )
} else {
print("myString has nil value")
}
When we run the above program using playground, we get the following result.
Hello, Swift 4!
You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value. Let's take a simple example −
var myString:String!
myString = "Hello, Swift 4!"
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
When we run the above program using playground, we get the following result −
Hello, Swift 4!
Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.
An optional binding for the if statement is as follows −
if let constantName = someOptional {
statements
}
Let's take a simple example to understand the usage of optional binding −
var myString:String?
myString = "Hello, Swift 4!"
if let yourString = myString {
print("Your string has - \(yourString)")
} else {
print("Your string does not have a value")
}
When we run the above program using playground, we get the following result −
Your string has - Hello, Swift 4!
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2421,
"s": 2253,
"text": "Swift 4 also introduces Optionals type, which handles the absence of a value. Optionals say either \"there is a value, and it equals x\" or \"there isn't a value at all\"."
},
{
"code": null,
"e": 2630,
"s": 2421,
"text": "An Optiona... |
C# Program to generate random lowercase letter | Firstly, set Random class −
Random random = new Random();
Set a range under the Next() method. This displays a letter between 0 and 26.
int a = random.Next(0, 26);
Here is the complete code −
Live Demo
using System;
using System.IO;
using System.Linq;
class Demo {
static void Main() {
Random random = new Random();
// random lowercase letter
int a = random.Next(0, 26);
char ch = (char)('a' + a);
Console.WriteLine(ch);
}
}
t | [
{
"code": null,
"e": 1090,
"s": 1062,
"text": "Firstly, set Random class −"
},
{
"code": null,
"e": 1120,
"s": 1090,
"text": "Random random = new Random();"
},
{
"code": null,
"e": 1198,
"s": 1120,
"text": "Set a range under the Next() method. This displays a ... |
Introduction to Solving Basic Bayesian Networks with OpenBUGS in R | by Tri Nguyen | Towards Data Science | A Bayesian network is a probabilistic graphical model that represents a set of variables and their conditional dependencies via an oriented acyclic graph. “Oriented” means that the arrows connecting the nodes of the graph are oriented (i.e. has directions) so the conditional dependencies have a one-way direction. “Acylic” means that it is impossible to loop through the network. It can only go up or down.
Let’s start with an example:
Manchester United is competing in the English Premier League. They have been struggling to keep up with their image of one of the world’s biggest club in recent years after the retirement of Sir Alex Ferguson, the most successful manager in the club’s history. Last year, they only finished 6th in the league. As such, at the beginning of the 2019/20 season, the fans believe that the club will finish in Top 3 of the league with only a probability of 0.2, in 4th place with the probability of 0.3, and outside of Top 4 with the probability of 0.5.
These probabilities hold true only if the club’s key player is Marcus Rashford is not severely injured throughout the season. The probability of a severe injury happening to him is 0.2. If that happens, the probabilities for the above end of season positions are 0.1, 0.2, and 0.7 respectively.
If they finish in Top 3, they will be qualified for next year’s Champions League Group Stage. If they finish 4th, they will have to go through Champions League Qualification Round so the probability of them proceeding to the Champions League Group Stage is reduced to 0.7.
Manchester United is also competing in the Europa League, second-tier to the Champions League in Europe. As a former winner, they have a 0.6 probability of winning the Europa League again if Rashford is fit. If Rashford is injured, the probability is reduced to 0.4. If they win the Europa League, they are guaranteed to have a place in next year’s Champions League Group Stage with 0.99 probability even if they don’t get into Top 3 unless UEFA changes the rules for next year.
If the club is qualified for next year’s Champions League Group Stage, they will have a 0.7 chance to sign one of their top transfer targets, Bruno Fernandes from Sporting Lisbon. If not, the chance to sign Fernandes is reduced to 0.4.
At the beginning of the 2020/2021 season, Bruno Fernandes is a Manchester United player.
- What is the probability that Rashford is injured?
- What is the probability that the club was qualified for Champions League?
- What is the probability that the club finished in Top 3?
- What is the probability that the club finished 4th?
- What is the probability that the club won the Europa League?
Some questions of this style are straight forward to solve analytically using Bayes’ theorem formula when the number of variables and dependencies involved is small. However, for problems like the above example, it will be much easier to use software applications for the Bayesian analysis to find the probabilities in question.
Here, we will use the library “R2OpenBUGS” in R to solve for those probabilities. The library is based on the OpenBUGS software, which is for the Bayesian analysis of complex statistical models using Markov chain Monte Carlo (MCMC) methods. The “BUGS” stands for (Bayesian inference Using Gibbs Sampling). As such, the installation of OpenBUGS is required for the library to run. The installation instruction can be found here.
First, we import the library “R2OpenBUGS” and define the path where the OpenBUGS program is installed.
Then, we will define our model and
Here, MR denotes the state of Marcus Rashford and when MR is around 2, Rashford is injured and we assign that event to MRinjured. Note that in this case, when MR is returned around 1, Rashford is fit. The order of these events could be switched up depending on how we assign the probabilities later. We can almost map those events like (MRfit, MRinjured) -> (1, 2) in this case.
Similarly, other variables are defined. Note that, since how well Manchester United do in the English Premier League (EPL) depends on the state of Marcus Rashford, “MR” variable is included when we define the EPL variable. Other dependencies follow similar fashion.
Next, we assign the data (i.e. the probabilities, hard evidence) that we have.
We see that BF is set to 1. That is because we know from the problem that Bruno Fernandes signs with United at the end of the season. Hence, that is hard evidence and we assign the BF variable to 1.
The rest of the data are given probabilities. Probabilities with dependencies have the form of matrices. Please note that the way matrices are defined here is different from the native matrix configuration on OpenBUGS itself. More info about how to define matrix on OpenBUGS software can be found here.
Next, we need to follow a default, compulsory step called Initialization. However, that is more applicable to problems involving continuous random distributions and we do not need to initialize any value here. However, the package will return an error if we do not assign the initialization step something, so we assign it to NULL.
Now, we can run the model to calculate the probabilities in question given the hard evidence.
“debug” is default to False. However, it is recommended to switch it to True as it is easier to see the errors in case the model does not run. We can now run the codes to get the model running. Here, we are going to run and iterate the model 100,000 times and then discard the first 1,000 results to ensure any large initial variations are not included.
When the model is run, OpenBUGS will open and display a window similar to the above.
It contains all the answers we are looking for but if we want everything to be in R, we will need to close the application so the R codes could finish running. Then we use the following code to display the results in R.
Given the news that Bruno Fernandes signed with United, the probability that Manchester United got qualified for next year’s Champions League is 81%. The probability that they won the Europa League also gets higher to 62.5%. The probabilities that they got Top 3 or 4th place in the Premier League are also marginally higher at 20.8% and 30.3%.
Noticeably, the probability that Marcus Rashford is injured is lowered to 17.6% because he plays an important role in the team’s performance and directly affects the event that the team is qualified for UCL, which directly affects whether Fernandes decides to sign with United or not.
library(R2OpenBUGS)OpenBUGS.pgm = "c:/Program Files (x86)/OpenBUGS/OpenBUGS323/OpenBUGS.exe"#Setting up the modelmodel <- function() { MR ~ dcat(p.MR[]); MRinjured <- equals(MR, 2); EPL ~ dcat(p.EPL[MR,]); EPLTop3 <- equals(EPL,1); EPL4th <- equals(EPL,2); EPLElse <- equals(EPL,3); Europa ~ dcat(p.Europa[MR,]); WonEL <- equals(Europa,1); UCL ~ dcat(p.UCL[EPL,Europa,]); InUCL <- equals(UCL,1); BF ~ dcat(p.BF[UCL,])}#Hard evidence: 1 is TRUE and 2 is FALSEdata <- list( BF = 1,p.MR = c(0.8,0.2),p.Europa = structure(.Data = c(0.6,0.3, 0.4,0.7), .Dim = c(2,2)),p.EPL = structure(.Data = c(0.2, 0.1, 0.3, 0.2, 0.5, 0.7), .Dim = c(2,3)),p.UCL = structure(.Data = c(1, 0.99, 0.99, 1, 0.7, 0, 0, 0.01, 0.01, 0, 0.3, 1), .Dim = c(3,2,2)),p.BF = structure(.Data = c( 0.7, 0.4, 0.3, 0.6), .Dim = c(2,2)) )#Initializationinits <- NULL#Run BUGS and save resultsout <- bugs(data = data, inits = inits, parameters.to.save = c("MRinjured", "EPLTop3", "EPL4th", "EPLElse", "WonEL", "InUCL"), model.file = model, digits = 5, n.chains = 1, n.burnin = 1000, n.iter = 100000, OpenBUGS.pgm=OpenBUGS.pgm, WINE = WINE, WINEPATH = WINEPATH, useWINE=F, debug = T, working.directory=getwd(), DIC = F )print(out$summary) | [
{
"code": null,
"e": 579,
"s": 171,
"text": "A Bayesian network is a probabilistic graphical model that represents a set of variables and their conditional dependencies via an oriented acyclic graph. “Oriented” means that the arrows connecting the nodes of the graph are oriented (i.e. has directions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.