title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
SAP ABAP - Creating Internal Tables | DATA statement is used to declare an internal table. The program must be told where the table begins and ends. So use the BEGIN OF statement and then declare the table name. After this, the OCCURS addition is used, followed by a number, here 0. OCCURS tells SAP that an internal table is being created, and the 0 states that it will not contain any records initially. It will then expand as it is filled with data.
Following is the syntax −
DATA: BEGIN OF <internal_tab> Occurs 0,
Let’s create the fields on a new line. For instance, create ‘name’ which is declared as LIKE ZCUSTOMERS1-name. Create another field called ‘dob’, LIKE ZCUSTOMERS1-dob. It is useful initially to give the field names in internal tables the same names as other fields that have been created elsewhere. Finally, declare the end of the internal table with “END OF <internal_tab>.” as shown in the following code −
DATA: BEGIN OF itab01 Occurs 0,
name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
Here ‘itab01’ is commonly used shorthand when creating temporary tables in SAP. The OCCURS clause is used to define the body of an internal table by declaring the fields for the table. When the OCCURS clause is used, you can specify a numeric constant ‘n’ to determine additional default memory if required. The default size of memory that is used by the OCCUR 0 clause is 8 KB. The structure of the internal table is now created, and the code can be written to fill it with records.
An internal table can be created with or without using a header line. To create an internal table with a header line, use either the BEGIN OF clause before the OCCURS clause or the WITH HEADER LINE clause after the OCCURS clause in the definition of the internal table. To create an internal table without a header line, use the OCCURS clause without the BEGIN OF clause.
You can also create an internal table as a local data type (a data type used only in the context of the current program) by using the TYPES statement. This statement uses the TYPE or LIKE clause to refer to an existing table.
The syntax to create an internal table as a local data type is −
TYPES <internal_tab> TYPE|LIKE <internal_tab_type> OF
<line_type_itab> WITH <key> INITIAL SIZE <size_number>.
Here the <internal_tab_type> specifies a table type for an internal table <internal_tab> and <line_type_itab> specifies the type for a line of an internal table. In TYPES statement, you can use the TYPE clause to specify the line type of an internal table as a data type and LIKE clause to specify the line type as a data object. Specifying a key for an internal table is optional and if the user does not specify a key, the SAP system defines a table type with an arbitrary key.
INITIAL SIZE <size_number> creates an internal table object by allocating an initial amount of memory to it. In the preceding syntax, the INITIAL SIZE clause reserves a memory space for size_number table lines. Whenever an internal table object is declared, the size of the table does not belong to the data type of the table.
Note − Much less memory is consumed when an internal table is populated for the first time.
Step 1 − Open the ABAP Editor by executing the SE38 transaction code. The initial screen of ABAP Editor appears.
Step 2 − In the initial screen, enter a name for the program, select the Source code radio button and click the Create button to create a new program.
Step 3 − In the 'ABAP: Program Attributes' dialog box, enter a short description for the program in the Title field, select the 'Executable program' option from the Type drop-down menu in the Attributes group box. Click the Save button.
Step 4 − Write the following code in ABAP editor.
REPORT ZINTERNAL_DEMO.
TYPES: BEGIN OF CustomerLine,
Cust_ID TYPE C,
Cust_Name(20) TYPE C,
END OF CustomerLine.
TYPES mytable TYPE SORTED TABLE OF CustomerLine
WITH UNIQUE KEY Cust_ID.
WRITE:/'The mytable is an Internal Table'.
Step 5 − Save, activate and execute the program as usual.
In this example, mytable is an internal table and a unique key is defined on the Cust_ID field.
The above code produces the following output −
The mytable is an Internal Table.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3313,
"s": 2898,
"text": "DATA statement is used to declare an internal table. The program must be told where the table begins and ends. So use the BEGIN OF statement and then declare the table name. After this, the OCCURS addition is used, followed by a number, here 0. OCCURS t... |
XSD - Syntax | An XML XSD is kept in a separate document and then the document can be linked to an XML document to use it.
The basic syntax of a XSD is as follows −
<?xml version = "1.0"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
targetNamespace = "http://www.tutorialspoint.com"
xmlns = "http://www.tutorialspoint.com" elementFormDefault = "qualified">
<xs:element name = 'class'>
<xs:complexType>
<xs:sequence>
<xs:element name = 'student' type = 'StudentType' minOccurs = '0'
maxOccurs = 'unbounded' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "StudentType">
<xs:sequence>
<xs:element name = "firstname" type = "xs:string"/>
<xs:element name = "lastname" type = "xs:string"/>
<xs:element name = "nickname" type = "xs:string"/>
<xs:element name = "marks" type = "xs:positiveInteger"/>
</xs:sequence>
<xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
</xs:complexType>
</xs:schema>
Schema is the root element of XSD and it is always required.
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
The above fragment specifies that elements and datatypes used in the schema are defined in http://www.w3.org/2001/XMLSchema namespace and these elements/data types should be prefixed with xs. It is always required.
targetNamespace = "http://www.tutorialspoint.com"
The above fragment specifies that elements used in this schema are defined in http://www.tutorialspoint.com namespace. It is optional.
xmlns = "http://www.tutorialspoint.com"
The above fragment specifies that default namespace is http://www.tutorialspoint.com.
elementFormDefault = "qualified"
The above fragment indicates that any elements declared in this schema must be namespace qualified before using them in any XML Document.It is optional.
Take a look at the following Referencing Schema −
<?xml version = "1.0"?>
<class xmlns = "http://www.tutorialspoint.com"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.tutorialspoint.com student.xsd">
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
xmlns = "http://www.tutorialspoint.com"
The above fragment specifies default namespace declaration. This namespace is used by the schema validator check that all the elements are part of this namespace. It is optional.
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.tutorialspoint.com student.xsd">
After defining the XMLSchema-instance xsi, use schemaLocation attribute. This attribute has two values, namespace and location of XML Schema, to be used separated by a space. It is optional.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1812,
"s": 1704,
"text": "An XML XSD is kept in a separate document and then the document can be linked to an XML document to use it."
},
{
"code": null,
"e": 1854,
"s": 1812,
"text": "The basic syntax of a XSD is as follows −"
},
{
"code": null,
... |
Why we use jQuery in our web application ? | 12 Aug, 2021
jQuery is a fast, feature-rich, and lightweight JavaScript library. The main purpose of using jQuery is is to make it much easier to use JavaScript on your modern and smart website. It is highly recommended to have a basic knowledge of HTML, CSS, and JavaScript.
jQuery was developed to save the time of developers by reducing the code. It takes loads of common duties that require many lines of JavaScript code to perform and wrap them into strategies that you may name with a single line of code.
Reasons to use jQuery in your application:
Easy to understand: It has simpler code than JavaScript. So you just have to write few lines of code to do the same thing. In addition, builders ought not to be professionals in programming or web layout to create incredible patterns for their sites. Any developer who has spent hours coding and trying out CSS documents will recognize the easy implementation that jQuery brings to the table. There’s additionally a set of strong jQuery UI additives that builders can plug into their websites.You might be able to understand by referring to the below example.JavaScript Code Snippet: function changeColor(color) {
document.body.style.background = color;
}
Onload = changeColor('green');jQuery Syntax:$('body').css('background', 'green');From the above example, you can notice that the JavaScript code is lengthier and complicated than the jQuery code. Both the code are performing the same work of changing the background color but jQuery takes less code. You can work around other examples, which indicates that jQuery minimizes the code and is less complicated to use.
You might be able to understand by referring to the below example.
JavaScript Code Snippet:
function changeColor(color) {
document.body.style.background = color;
}
Onload = changeColor('green');
jQuery Syntax:
$('body').css('background', 'green');
From the above example, you can notice that the JavaScript code is lengthier and complicated than the jQuery code. Both the code are performing the same work of changing the background color but jQuery takes less code. You can work around other examples, which indicates that jQuery minimizes the code and is less complicated to use.
Easily Integrated with other IDE: Most .Net developers use Visual Studio and are acquainted with NuGet. This is a part of the purpose why jQuery’s recognition keeps developing with .Net developers. With the addition of the jQuery cell difficulty for Windows, you currently have all the development benefits of the jQuery library for the Windows Phone platform.
Animation becomes easy: jQuery makes use of CSS, HTML, JavaScript, and AJAX. In this method, you could practice an optimization approach on your website online while not having to make unique changes for technologies like Flash. You can attain great-searching outcomes as a way to maintain your audience engaged.
Faster: Many search engines are considering page load time as one of the main factors because it affects SEO. For this reason, every developer in today’s world wants to make codes as concise as possible. The best way to make your website faster is by writing less code and it is possible by using the simplest JavaScript library called jQuery.
SEO friendly: SEO stand for search engine optimization and it is the process of improving the quality and quantity of website traffic to a website or a web page from search engines. So many popular search engines like google, bing and yahoo use SEO. jQuery may be optimized for search engines, and there are a lot of plug-ins for developers.
Run in all major browsers: The team behind the jQuery library knows what are the main issues that normally occurs in all major browsers. So they have developed this library to ease the developer’s work.
jQuery-Basics
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the value in an input text box using jQuery ?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
jQuery | parent() & parents() with Examples
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "jQuery is a fast, feature-rich, and lightweight JavaScript library. The main purpose of using jQuery is is to make it much easier to use JavaScript on your modern and smart we... |
Last digit in a power of 2 | 27 Apr, 2021
Given a number n, we need to find the last digit of 2n
Input : n = 4 Output : 6 The last digit in 2^4 = 16 is 6Input : n = 11 Output : 8 The last digit in 2^11 = 2048 is 8
A Naive Solution is to first compute power = pow(2, n), then find the last digit in power using power % 10. This solution is inefficient and also has an integer arithmetic issue for slightly large n.An Efficient Solution is based on the fact that the last digits repeat in cycles of 4 if we leave 2^0 which is 1. Powers of 2 (starting from 2^1) are 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, ... We can notice that the last digits are 2, 4, 8, 6, 2, 4, 8, 6, 2, 4, 8, ...1) We compute rem = n % 4. Note that the last rem will have a value from 0 to 3. 2) We return the last digit according to the value of the remainder.
Remainder Last Digit
1 2
2 4
3 8
0 6
Illustration : Let n = 11, rem = n % 4 = 3. Last digit in 2^3 is 8 which is same as last digit of 2^11.
C++
Java
Python3
C#
Javascript
// C++ program to find last digit in a power of 2.#include <bits/stdc++.h>using namespace std; int lastDigit2PowerN(int n){ // Corner case if (n == 0) return 1; // Find the shift in current cycle // and return value accordingly else if (n % 4 == 1) return 2; else if (n % 4 == 2) return 4; else if (n % 4 == 3) return 8; else return 6; // When n % 4 == 0} // Driver codeint main(){ for (int n = 0; n < 20; n++) cout << lastDigit2PowerN(n) << " "; return 0;}
// Java program to find last// digit in a power of 2.import java.io.*;import java.util.*; class GFG{ static int lastDigit2PowerN(int n){ // Corner case if (n == 0) return 1; // Find the shift in current cycle // and return value accordingly else if (n % 4 == 1) return 2; else if (n % 4 == 2) return 4; else if (n % 4 == 3) return 8; else return 6; // When n % 4 == 0} // Driver codepublic static void main(String[] args){ for (int n = 0; n < 20; n++) System.out.print(lastDigit2PowerN(n) + " ");}} // This code is contributed by coder001
# Python3 program to find last# digit in a power of 2.def lastDigit2PowerN(n): # Corner case if n == 0: return 1 # Find the shift in current cycle # and return value accordingly elif n % 4 == 1: return 2 elif n % 4 == 2: return 4 elif n % 4 == 3: return 8 else: return 6 # When n % 4 == 0 # Driver codefor n in range(20): print(lastDigit2PowerN(n), end = " ") # This code is contributed by divyeshrabadiya07
// C# program to find last// digit in a power of 2.using System;class GFG{ static int lastDigit2PowerN(int n){ // Corner case if (n == 0) return 1; // Find the shift in current cycle // and return value accordingly else if (n % 4 == 1) return 2; else if (n % 4 == 2) return 4; else if (n % 4 == 3) return 8; else return 6; // When n % 4 == 0} // Driver codepublic static void Main(string[] args){ for (int n = 0; n < 20; n++) { Console.Write(lastDigit2PowerN(n) + " "); }}} // This code is contributed by rutvik_56
<script> // JavaScript program to find // last digit in a power of 2. function lastDigit2PowerN(n) { // Corner case if (n == 0) return 1; // Find the shift in current cycle // and return value accordingly else if (n % 4 == 1) return 2; else if (n % 4 == 2) return 4; else if (n % 4 == 3) return 8; else return 6; // When n % 4 == 0 } // Driver code for (var n = 0; n < 20; n++) document.write(lastDigit2PowerN(n) + " "); </script>
1 2 4 8 6 2 4 8 6 2 4 8 6 2 4 8 6 2 4 8
Time Complexity: O(1) Auxiliary Space: O(1)Can we generalize it for any input numbers? Please refer Find Last Digit of a^b for Large Numbers
coder001
divyeshrabadiya07
rutvik_56
rdtank
maths-power
number-theory
Mathematical
School Programming
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 84,
"s": 28,
"text": "Given a number n, we need to find the last digit of 2n "
},
{
"code": null,
"e": 203,
"s": 84,
"text": "Input : n = 4 Output : 6 The last digit in 2^4 = 16 ... |
Introduction to Sanic Web Framework – Python | 10 May, 2022
WHAT IS SANIC? Sanic is an asynchronous web framework and web server for Python 3.5+ that’s written to go fast. Sanic was developed at MagicStack and is based on their uvloop event loop, which is a replacement for Python asyncio’s default event loop, thereby making Sanic blazing fast. Syntactically Sanic resembles Flask. Sanic maybe used as a replacement for Django or Flask to build highly scalable, efficient and blazing fast performant web applications. BUILDING OUR FIRST SANIC APP! Step 1: It is preferable to use virtual environments in Python to create isolated environments with project-specific dependencies. Since Sanic 19.6+ versions do not support Python 3.5, we will work with Python 3.6+. To install sanic in our Python virtual environment we will execute the following command – pip3 install sanic Step 2: Let us create a directory named sanic_demo & within it a file named main.py with the following lines of code –
Python3
from sanic import Sanicfrom sanic import response app = Sanic("My First Sanic App") # webapp path defined used route decorator@app.route("/")def run(request): return response.text("Hello World !") # debug logs enabled with debug = Trueapp.run(host ="0.0.0.0", port = 8000, debug = True)
Step 3: We may either run main.py from an IDE, or run the file from Terminal by executing the following command – python3 main.py The Sanic web server is up on 8000 port of our ‘localhost’. Step 4: Navigating to http://0.0.0.0:8000/ from our web browser renders “Hello World!”. CONFIGURATION The config attribute of the Sanic app object is used to configure parameters. The app config object can be assigned key-value pairs as follows :
Python3
from sanic import Sanicfrom sanic import response app = Sanic("My First Sanic App") app.config["SECURITY_TOKEN"] = [{"ApiKeyAuth": []}]
The full list of configuration params is available at the official documentation page – Sanic Config ROUTING AND BLUEPRINTS Sanic supports the route decorator to map handler functions to HTTP requests. We can use an optional parameter called methods in the ‘route’ decorator to work with any of the HTTP methods in the list. Blueprints is a concept used for plugging sub-routes into the Sanic app from sub-modules of a large application. Blueprints must be registered into the Sanic app object. Using blueprints also avoids passing around the Sanic app object all over the application. Let us modify our original main.py file to demonstrate the usage of routes and blueprints –
Python3
# this is our 'main.py' filefrom sanic import Sanicfrom sanic import responsefrom sanic.log import loggerfrom controller import my_bp app = Sanic("My First Sanic App") # registering route defined by blueprintapp.blueprint(my_bp) # webapp path defined used 'route' decorator@app.route("/")def run(request): return response.text("Hello World !") @app.route("/post", methods =['POST'])def on_post(request): try: return response.json({"content": request.json}) except Exception as ex: import traceback logger.error(f"{traceback.format_exc()}") app.run(host ="0.0.0.0", port = 8000, debug = True)
Let us create a new file named controller.py to declare our blueprints –
Python3
# this is our 'controller.py' filefrom sanic import responsefrom sanic import Blueprint my_bp = Blueprint('my_blueprint') @my_bp.route('/my_bp')def my_bp_func(request): return response.text('My First Blueprint')
Let us run main.py and check the results when /my_bp endpoint is accessed – We have used a web client called ‘Insomnia‘ to demonstrate our POST request – RENDERING CONTENT Sanic routes can serve html files, json content, media files etc. To serve static content like images, pdf, static html files etc we need to use app.static() method which maps the path of a static file to an endpoint specified by a ‘route’. Let us modify our main.py file to demonstrate this –
Python3
# this is our 'main.py' filefrom sanic import Sanicfrom sanic import responsefrom sanic.log import loggerfrom controller import my_bp app = Sanic("My First Sanic App") # registering route defined by blueprintapp.blueprint(my_bp)# configuring endpoint to serve an image downloaded from the webapp.static('/floral_image.jpg', '/sanic_demo / ws_Beautiful_flowers_1920x1080.jpg') # webapp path defined used 'route' decorator@app.route("/")def run(request): return response.text("Hello World !") @app.route("/post", methods =['POST'])def on_post(request): try: return response.json({"content": request.json}) except Exception as ex: import traceback logger.error(f"{traceback.format_exc()}") app.run(host ="0.0.0.0", port = 8000, debug = True)
Running main.py and accessing http://0.0.0.0:8000/floral_image.jpg renders the image on the browser. Let us further modify main.py to access some html content – Let us create a sample index.html file –
html
<html><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Render HTML on Sanic</title></head> <body>Gotta go fast!</body></html>
Python3
# this is our 'main.py' filefrom sanic import Sanicfrom sanic import responsefrom sanic.log import loggerfrom controller import my_bp app = Sanic("My First Sanic App") app.blueprint(my_bp) # registering route defined by blueprint app.static('/floral_image.jpg', '/sanic_demo / ws_Beautiful_flowers_1920x1080.jpg') # webapp path defined used 'route' decorator@app.route("/")def run(request): return response.text("Hello World !") @app.route("/post", methods =['POST'])def on_post(request): try: return response.json({"content": request.json}) except Exception as ex: import traceback logger.error(f"{traceback.format_exc()}") @app.route("/display")def display(request): return response.file('/sanic_demo / index.html') app.run(host ="0.0.0.0", port = 8000, debug = True)
Running main.py and accessing http://0.0.0.0:8000/display renders the following on the browser – EXCEPTION HANDLING Exceptions can be explicitly raised within Sanic request handlers. The Exceptions take a message as the first argument and can also include a status code. The @app.exception decorator can be used to handle Sanic Exceptions. Let us demonstrate by tweaking our main.py file –
Python3
# this is our 'main.py' file from sanic import Sanicfrom sanic import responsefrom sanic.log import loggerfrom controller import my_bpfrom sanic.exceptions import ServerError, NotFound app = Sanic("My First Sanic App") app.blueprint(my_bp) # registering route defined by blueprint app.static('/floral_image.jpg', '/sanic_demo / ws_Beautiful_flowers_1920x1080.jpg') # raise Exception@app.route('/timeout')async def terminate(request): raise ServerError("Gateway Timeout error", status_code = 504) @app.exception(NotFound)async def ignore_5xx(request, exception): return response.text(f"Gateway is always up: {request.url}") # webapp path defined used 'route' decorator@app.route("/")def run(request): return response.text("Hello World !") @app.route("/post", methods =['POST'])def on_post(request): try: return response.json({"content": request.json}) except Exception as ex: import traceback logger.error(f"{traceback.format_exc()}") @app.route("/display")def display(request): return response.file('/sanic_demo / index.html') app.run(host ="0.0.0.0", port = 8000, debug = True)
Exception rendered on browser – NotFound (thrown when request handler not found for route) and ServerError(thrown due to serve code issues) are most commonly used. ASYNC SUPPORT Web applications characteristically talk to external resources, like databases, queues, external APIs etc to retrieve information required to process requests. Sanic, a Python Web Framework that has Python 3.5+’s asyncio library’s async/await syntax pre-baked into it, is the ideal candidate for designing large scale I/O bound projects which work with many connections. This enables the webapp’s requests to be processed in a non-blocking and concurrent way. Python 3.5 introduced asyncio, which is a library to write concurrent code using the async/await syntax (source: https://docs.python.org/3/library/asyncio.html). The asyncio library provides an event loop which runs async I/O functions. Sanic provides support for async/await syntax, thereby making request handling non-blocking and super fast. Adding the async keyword to request handler functions makes the function handle the code asynchronously, thereby leveraging Sanic’s performance benefits. Instead of asyncio’s event loop, Sanic uses MagicStack’s proprietary uvloop which is faster than asyncio’s event loop, leading to blazing fast speeds. However, on Windows OS, Sanic reverts to asyncio’s event loop under the hood, due to issues with uvloop on Windows. Reference: Sanic Official Docs.
sagartomar9927
Python Framework
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
Similarities and Difference between Java and C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 987,
"s": 52,
"text": "WHAT IS SANIC? Sanic is an asynchronous web framework and web server for Python 3.5+ that’s written to go fast. Sanic was developed at MagicStack and is based on their uvloop... |
Maximum product of a triplet (subsequence of size 3) in array in C++ Program. | In this problem, we are given an array arr[] consisting of n integers. Our task is to find the maximum product of a triplet (subsequence of size 3) in array. Here, we will be finding the triple with maximum product value and then return the product.
Let’s take an example to understand the problem,
arr[] = {9, 5, 2, 11, 7, 4}
693
Here, we will find the triplet that gives the maximum product of all elements of the array. maxProd = 9 * 11 * 7 = 693
There can be multiple solutions to the problem. We will be discussing them here,
Direct method In this method, we will directly loop through the array and then find all possible triplet. Find the product of elements of each triplet and return the maximum of all of them.
Initialise
maxProd = −1000
Step 1:
Create three nested loops:
Loop 1:i −> 0 to n−3
Loop 2: j −> i to n−2
Loop 3: k −> j to n−1
Step 1.1 −
Find the product, prod = arr[i]*arr[j]*arr[k].
Step 1.2 −
if prod > maxProd −> maxProd = prod.
Step 3 −
return maxProd.
Program to show the implementation of our solution,
Live Demo
#include <iostream>
using namespace std;
int calcMaxProd(int arr[], int n){
int maxProd = −1000;
int prod;
for (int i = 0; i < n − 2; i++)
for (int j = i + 1; j < n − 1; j++)
for (int k = j + 1; k < n; k++){
prod = arr[i] * arr[j] * arr[k];
if(maxProd < prod)
maxProd = prod;
}
return maxProd;
}
int main(){
int arr[] = { 9, 5, 2, 11, 7, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Maximum product of a triplet in array is "<<calcMaxProd(arr, n);
return 0;
}
Maximum product of a triplet in array is 693
Using Sorting
In this method, we will sort the array in descending order. In sorted array, the maximum product triplet will be at,
(arr[0], arr[1], arr[2])
(arr[0], arr[1], arr[2])
We will return the maximum of the product of these triplets.
Step 1 −
Sort the given array in descending order.
Step 2 −
Find product of triples,
maxTriplet1 = arr[0]*arr[1]*arr[2]
maxTriplet2 = arr[0]*arr[n−1]*arr[n−2]
Step 3 −
if( maxTriplet1 > maxTriplet2 ) −> return maxTriplet1
Step 4 −
else −> return maxTriplet2.
Program to illustrate the working of our solution,
Live Demo
#include <bits/stdc++.h>
using namespace std;
int calcMaxProd(int arr[], int n){
sort(arr, arr + n, greater<>());
int maxTriplet1 = arr[0]*arr[1]*arr[2];
int maxTriplet2 = arr[0]*arr[n−1]*arr[n−2];
if(maxTriplet1 > maxTriplet2)
return maxTriplet1;
return maxTriplet2;
}
int main(){
int arr[] = { 9, 5, 2, 11, 7, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Maximum product of a triplet in array is
"<<calcMaxProd(arr, n);
return 0;
}
Maximum product of a triplet in array is 693
Finding triplet values.
As we now know that the maximum product triplet can be from either of the two triplets,
(maximum, second_max, third_max)
(maximum, minimum, second_min)
So, we can directly find these values by traversing the array, and then using the values, we will find the maximum product triplet.
Initialise
max = -1000, secMax = -1000, thirdMax = -1000 , min = 10000, secMin = 10000
Step 1−
loop the array i −> 0 to n−1.
Step 1.1
if(arr[i] > max) −> thirdMax = secMax, secMax = max, max
= arr[i]
Step 1.2−
elseif(arr[i] > secMax) −> thirdMax = secMax, secMax =
arr[i]
Step 1.3−
elseif(arr[i] > thirdMax) −> thirdMax = arr[i]
Step 1.4−
if(arr[i] < min) −> secMin = min, min = arr[i]
Step 1.4−
elseif(arr[i] < secMin) −> secMin = arr[i]
Step 2−
triplet1 = max * secMax * thridMax
triplet2 = max * min * secMin
Step 3−
if(triplet1 > triplet2) −> return triplet1
Step 4−
else −> return triplet2
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
int calcMaxProd(int arr[], int n){
int max = −1000, secMax = −1000, thirdMax = −1000;
int min = 1000, secMin = 1000;
for (int i = 0; i < n; i++){
if (arr[i] > max){
thirdMax = secMax;
secMax = max;
max = arr[i];
}
else if (arr[i] > secMax){
thirdMax = secMax;
secMax = arr[i];
}
else if (arr[i] > thirdMax)
thirdMax = arr[i];
if (arr[i] < min){
secMin = min;
min = arr[i];
}
else if(arr[i] < secMin)
secMin = arr[i];
}
int triplet1 = max * secMax * thirdMax;
int triplet2 = max * secMin * min;
if(triplet1 > triplet2)
return triplet1;
return triplet2;
}
int main(){
int arr[] = { 9, 5, 2, 11, 7, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Maximum product of a triplet in array is
"<<calcMaxProd(arr, n);
return 0;
}
Maximum product of a triplet in array is 693 | [
{
"code": null,
"e": 1437,
"s": 1187,
"text": "In this problem, we are given an array arr[] consisting of n integers. Our task is to find the maximum product of a triplet (subsequence of size 3) in array. Here, we will be finding the triple with maximum product value and then return the product."
... |
Matplotlib.axes.Axes.autoscale() in Python | 19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.autoscale() function in axes module of matplotlib library is used to autoscale the axis view to the data (toggle).
Syntax: Axes.autoscale(self, enable=True, axis=’both’, tight=None)
Parameters: This method accepts the following parameters.
enable : If this parameter is True (default) turns autoscaling on, False turns it off.
axis: This parameter is used to which axis to be operate on. {‘both’, ‘x’, ‘y’}
tight: This parameter is forwarded to autoscale_view.
Return value: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.autoscale() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function import numpy as npfrom matplotlib.path import Pathfrom matplotlib.patches import PathPatchimport matplotlib.pyplot as plt vertices = []codes = [] codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]vertices = [(1, 1), (1, 2), (2, 2), (2, 1), (0, 0)] codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]vertices += [(4, 4), (5, 5), (5, 4), (0, 0)] vertices = np.array(vertices, float)path = Path(vertices, codes) pathpatch = PathPatch(path, facecolor ='None', edgecolor ='green') fig, ax = plt.subplots()ax.add_patch(pathpatch)ax.autoscale() fig.suptitle('matplotlib.axes.Axes.autoscale() \function Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.collections import EllipseCollection x = np.arange(10)y = np.arange(15)X, Y = np.meshgrid(x, y) XY = np.column_stack((X.ravel(), Y.ravel())) fig, ax = plt.subplots() ec = EllipseCollection(10, 10, 5, units ='y', offsets = XY * 0.5, transOffset = ax.transData, cmap ="inferno") ec.set_array((X * Y).ravel())ax.add_collection(ec)ax.autoscale_view()ax.set_xlabel('X')ax.set_ylabel('y')cbar = plt.colorbar(ec)cbar.set_label('X + Y') fig.suptitle('matplotlib.axes.Axes.autoscale() function \Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text... |
How to remove an element from ArrayList in Java? | 07 Jul, 2022
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. With the introduction and upgradations in java versions, newer methods are being available if we do see from Java8 perceptive lambda expressions and streams concepts were not available before it as it was introduced in java version8, so do we have more ways to operate over Arraylist to perform operations. Here we will be discussing a way to remove an element from an ArrayList.
While removing elements from ArrayList there can either we are operating to remove elements over indexes or via values been there in an ArrayList. We will be discussing both ways via interpreting through a clean java program.
Methods:
There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows:
Using remove() method by indexes(default)Using remove() method by valuesUsing remove() method over iterators
Using remove() method by indexes(default)
Using remove() method by values
Using remove() method over iterators
Note: It is not recommended to use ArrayList.remove() when iterating over elements.
Method 1: Using remove() method by indexes
It is a default method as soon as we do use any method over data structure it is basically operating over indexes only so whenever we do use remove() method we are basically removing elements from indices from an ArrayList.
ArrayList class provides two overloaded remove() methods.
remove(int index): Accepts the index of the object to be removed
remove(Object obj): Accepts the object to be removed
Let us figure out with the help of examples been provided below as follows:
Example:
Java
// Java program to Remove Elements from ArrayList// Using remove() method by indices // Importing required classesimport java.util.ArrayList;import java.util.List; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of List interface with // reference to ArrayList class List<Integer> al = new ArrayList<>(); // Adding elements to our ArrayList // using add() method al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Printing the current ArrayList System.out.println(al); // This makes a call to remove(int) and // removes element 20 al.remove(1); // Now element 30 is moved one position back // So element 30 is removed this time al.remove(1); // Printing the updated ArrayList System.out.println(al); }}
[10, 20, 30, 1, 2]
[10, 1, 2]
Now we have seen removing elements in an ArrayList via indexes above, now let us see that the passed parameter is considered an index. How to remove elements by value.
Method 2: Using remove() method by values
Example:
Java
// Java program to Remove Elements from ArrayList// Using remove() method by values // Importing required classesimport java.util.ArrayList;import java.util.List; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of List interface with // reference to ArrayList List<Integer> al = new ArrayList<>(); // Adding elements to ArrayList class // using add() method al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Printing the current ArrayList System.out.println(al); // This makes a call to remove(Object) and // removes element 1 al.remove(Integer.valueOf(1)); // This makes a call to remove(Object) and // removes element 2 al.remove(Integer.valueOf(2)); // Printing the modified ArrayList System.out.println(al); }}
Output :
[10, 20, 30,1 ,2]
[10, 20, 30]
Note: It is not recommended to use ArrayList.remove() when iterating over elements.
Also new Integer( int_value) has been deprecated since Java 9, so it is better idea to use Integer.valueOf(int_value) to convert a primitive integer to Integer Object.
Method 3: Using Iterator.remove() method
This may lead to ConcurrentModificationException When iterating over elements, it is recommended to use Iterator.remove() method.
Example:
Java
// Java program to demonstrate working of// Iterator.remove() on an integer ArrayListimport java.util.ArrayList;import java.util.Iterator;import java.util.List; public class GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList List<Integer> al = new ArrayList<>(); // Adding elements to our ArrayList // using add() method al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Printing the current ArrayList System.out.println(al); // Creating iterator object Iterator itr = al.iterator(); // Holds true till there is single element // remaining in the object while (itr.hasNext()) { // Remove elements smaller than 10 using // Iterator.remove() int x = (Integer)itr.next(); if (x < 10) itr.remove(); } // Printing the updated ArrayList System.out.print(al); }}
[10, 20, 30, 1, 2]
[10, 20, 30]
This article is contributed by Nitsdheerendra. 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.
Ankur Goel
anikakapoor
solankimayank
gabaa406
simranarora5sos
sumitgumber28
purushottamkumar4
Java-ArrayList
Java-Collections
java-list
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 727,
"s": 52,
"text": "ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but... |
Python | Remove element from given list containing specific digits | 11 Oct, 2021
Given a list, the task is to remove all those elements from list which contains the specific digits.
Examples:
Input: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
no_delete = ['2', '3', '4', '0']
Output: [1, 5, 6, 7, 8, 9, 11, 15, 16]
Explanation:
Numbers 2, 3, 4, 10, 12, 13, 14 contains digits
from no_delete, therefore remove them.
Input: lst = [1, 2, 3, 4, 5, 6, 7, 8, 13, 15, 16]
no_delete = {'6', '5', '4', '3'}
Output: [1, 2, 7, 8, 9, 10, 11, 12]
Explanation:
Numbers 3, 4, 5, 6, 13, 14, 15, 16 contains digits
from no_delete, therefore remove them.
Below are some methods to do the task.
Method #1: Using Iteration
# Python code to remove all those elements # from list which contains certain digits # Input List InitialisationInput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] # Numbers to deleteno_delete = [1, 0] # Output List InitialisationOutput = [] # Using iteration to remove all the elements for elem in Input: flag = 1 temp = elem while elem > 0: rem = elem % 10 elem = elem//10 if rem in no_delete: flag = 0 if flag == 1: Output.append(temp) # Printing Output print("Initial list is :", Input)print("Delete list :", no_delete)print("List after removing elements is :", Output)
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
Delete list : [1, 0]
List after removing elements is : [2, 3, 4, 5, 6, 7, 8, 9]
Method #2: Using List comprehension and any() function
# Python code to remove all those elements from list # which contains certain digits # Input List InitialisationInput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] # Numbers to deleteno_delete = ['2', '3', '4', '0'] # using list comprehension and any()Output = [a for a in Input if not any(b in no_delete for b in str(a))] # Printing Output print("Initial list is :", Input)print("Delete list :", no_delete)print("List after removing elements is :", Output)
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
Delete list : ['2', '3', '4', '0']
List after removing elements is : [1, 5, 6, 7, 8, 9, 11, 15, 16]
Method #3: Using List comprehension and set()
# Python code to remove all those elements from list # which contains certain digits # Input List InitialisationInput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] # Numbers to deleteno_delete = {'6', '5', '4', '3'} # Using list comprehension and setOutput = [x for x in Input if not no_delete & set(str(x))] # Printing Output print("Initial list is :", Input)print("Delete list :", no_delete)print("List after removing elements is :", Output)
Initial list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16]
Delete list : {'3', '4', '6', '5'}
List after removing elements is : [1, 2, 7, 8, 9, 10, 11, 12]
gabaa406
Python list-programs
Python
Python Programs
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
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Split string into list of characters | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "Given a list, the task is to remove all those elements from list which contains the specific digits."
},
{
"code": null,
"e": 139,
"s": 129,
"text": "Examp... |
Difference between Windows application and Web application | 15 Jun, 2022
1. Windows application : It is an application that can run on the windows platform. Graphical user interface forms can be created using this. We can create web applications using IDE Microsoft Visual Studio. This can be done using a variety of programming languages such C#, C++, J#, Visual Basic and many more. Windows applications on a computer system –
2. Web application : Web application is an application that runs on web browser making use of web server. It makes use of is Microsoft IIS configuration i.e., Internet Information Services (in developing web applications). A variety of web applications using .net can be made. These include many ranging from simple HTML pages to highly interactive business applications.
Examples of Web applications –
Difference between Windows application and web application :
sumitgumber28
abhishek0719kadiyan
annieahujaweb2020
Web technologies
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Synchronous and Asynchronous Transmission
Difference Between Method Overloading and Method Overriding in Java
Difference Between Go-Back-N and Selective Repeat Protocol
Time complexities of different data structures
Difference between Compile-time and Run-time Polymorphism in Java
Differences and Applications of List, Tuple, Set and Dictionary in Python
Difference between HTTP GET and POST Methods
Difference between Top down parsing and Bottom up parsing
Difference between Prim's and Kruskal's algorithm for MST
Difference Between Paging and Segmentation | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 385,
"s": 28,
"text": "1. Windows application : It is an application that can run on the windows platform. Graphical user interface forms can be created using this. We can create web applications us... |
Python bytes() method | 26 May, 2022
Python byte() function converts an object to an immutable byte-represented object of given size and data.
Syntax : bytes(src, enc, err)
Parameters :
src : The source object which has to be converted
enc : The encoding required in case object is a string
err : Way to handle error in case the string conversion fails.
Returns : Byte immutable object consisting of unicode 0-256 characters according to src type.
integer : Returns array of size initialized to null
iterable : Returns array of iterable size with elements equal to iterable elements( 0-256 )
string : Returns the encoded string acc. to enc and if encoding fails, performs action according to err specified.
no arguments : Returns array of size 0.
In this example, we are going to convert string to bytes using the Python bytes() function, for this we take a variable with string and pass it into the bytes() function with UTF-8 parameters. UTF-8 is capable of encoding all 1,112,064 valid character code points in Unicode using one to four one-byte code units
Python3
# python code demonstrating# int to bytesstr = "Welcome to Geeksforgeeks" arr = bytes(str, 'utf-8') print(arr)
Output:
b'Welcome to Geeksforgeeks'
In this example, we are going to see how to get an array of bytes from an integer using the Python bytes() function, for this we will pass the integer into the bytes() function.
Python3
# python code to demonstrate# int to bytes number = 12result = bytes(number) print(result)
Output:
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
When we pass nothing in bytes() function then it creates an array of size 0.
Python3
print(bytes())
Output:
b''
Python3
# Python 3 code to demonstrate the# working of bytes() on int, iterables, none # initializing integer and iterablesa = 4lis1 = [1, 2, 3, 4, 5] # No argument caseprint ("Byte conversion with no arguments : " + str(bytes())) # conversion to bytesprint ("The integer conversion results in : " + str(bytes(a)))print ("The iterable conversion results in : " + str(bytes(lis1)))
Output:
Byte conversion with no arguments : b''
The integer conversion results in : b'\x00\x00\x00\x00'
The iterable conversion results in : b'\x01\x02\x03\x04\x05'
Bytes accept a string as an argument and require an encoding scheme with it to perform it. The most important aspect of this is handling errors in case of encoding failure, some of the error handling schemes defined are :
String Error Handlers :
strict : Raises the default UnicodeDecodeError in case of encode failure.
ignore : Ignores the unencodable character and encodes the remaining string.
replace : Replaces the unencodable character with a ‘?’.
Python3
# Python 3 code to demonstrate the# working of bytes() on string # initializing stringstr1 = 'GeeksfÖrGeeks' # Giving ascii encoding and ignore errorprint("Byte conversion with ignore error : " + str(bytes(str1, 'ascii', errors='ignore'))) # Giving ascii encoding and replace errorprint("Byte conversion with replace error : " + str(bytes(str1, 'ascii', errors='replace'))) # Giving ascii encoding and strict error# throws exceptionprint("Byte conversion with strict error : " + str(bytes(str1, 'ascii', errors='strict')))
Output:
Byte conversion with ignore error : b'GeeksfrGeeks'
Byte conversion with replace error : b'Geeksf?rGeeks'
Exception :
UnicodeEncodeError: ‘ascii’ codec can’t encode character ‘\xd6’ in position 6: ordinal not in range(128)
kumar_satyam
abhisidbuddhagautam
sumitgumber28
Python-Built-in-functions
Python-Data Type
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
Defaultdict in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "Python byte() function converts an object to an immutable byte-represented object of given size and data."
},
{
"code": null,
"e": 164,
"s": 134,
"text": "... |
Maximum of four numbers without using conditional or bitwise operator in C++ | In this problem, we are given four integer numbers. Our task is to create a
program to find the maximum of four numbers without using conditional or
bitwise operator in C++.
Code Description − Here, we have four integer values. And we need to find the maximum value out of these numbers without using any conditional or bitwise operator.
Let’s take an example to understand the problem,
a = 4, b = 7, c = 1, d = 9
9
To solve the problem, we will take two elements first, then take the greater element with pair. For each pair, we will create a 2 element arr[] and find which element is greater using the boolean value. The boolean value is used as index, found using the the formula [abs(x - y) + (x - y)].
An easy explanation is,
If arr[0] is greater than arr[1], boolean value is False. else it is True.
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
int findMax(int x, int y){
int arr[2] = {x,y};
bool MaxIndex = ( !(arr[0] - arr[1] + abs(arr[0] - arr[1])));
return arr[MaxIndex];
}
int CalcMaxElement(int a, int b, int c, int d) {
int max = a;
max = findMax(max, b);
max = findMax(max, c);
max = findMax(max, d);
return max;
}
int main() {
int a = 4, b = 9, c = 7, d = 1;
cout<<"The maximum of four numbers is "<<CalcMaxElement(a,b,c,d);
return 0;
}
The maximum of four numbers is 9 | [
{
"code": null,
"e": 1361,
"s": 1187,
"text": "In this problem, we are given four integer numbers. Our task is to create a\nprogram to find the maximum of four numbers without using conditional or\nbitwise operator in C++."
},
{
"code": null,
"e": 1525,
"s": 1361,
"text": "Code D... |
Time complexity of recursive Fibonacci program | 20 Oct, 2017
The Fibonacci numbers are the numbers in the following integer sequence 0, 1, 1, 2, 3, 5, 8, 13...Mathematically Fibonacci numbers can be written by the following recursive formula.
For seed values F(0) = 0 and F(1) = 1
F(n) = F(n-1) + F(n-2)
Before proceeding with this article make sure you are familiar with the recursive approach discussed in Program for Fibonacci numbers
Analysis of the recursive Fibonacci program:We know that the recursive equation for Fibonacci is =++.What this means is, the time taken to calculate fib(n) is equal to the sum of time taken to calculate fib(n-1) and fib(n-2). This also includes the constant time to perform the previous addition.
On solving the above recursive equation we get the upper bound of Fibonacci as but this is not the tight upper bound. The fact that Fibonacci can be mathematically represented as a linear recursive function can be used to find the tight upper bound.Now Fibonacci is defined as
= +
The characteristic equation for this function will be = + – – =
Solving this by quadratic formula we can get the roots as = (+)/ and =( – )/
Now we know that solution of a linear recursive function is given as = +
where and are the roots of the characteristic equation.So for our Fibonacci function = + the solution will be
= +Clearly and are asymptotically the same as both functions are representing the same thing.Hence it can be said that = or we can write below (using the property of Big O notation that we can drop lower order terms) = = This is the tight upper bound of fibonacci.\
Fun Fact:1.6180 is also called the golden ratio. You can read more about golden ratio here: Golden Ratio in Maths
This article is contributed by Vineet Joshi. 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.
Fibonacci
Analysis
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Analysis of Algorithms | Set 4 (Analysis of Loops)
Time Complexity of building a heap
Analysis of different sorting techniques
Time complexities of different data structures
NP-Completeness | Set 1 (Introduction)
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between NP hard and NP complete problem
Analysis of Algorithms | Big-O analysis
What does 'Space Complexity' mean? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Oct, 2017"
},
{
"code": null,
"e": 234,
"s": 52,
"text": "The Fibonacci numbers are the numbers in the following integer sequence 0, 1, 1, 2, 3, 5, 8, 13...Mathematically Fibonacci numbers can be written by the following recursive f... |
Queries using AND ,OR ,NOT operators in MySQL | 21 Jun, 2022
AND, OR, NOT operators are basically used with WHERE clause in order to retrieve data from table by filtering with some conditions using AND, OR, NOT in MySQL.Here in this article let us see different queries on the student table using AND, OR, NOT operators step-by-step.
Step-1:Creating a database university:
CREATE DATABASE university;
Step-2:Using the database university:
USE university;
Step-3:Creating a table student:
CREATE TABLE student(
student_id INT
student_name VARCHAR(20)
birth_date DATE
branch VARCHAR(20)
state VARCHAR(20));
Step-4:Viewing the description of the table student:
DESCRIBE student;
Step-5:Adding rows into student table:
INSERT INTO student VALUES(194001,'PRANAB','1999-03-17','CSE','PUNJAB');
INSERT INTO student VALUES(194002,'PRAKASH','2000-08-07','ECE','TAMIL NADU');
INSERT INTO student VALUES(194003,'ROCKY','2000-03-10','ECE','PUNJAB');
INSERT INTO student VALUES(194004,'TRIBHUVAN','1999-03-15','CSE','ANDHRA PRADESH');
INSERT INTO student VALUES(194005,'VAMSI','2000-04-19','CSE','TELANGANA');
Step-6:Viewing the rows in the table:
SELECT * FROM student;
syntax for AND operator:SELECT * FROM table_nameWHERE condition1 AND condition2 AND ....CONDITIONn;
Example-1:Query to find student records with a branch with CSE and state with PUNJAB using AND operator in MySQL:
SELECT *
FROM student
WHERE branch='CSE'ANDstate='PUNJAB'
All the students with branch CSE and from Punjab.
syntax for OR operator:SELECT * FROM table_nameWHERE condition1 OR condition2 OR....CONDITIONn;
Example-2:Query to find student records with a branch with CSE or ECE using OR operator in MySQL:
SELECT *
FROM student
WHERE branch='CSE' OR branch='ECE';
All the students with branch either CSE or ECE.
syntax for NOT operator:SELECT * FROM table_nameWHERE NOT condition1 NOT condition2 NOT...CONDITIONn;
Example-3:Query to find student records who were out of PUNJAB using the NOT operator in MySQL:
SELECT *
FROM student
WHERE NOT state='PUNJAB';
All the students were from states other than Punjab.
aayushi2402
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 326,
"s": 53,
"text": "AND, OR, NOT operators are basically used with WHERE clause in order to retrieve data from table by filtering with some conditions using AND, OR, NOT in MySQL.Here in this ar... |
What are the differences between an Annotation and a Decorator in Angular? | 11 Feb, 2022
Although Annotations and Decorators both share the same @ symbol in Angular, they both are different language features.
Annotations: These are hard-coded language feature. Annotations are only metadata set on the class that is used to reflect the metadata library. When user annotates a class, the compiler creates an attribute on that class called annotations, stores an annotation array in it, then tries to instantiate an object with the same name as the annotation, passing the metadata into the constructor. Annotations are not predefined in AngularJs so we can name them on our own.
Example:@ComponentAnnotation
@ComponentAnnotation
Features of Annotations:
Annotations are hard-coded.
Annotations are used by AtScript and Traceur compiler.
Annotations reflect metadata library
Note: Nowadays AngularJs switched from AtScript to TypeScript but Annotations are supported these days also.
Example: Here component is annotated as ComponentAnnotation and further used.
import { ComponentAnnotation as Component,} from '@angular/core'; export class ComponentAnnotation extends DirectiveMetadata { constructor() { }}
Decorators: A decorator is a function that adds metadata to a class, its members, or its method arguments. A decorator is just a function that gives you access to the target that needs to be decorated. There are four type of decorators all of them arem mentioned below:
Types of Decorators:
Class decorators like @Component, @NgModule
Property decorators like @Input and @Output
Method decorators like @HostListener
Parameter decorators like @Injectable
Features of Decorators:
Decorators are predefined in AngularJs.
Decorators are used by TypeScript compiler.
Decorators are used to attach metadata to a class,objects and method.
Example:
import { Component } from '@angular/core'; @Component({ selector: 'hi', template: '<div>GeeksForGeeks</div>',})export class Geeks{ constructor() { console.log('GeeksForGeeks'); }}
Differences between Annotation and Decorator:
Conclusion:There is a very significant difference between Annotations and Decorators in AngularJS. Both Decorators and Annotations are supported by Angular. This is a legacy thing because Angular2 swapped from AtScript to TypeScript. Decorators are the default in AngularJs but you can use Annotations too.
jainnikhil0442
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "Although Annotations and Decorators both share the same @ symbol in Angular, they both are different language features."
},
{
"code": null,
"e": 617,
"s": 148,... |
Print contents of a file in C | Here is an example to print contents of a file in C language,
Let’s say we have “new.txt” file with the following content.
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
Now, let us see the example.
#include<stdio.h>
#include<conio.h>
void main() {
FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");
while((s=fgetc(f))!=EOF) {
printf("%c",s);
}
fclose(f);
getch();
}
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file.
FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");
while((s=fgetc(f))!=EOF) {
printf("%c",s);
} | [
{
"code": null,
"e": 1249,
"s": 1187,
"text": "Here is an example to print contents of a file in C language,"
},
{
"code": null,
"e": 1310,
"s": 1249,
"text": "Let’s say we have “new.txt” file with the following content."
},
{
"code": null,
"e": 1349,
"s": 1310,
... |
How to Check GPS is On or Off in Android Programmatically? | 27 Sep, 2021
GPS (Global Positioning System) is a satellite-based navigation system that accommodates radio signals between satellite and device to process the device’s location in the form of coordinates. GPS gives latitude and longitude values of the device. Recent mobile phones are equipped with GPS modules to know their exact location on software like Google Maps. However, GPS data is used for many other applications for finding the device, showing news related to that geographic location, and many others.
This article will show you how you could programmatically check if the GPS in an Android device is enabled or disabled.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Add permissions in the AndroidManifest.xml
XML
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a TextView and a Button in the layout file. The TextView will display if the GPS is enabled or disabled upon the Button trigger.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Hello Geek!" android:layout_above="@+id/button"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Click"/> </RelativeLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Contextimport android.location.LocationManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.os.Looperimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport java.util.concurrent.Executors class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring TextView and Button from the layout file val mTextView = findViewById<TextView>(R.id.text_view) val mButton = findViewById<Button>(R.id.button) // What happens when button is clicked mButton.setOnClickListener { // Calling Location Manager val mLocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager // Checking GPS is enabled val mGPS = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // Display the message into the string mTextView.text = mGPS.toString() } }}
Output:
You can see that when the button is clicked, the status of GPS is displayed in the TextView.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 531,
"s": 28,
"text": "GPS (Global Positioning System) is a satellite-based navigation system that accommodates radio signals between satellite and device to process the device’s location in the for... |
Python | Pandas DataFrame.axes | 20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.axes attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
Syntax: DataFrame.axes
Parameter : None
Returns : list
Example #1: Use DataFrame.axes attribute to return a list containing the axes labels of the dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.axes attribute to return the axes labels of the dataframe.
# return the axes labels of the dataframeresult = df.axes # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.axes attribute has successfully returned a list containing the axes labels of the dataframe. Example #2: Use DataFrame.axes attribute to return a list containing the axes labels of the dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.axes attribute to return the axes labels of the dataframe.
# return the axes labels of the dataframeresult = df.axes # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.axes attribute has successfully returned a list containing the axes labels of the dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both ... |
Tkinter – Separator Widget | 15 Oct, 2021
Tkinter supports a variety of widgets to make GUI more and more attractive and functional. The Separator widget is used to partition the tkinter widgets such as label, buttons etc. Using this widget we can make our design more attractive and intuitive. Now we will see how to implement this widget.
Syntax:
Separator(master, orient)
Parameters:
master: parent widget or main Tk() object
orient: vertical or horizontal
Vertical Orientation:
Python3
# Python program to# Illustrate Separator# widget # Import required modulesfrom tkinter import *from tkinter import ttk # Main tkinter windowx = Tk()x.geometry("400x300") # Label Widgetb = Label(x, bg="#f5f5f5", bd=4, relief=RAISED, text="With Separator")b.place(relx=0.03, rely=0.1, relheight=0.8, relwidth=0.4) # Separator objectseparator = ttk.Separator(x, orient='vertical')separator.place(relx=0.47, rely=0, relwidth=0.2, relheight=1) # Label Widgeta = Label(x, bg="#f5f5f5", bd=4, relief=RAISED, text="With Separator")a.place(relx=0.5, rely=0.1, relheight=0.8, relwidth=0.4) mainloop()
Output:
In the above program, the vertical without separator output will be generated only. However, a tkinter window without separator looks like this:
Horizontal Orientation:
Python3
# Python program to# Illustrate Separator# widget # Import required modulesfrom tkinter import *from tkinter import ttk # Main tkinter windowx = Tk()x.geometry("400x300") # Label Widgetb = Label(x, bg="#f5f5f5", bd=4, relief=RAISED, text="With Separator")b.place(relx=0.1, rely=0.05, relheight=0.4, relwidth=0.8) # Separator objectseparator = ttk.Separator(x, orient='horizontal')separator.place(relx=0, rely=0.47, relwidth=1, relheight=1) # Label Widgeta = Label(x, bg="#f5f5f5", bd=4, relief=RAISED, text="With Separator")a.place(relx=0.1, rely=0.5, relheight=0.4, relwidth=0.8) mainloop()
Output:
In the above program, the horizontal without separator output will be generated only. However, a tkinter window without a separator looks like this:
anikakapoor
sweetyty
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 327,
"s": 28,
"text": "Tkinter supports a variety of widgets to make GUI more and more attractive and functional. The Separator widget is used to partition the tkinter widgets such as label, buttons... |
Java program to remove all duplicates words from a given sentence | To remove all duplicate words from a given sentence, the Java code is as follows −
Live Demo
import java.util.Arrays;
import java.util.stream.Collectors;
public class Demo{
public static void main(String[] args){
String my_str = "This is a is sample a sample only.";
my_str = Arrays.stream(my_str.split("\\s+")).distinct().collect(Collectors.joining(" "));
System.out.println(my_str);
}
}
This is a sample only.
A class named Demo contains the main function. In this function, a String object is defined. It is split based on the spaces and only distinct words of the string are joined together using space as a separator and displayed on the console. | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To remove all duplicate words from a given sentence, the Java code is as follows −"
},
{
"code": null,
"e": 1156,
"s": 1145,
"text": " Live Demo"
},
{
"code": null,
"e": 1476,
"s": 1156,
"text": "import java.util.... |
How to display paragraph elements as inline using CSS ? - GeeksforGeeks | 05 Nov, 2020
The purpose of this article is to display paragraph elements as inline elements using CSS. The display property in CSS is used for placing the components (“div”, “hyperlink”, “heading”, etc) on the web page. The display property is set to inline. It has the default property of “anchor” tags. It is used to place the “div” inline i.e. in a horizontal manner. The inline option of display property ignores the “width” and “height” set by the user.
Syntax:
display: inline;
Example:
HTML
<!DOCTYPE html><html> <head> <style> #main { height: 200px; width: 200px; background: teal; display: inline; } #main1 { height: 200px; width: 200px; background: cyan; display: inline; } #main2 { height: 200px; width: 200px; background: green; display: inline; } .gfg { margin-left: 20px; font-size: 42px; font-weight: bold; color: #009900; } .geeks { font-size: 25px; margin-left: 30px; } .main { margin: 50px; } </style></head> <body> <div class="gfg">GeeksforGeeks</div> <h2> How to display paragraph elements as inline elements using CSS? </h2> <p class="main"> <p id="main"> BLOCK 1 </p> <p id="main1"> BLOCK 2</p> <p id="main2">BLOCK 3 </p> </p></body> </html>
Output:
Supported browsers are listed below:
Google ChromeInternet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 27068,
"s": 26621,
"text": "The purpose of this article is to display paragraph elements as inline elements using CSS. The display property in CSS is used for placing the components (“div”, “... |
Launching parallel tasks in Python | If a Python program can be broken into subprograms who is processing do not depend on each other, then each of the subprogram can be run in parallel when the overall program is being run. This concept is known as parallel processing in Python.
This module can be used to create many child processes of a main process which can run in parallel. In the below program we initialize a process and then use the run method to run the multiple sub-processes. We can see different sub processes in the print statement by using the process id. We also use the sleep method to see print the statements with a small delay one after another.
Live Demo
import multiprocessing
import time
class Process(multiprocessing.Process):
def __init__(self, id):
super(Process, self).__init__()
self.id = id
def run(self):
time.sleep(1)
print("Running process id: {}".format(self.id))
if __name__ == '__main__':
p = Process("a")
p.start()
p.join()
p = Process("b")
p.start()
p.join()
p = Process("c")
p.start()
p.join()
Running the above code gives us the following result −
Running process id: a
Running process id: b
Running process id: c | [
{
"code": null,
"e": 1306,
"s": 1062,
"text": "If a Python program can be broken into subprograms who is processing do not depend on each other, then each of the subprogram can be run in parallel when the overall program is being run. This concept is known as parallel processing in Python."
},
{... |
Java Program to Add Two Numbers | public class MyFirstJavaProgram {
/* This is my first java program.
* This will add two numbers
*/
public static void main(String []args) {
int a = 3, b = 4;
Int sum = a + b;
System.out.println(sum); // prints 7
}
} | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": " public class MyFirstJavaProgram {\n\n /* This is my first java program.\n * This will add two numbers\n */\n\n public static void main(String []args) {\n int a = 3, b = 4;\n Int sum = a + b;\n System.out.println(sum); // prints... |
Theory of Principal Component Analysis (PCA) and implementation on Python | by Jonathan Leban | Towards Data Science | When working on a complex science project with a lot of data where each example is described by many characteristics, you may want to visualize the data. In fact, visualization in 1D, 2D or 3D is easy, but if you want to visualize your data composed of 100 characteristics, you won’t see anything in 100D. So you have to reduce the dimension and place your data in a space with a dimension equal to or smaller than 3D. This can be done using Principal Component Analysis (PCA). Another very good use of PCA is to speed up the training process of your machine learning algorithm. The more features you have, the more complex your machine learning algorithm is and the more parameters it needs to learn. Thus, the longer the computation time will be. Now, it seems obvious that if you reduce the size of your data, the time needed to learn your algorithm will decrease considerably. But, you may wonder if we reduce the number of variables, then we will lose a lot of information from our data and the result will not be accurate at all. This is the main challenge of the PCA algorithm and we will see in this article how to ensure good accuracy.
To illustrate this situation, I will use the MNIST database is a large database of handwritten digits.
In this article, I will show you the theory behind PCA and how to implement it on Python. I will also give you some tips on when to use this method.
In the principal component analysis algorithm, the objective is to find the k vectors on which to project the data in order to minimize the projection error. These k vectors will be the k directions on which to project the data. Here, k corresponds to your final dimension: if you want to look at your data in a 2D dimensional space, then k will be equal to 2.
How do we find these k vectors ?
Let’s call A the matrix which describes our data. PCA involves transforming interdependent variables (called “correlated” in statistics) into new variables that are uncorrelated with each other. These variables are called principal components and will describe the information conveyed by the data. We need to look at the covariance matrix because covariance is a measure of the joint variability of two random variables. But why covariance? Let’s think about how we can learn from the data. You look at the mean and how the variables are far from or close to the mean. This is essentially covariance: the deviation from the mean. So in the PCA, we have to calculate the covariance of our data matrix and look for the directions or vectors that collect the most information so that we can keep the PI and get rid of the rest. But it’s not as simple as that and we’re going to look at it step by step to see how we do it.
The aim of this step is to standardize the range of the continuous initial variables so that each one of them contributes equally to the analysis.
More specifically, the reason why it is critical to perform standardization prior to PCA, is that the latter is quite sensitive regarding the variances of the initial variables. That is, if there are large differences between the ranges of initial variables, those variables with larger ranges will dominate over those with small ranges (For example, a variable that ranges between 0 and 100 will dominate over a variable that ranges between 0 and 1), which will lead to biased results. So, transforming the data to comparable scales can prevent this problem.
Mathematically, this can be done by subtracting the mean and dividing by the standard deviation for each value of each variable. Recall that Ais the matrix which describes our data, thus each row is an example and each column is a feature. Let’s set n equal to the number of features et m the number of examples. Thus the matrix A is a matrix mxn.
The covariance matrix is given by the following formula:
Then, we need to diagonalize the covariance matrix. We will call S the diagonal matrix. U and V will be the transformation matrices. Thus we have:
If you have heard about PCA you may have heard about SVD. SVD is for Singular Value Decomposition and it is what we are applying here on A. The SVD theory states that it exist the following decomposition for the matrix A:
where U and V are orthogonal matrices with orthonormal eigenvectors chosen from AAT and ATA respectively. S’ is a diagonal matrix with r elements equal to the root of the positive eigenvalues of XXT or XT X. The diagonal elements are composed of singular values.
And we have S’2 = S. The next step is to reorganize the eigenvectors to produce U and V. To standardize the solution, we order the eigenvectors such that vectors with higher eigenvalues come before those with smaller values.
Comparing to eigen decomposition, SVD works on non-square matrices. U and V are invertible for any matrix in SVD.
The idea of dimensionality reduction is to keep k eigen vectors which describe the best the data. Thus, we have:
Then we add null space, which is already orthogonal to first r v’s and u’s to go from reduced to full SVD.
There is a formula we need to apply to keep a certain percentage of the total variance. Let’s say we want to keep 99% of the variance then we have the following:
Now that we have seen the maths behind the PCA we will implement it on Python.
The dataset that we will use is accessible here. Thus first we import the data and the different libraries we will need.
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pylab as plt# import the datadata = pd.read_csv("train.csv")# some pre-processing on the datalabels = data['label'].head(1500) # we only keep the first 1500 # Drop the label feature and store the pixel data in A and we keep # only the first 1500A = data.drop("label",axis=1).head(1500)
from sklearn.preprocessing import StandardScalerstandardized_data = StandardScaler().fit_transform(A)
First, we calculate the covariance matrix of A.
covar_matrix = np.matmul(standardized_data.T , standardized_data)
Then, we calculate the eigen values and the corresponding eigen vectors. But here we only calculate the two highest ones.
# the parameter 'eigvals' is defined (low value to heigh value) # eigh function will return the eigen values in ascending ordervalues, vectors = eigh(covar_matrix, eigvals=(782,783))
Then we project the original data sample on the plane formed by the two principal eigen vectors we have just calculated.
new_coordinates = np.matmul(vectors.T, sample_data.T)
Then, we append the labels to the 2d projected data and we create a dataframe to then use seaborn and plot the labeled points:
new_coordinates = np.vstack((new_coordinates, labels)).T# creating a new data frame for plotting the labeled points.dataframe = pd.DataFrame(data=new_coordinates, columns=("1st_principal", "2nd_principal", "label"))# plotsn.FacetGrid(dataframe, hue="label", size=6).map(plt.scatter, '1st_principal', '2nd_principal').add_legend()plt.show()
There is a lot of overlapping among classes means PCA not very good for the high dimensional dataset. Very few classes can be separated but most of them are mixed. PCA is mainly used for dimensionality reduction, not for visualization. To visualize high dimension data, we mostly use T-SNE.
We can also use the PCA module in Python to do it:
# initializing the pcafrom sklearn import decompositionpca = decomposition.PCA()# configuring the parameteres# the number of components = 2pca.n_components = 2pca_data = pca.fit_transform(standardized_data)pca_data = np.vstack((pca_data.T, labels)).T# creating a new data frame which help us in plotting the result datapca_df = pd.DataFrame(data=pca_data, columns=("1st_principal", "2nd_principal", "label"))# plot the datasns.FacetGrid(pca_df, hue="label", size=6).map(plt.scatter, '1st_principal', '2nd_principal').add_legend()plt.show()
In this section we want to find the number of eigen vectors necessary to describe our data well. Thus we need to calculate the significance of each eigen value and then the cumulative variance. I define the significance of an eigen value as:
# initializing the pcafrom sklearn import decompositionpca = decomposition.PCA()# PCA for dimensionality reduction (non-visualization)pca.n_components = 784pca_data = pca.fit_transform(standardized_data)# then we calculate the significance but the absolute value is not necessary as the eigen values are already positivesignificance = pca.explained_variance_/ np.sum(pca.explained_variance_)cum_var_explained = np.cumsum(significance)# Plot the PCA spectrumplt.figure(1, figsize=(6, 4))plt.clf()plt.plot(cum_var_explained, linewidth=2)plt.axis('tight')plt.grid()plt.xlabel('n_components')plt.ylabel('Cumulative_explained_variance')plt.show()
Let’s refresh what we have seen in the first part:
Thus we plot the cumulative sum of variance with the component. Here 300 components explain almost 90% of the variance. So we can reduce the dimension according to the required variance.
PCA is a method of reducing dimensionality, but component independence can be required: Independent Component Analysis (ICA). PCA is an unsupervised linear method, which is not the case with most unsupervised techniques. Since PCA is a dimensionality reduction method, it allows the data to be projected in 1D, 2D or 3D and thus visualize the data. It is also very useful for speeding up the training process because it considerably reduces the number of features and therefore the number of parameters.
I hope you have find what you were looking for in this article and good luck for your future projects!
PS: I am currently a Master of Engineering Student at Berkeley, and if you want to discuss the topic, feel free to reach me. Here is my email. | [
{
"code": null,
"e": 1317,
"s": 172,
"text": "When working on a complex science project with a lot of data where each example is described by many characteristics, you may want to visualize the data. In fact, visualization in 1D, 2D or 3D is easy, but if you want to visualize your data composed of 1... |
Age Testing | It is a testing technique that evaluates a system's ability to perform in the future and usually carried out by test teams. As the system gets older, how significantly the performance might drop is what is being measured in Age Testing.
Let us also understand the concept of Defect Age. It is measured in terms of two parameters:
1. Phases
2. Time
Defect age in phases is defined as the difference between defect injection phase and defect detection phase.
1. 'defect injection phase' is the phase of the software development life cycle when the defect was introduced.
2. 'defect detection phase' is the phase of the software development life cycle when the defect was pinpointed.
Defect Age in Phase = Defect Detection Phase - Defect Injection Phase
Consider, the SDLC Methodology that we have adopted has the following phases:
1. Requirements Development
2. Design
3. Coding
4. Unit Testing
5. Integration Testing
6. System Testing
7. Acceptance Testing, and if a defect is identified in Unit Testing (4) and the defect was introduced in Design stage (2) of the Development, then Defect Age is (4)-(2) = 2.
Defect age is defined as the time difference between defect detected date and the current date, provided the defect is still said to be open.
1. Defects are in "Open" and "Assigned" Status and NOT just in "New" Status.
2. Defects that are in "Closed" due to "non-reproducible" or "duplicate" are NOT considered.
3. Difference in days or hours is calculated, from the defect open date and current date.
Defect Age in Time = Defect Fix Date (OR) Current Date - Defect Detection Date
If a defect was detected on 05/05/2013 11:30:00 AM and closed on 23/05/2013 12:00:00 PM, the Defect Age would be calculated as follows.
Defect Age in Days = 05/05/2013 11:30:00 AM - 23/05/2013 12:00:00 PM
Defect Age in Days = 19 days
For assessing the effectiveness of each phase and any review/testing activities, lesser the defect age, better the effectiveness.
80 Lectures
7.5 hours
Arnab Chakraborty
10 Lectures
1 hours
Zach Miller
17 Lectures
1.5 hours
Zach Miller
60 Lectures
5 hours
John Shea
99 Lectures
10 hours
Daniel IT
62 Lectures
5 hours
GlobalETraining
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 5982,
"s": 5745,
"text": "It is a testing technique that evaluates a system's ability to perform in the future and usually carried out by test teams. As the system gets older, how significantly the performance might drop is what is being measured in Age Testing."
},
{
"c... |
Bulma Size - GeeksforGeeks | 08 Dec, 2021
Bulma size is used to set your website’s content font size, there are 7 different sizes class in Bulma. You can use any of them to define the size of your context.
Size classes:
is-size-1: The size of this class is pre defined which is font-size of 3rem.
is-size-2: The size of this class is pre defined which is font-size of 2.5rem.
is-size-3: The size of this class is pre defined which is font-size of 2rem.
is-size-4: The size of this class is pre defined which is font-size of 1.5rem.
is-size-5: The size of this class is pre defined which is font-size of 1.25rem.
is-size-6: The size of this class is pre defined which is font-size of 1.0rem.
is-size-7: The size of this class is pre defined which is font-size of 0.75rem.
Example: Below example illustrate the size class in Bulma.
HTML
<!DOCTYPE html><html> <head> <title>Bulma Typography</title> <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css'></head> <body class="has-text-centered"> <h1 class="is-size-2 has-text-success"> GeeksforGeeks </h1> <b>Bulma Size</b> <br> <div class="container"> <p class="is-size-1">GeeksforGeeks</p> <p class="is-size-2">GeeksforGeeks</p> <p class="is-size-3">GeeksforGeeks</p> <p class="is-size-4">GeeksforGeeks</p> <p class="is-size-5">GeeksforGeeks</p> <p class="is-size-6">GeeksforGeeks</p> <p class="is-size-7">GeeksforGeeks</p> </div></body></html>
Output:
Size
Reference: https://bulma.io/documentation/helpers/typography-helpers/#size
Bulma
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
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": 25717,
"s": 25689,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25881,
"s": 25717,
"text": "Bulma size is used to set your website’s content font size, there are 7 different sizes class in Bulma. You can use any of them to define the size of your context.... |
What is a Stream and what are the types of Streams and classes in Java? | Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc.
In general, a Stream will be an input stream or, an output stream.
InputStream − This is used to read data from a source.
OutputStream − This is used to write data to a destination.
Based on the data they handle there are two types of streams −
Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc.
Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.
Following diagram illustrates all the input and output Streams (classes) in Java.
In addition to above mentioned classes Java provides 3 standard streams representing the input and, output devices.
Standard Input − This is used to read data from user through input devices. keyboard is used as standard input stream and represented as System.in.
Standard Output − This is used to project data (results) to the user through output devices. A computer screen is used for standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err.
Following Java program reads the data from user using BufferedInputStream and writes it into a file using BufferedOutputStream.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedInputStreamExample {
public static void main(String args[]) throws IOException {
//Creating an BufferedInputStream object
BufferedInputStream inputStream = new BufferedInputStream(System.in);
byte bytes[] = new byte[1024];
System.out.println("Enter your data ");
//Reading data from key-board
inputStream.read(bytes);
//Creating BufferedOutputStream object
FileOutputStream out= new FileOutputStream("D:/myFile.txt");
BufferedOutputStream outputStream = new BufferedOutputStream(out);
//Writing data to the file
outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}
Enter your data
Hi welcome to Tutorialspoint ....
Data successfully written in the specified file | [
{
"code": null,
"e": 1233,
"s": 1062,
"text": "Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc."
},
{
"code": null,
"e": 1300,
"s": 1233,
"text": "In general,... |
Finding and returning uncommon characters between two strings in JavaScript | We are required to write a JavaScript function that takes in two strings. Our function should return a new string of characters which is not common to both the strings.
Following is the code −
Live Demo
const str1 = "xyab";
const str2 = "xzca";
const findUncommon = (str1 = '', str2 = '') => {
const res = [];
for (let i = 0; i < str1.length; i++){
if (!(str2.includes(str1[i]))){
res.push(str1[i])
}
}
for (let i = 0; i < str2.length; i++){
if (!(str1.includes(str2[i]))){
res.push(str2[i])
}
}
return res.join("");
};
console.log(findUncommon(str1, str2));
ybzc | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in two strings. Our function should return a new string of characters which is not common to both the strings."
},
{
"code": null,
"e": 1255,
"s": 1231,
"text": "Following is ... |
Filter query by current date in MySQL | Let us first create a table −
mysql> create table DemoTable(DueDate datetime);
Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-07-10 04:20:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-07-10 05:10:40');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('2019-07-10 09:00:20');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-07-10 10:01:04');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('2019-07-10 12:11:10');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+
| DueDate |
+---------------------+
| 2019-07-10 04:20:00 |
| 2019-07-10 05:10:40 |
| 2019-07-10 09:00:20 |
| 2019-07-10 10:01:04 |
| 2019-07-10 12:11:10 |
+---------------------+
5 rows in set (0.00 sec)
Following is the query to filter by current date −
mysql> select *from DemoTable where date(DueDate)=curdate()
and time(DueDate) > '04:00:00'
and time(DueDate) < '10:00:00';
This will produce the following output −
+---------------------+
| DueDate |
+---------------------+
| 2019-07-10 04:20:00 |
| 2019-07-10 05:10:40 |
| 2019-07-10 09:00:20 |
+---------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1178,
"s": 1092,
"text": "mysql> create table DemoTable(DueDate datetime);\nQuery OK, 0 rows affected (0.94 sec)"
},
{
"code": null,
"e": 1234,
"s": 1178,
"te... |
Spring AOP - Annotation Based Application | Let us write an example which will implement advice using Annotation based configuration. For this, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class Logging {
/** Following is the definition for a Pointcut to select
* all the methods available. So advice will be called
* for all the methods.
*/
@Pointcut("execution(* com.tutorialspoint.*.*(..))")
private void selectAll(){}
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
@Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student");
student.getName();
student.getAge();
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy/>
<!-- Definition for student bean -->
<bean id = "student" class = "com.tutorialspoint.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.Logging"/>
</beans>
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2472,
"s": 2269,
"text": "Let us write an example which will implement advice using Annotation based configuration. For this, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 2621,
"s"... |
Python Design Patterns - Command | Command Pattern adds a level of abstraction between actions and includes an object, which invokes these actions.
In this design pattern, client creates a command object that includes a list of commands to be executed. The command object created implements a specific interface.
Following is the basic architecture of the command pattern −
We will now see how to implement the design pattern.
def demo(a,b,c):
print 'a:',a
print 'b:',b
print 'c:',c
class Command:
def __init__(self, cmd, *args):
self._cmd=cmd
self._args=args
def __call__(self, *args):
return apply(self._cmd, self._args+args)
cmd = Command(dir,__builtins__)
print cmd()
cmd = Command(demo,1,2)
cmd(3)
The above program generates the following output −
The output implements all the commands and keywords listed in Python language. It prints the necessary values of the variables.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2592,
"s": 2479,
"text": "Command Pattern adds a level of abstraction between actions and includes an object, which invokes these actions."
},
{
"code": null,
"e": 2757,
"s": 2592,
"text": "In this design pattern, client creates a command object that includes... |
Difference between array_merge() and array_combine() functions in PHP - GeeksforGeeks | 30 Sep, 2021
array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. The merging occurs in such a manner that the values of one array are appended at the end of the previous array. The function takes the list of arrays separated by commas as a parameter that is needed to be merged and returns a new array with merged values of arrays passed in parameter.
Syntax:
array array_merge( $array1, $array2, ...., $array n)
where, $array1, $array2, . . . are the input arrays that need to be merged.
Example: PHP program to merge two arrays.
PHP
<?php // Define array1 with keys and values$array1 = array("subject1" => "Python","subject2" => "sql"); // Define array2 with keys and values$array2 = array("subject3" => "c/c++","subject4" => "java"); // Merge both array1 and array2$final = array_merge($array1, $array2); // Display merged arrayprint_r($final); ?>
Array
(
[subject1] => Python
[subject2] => sql
[subject3] => c/c++
[subject4] => java
)
Example 2: PHP program to merge multiple arrays.
PHP
<?php // Define array1 with keys and values$array1 = array("subject1" => "Python", "subject2" => "sql"); // Define array2 with keys and values$array2 = array("subject3" => "c/c++", "subject4" => "java"); // Define array3 with keys and values$array3 = array("subject5" => "CN", "subject6" => "OS"); // Define array4 with keys and values$array4 = array("subject7" => "data mining", "subject8" => "C#"); // Merge all arrays$final = array_merge($array1, $array2, $array3, $array4); // Display merged arrayprint_r($final); ?>
Array
(
[subject1] => Python
[subject2] => sql
[subject3] => c/c++
[subject4] => java
[subject5] => CN
[subject6] => OS
[subject7] => data mining
[subject8] => C#
)
array_combine() Function: The array_combine() function is used to combine two arrays and create a new array by using one array for keys and another array for values i.e. all elements of one array will be the keys of new array and all elements of the second array will be the values of this new array.
Syntax:
array_combine(array1, array2)
Where, array1 is the first array with keys and array2 is the second array with the values.
Example: PHP program to combine arrays.
PHP
<?php // Define array1 with keys $array1 = array("subject1" ,"subject2"); // Define array2 with values$array2 = array( "c/c++", "java"); // Combine two arrays$final = array_combine($array1, $array2); // Display merged arrayprint_r($final); ?>
Array
(
[subject1] => c/c++
[subject2] => java
)
Example 2:
PHP
<?php // Define array1 with keys $array1 = array("subject1", "subject2", "subject3", "subject4"); // Define array2 with values$array2 = array( "c/c++", "java", "Python", "HTML"); // Combine two arrays$final = array_combine($array1, $array2); // Display merged arrayprint_r($final); ?>
Array
(
[subject1] => c/c++
[subject2] => java
[subject3] => Python
[subject4] => HTML
)
Difference Between array_merge() and array_combine() Function:
array_merge() Function
array_combine() Function
PHP-function
PHP-Questions
Picked
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 25068,
"s": 25040,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 25569,
"s": 25068,
"text": "array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values o... |
Common operations on various Data Structures - GeeksforGeeks | 11 Apr, 2022
Data Structure is the way of storing data in computer’s memory so that it can be used easily and efficiently. There are different data-structures used for the storage of data. It can also be define as a mathematical or logical model of a particular organization of data items. The representation of particular data structure in the main memory of a computer is called as storage structure. For Examples: Array, Stack, Queue, Tree, Graph, etc.
Operations on different Data Structure: There are different types of operations that can be performed for the manipulation of data in every data structure. Some operations are explained and illustrated below:
Traversing: Traversing a Data Structure means to visit the element stored in it. This can be done with any type of DS. Below is the program to illustrate traversal in an array:
Array
Stack
Queue
LinkedList
// C++ program to traversal in an array#include <iostream>using namespace std; // Driver Codeint main(){ // Initialise array int arr[] = { 1, 2, 3, 4 }; // size of array int N = sizeof(arr) / sizeof(arr[0]); // Traverse the element of arr[] for (int i = 0; i < N; i++) { // Print the element cout << arr[i] << ' '; } return 0;}
// C++ program to traversal in an stack#include <bits/stdc++.h>using namespace std; // Function to print the element in stackvoid printStack(stack<int>& St){ // Traverse the stack while (!St.empty()) { // Print top element cout << St.top() << ' '; // Pop top element St.pop(); }} // Driver Codeint main(){ // Initialise stack stack<int> St; // Insert Element in stack St.push(4); St.push(3); St.push(2); St.push(1); // Print elements in stack printStack(St); return 0;}
// C++ program to traversal// in an queue#include <bits/stdc++.h>using namespace std; // Function to print the// element in queuevoid printQueue(queue<int>& Q){ // Traverse the stack while (!Q.empty()) { // Print top element cout << Q.front() << ' '; // Pop top element Q.pop(); }} // Driver Codeint main(){ // Initialise queue queue<int> Q; // Insert element Q.push(1); Q.push(2); Q.push(3); Q.push(4); // Print elements printQueue(Q); return 0;}
// C++ program to traverse the// given linked list#include <bits/stdc++.h>using namespace std;struct Node { int data; Node* next;}; // Function that allocates a new// node with given dataNode* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a new node// at the end of linked listNode* insertEnd(Node* head, int data){ // If linked list is empty, // Create a new node if (head == NULL) return newNode(data); // If we have not reached the end // Keep traversing recursively else head->next = insertEnd(head->next, data); return head;} /// Function to traverse given LLvoid traverse(Node* head){ if (head == NULL) return; // If head is not NULL, // print current node and // recur for remaining list cout << head->data << " "; traverse(head->next);} // Driver Codeint main(){ // Given Linked List Node* head = NULL; head = insertEnd(head, 1); head = insertEnd(head, 2); head = insertEnd(head, 3); head = insertEnd(head, 4); // Function Call to traverse LL traverse(head);}
1 2 3 4
Below is the program to illustrate traversal in an array in java:
Java
Python3
C#
Javascript
// Java program to traversal in an array import java.util.*; class GFG{ // Driver Codepublic static void main(String[] args){ // Initialise array int arr[] = { 1, 2, 3, 4 }; // size of array int N = arr.length; // Traverse the element of arr[] for (int i = 0; i < N; i++) { // Print the element System.out.print(arr[i] + " "); } }} // This code contributed by Rajput-Ji
# Python program to traversal in an array # Driver Codeif __name__ == '__main__': # Initialise array arr = [ 1, 2, 3, 4 ]; # size of array N = len(arr); # Traverse the element of arr for i in range(N): # Print element print(arr[i], end=" "); # This code is contributed by Rajput-Ji
// C# program to traversal in an array using System; public class GFG { // Driver Code public static void Main(String[] args) { // Initialise array int []arr = { 1, 2, 3, 4 }; // size of array int N = arr.Length; // Traverse the element of []arr for (int i = 0; i < N; i++) { // Print the element Console.Write(arr[i] + " "); } }} // This code contributed by Rajput-Ji
<script>// javascript program to traversal in an array // Driver Code // Initialise array var arr = [ 1, 2, 3, 4 ]; // size of array var N = arr.length; // Traverse the element of arr for (i = 0; i < N; i++) { // Print the element document.write(arr[i] + " "); } // This code is contributed by Rajput-Ji</script>
Below is the program to illustrate traversal in a Stack in java:
Java
C#
Javascript
// Java program to traversal in an stack import java.util.*; class GFG{ // Function to print the element in stackstatic void printStack(Stack<Integer> St){ // Traverse the stack while (!St.isEmpty()) { // Print top element System.out.print(St.peek() +" "); // Pop top element St.pop(); }} // Driver Codepublic static void main(String[] args){ // Initialise stack Stack<Integer> St = new Stack<>() ; // Insert Element in stack St.add(4); St.add(3); St.add(2); St.add(1); // Print elements in stack printStack(St);}} // This code contributed by Rajput-Ji
// C# program to traversal in an stackusing System;using System.Collections.Generic; public class GFG { // Function to print the element in stack static void printStack(Stack<int> St) { // Traverse the stack while (St.Count != 0) { // Print top element Console.Write(St.Peek() + " "); // Pop top element St.Pop(); } } // Driver Code public static void Main(String[] args) { // Initialise stack Stack<int> St = new Stack<int>(); // Insert Element in stack St.Push(4); St.Push(3); St.Push(2); St.Push(1); // Print elements in stack printStack(St); }} // This code is contributed by Rajput-Ji
<script>// javascript program to traversal in an stack // Function to print the element in stack function printStack(St) { // Traverse the stack while (St.length != 0) { // Print top element document.write(St.pop() + " "); } } // Driver Code // Initialise stack var St = []; // Insert Element in stack St.push(4); St.push(3); St.push(2); St.push(1); // Print elements in stack printStack(St); // This code is contributed by Rajput-Ji</script>
Searching: Searching means to find a particular element in the given data-structure. It is considered as successful when the required element is found. Searching is the operation which we can performed on data-structures like array, linked-list, tree, graph, etc.Below is the program to illustrate searching an element in an array:
Array
Stack
Queue
LinkedList
// C++ program to searching in an array#include <iostream>using namespace std; // Function that finds element K in the// arrayvoid findElement(int arr[], int N, int K){ // Traverse the element of arr[] // to find element K for (int i = 0; i < N; i++) { // If Element is present then // print the index and return if (arr[i] == K) { cout << "Element found!"; return; } } cout << "Element Not found!";} // Driver Codeint main(){ // Initialise array int arr[] = { 1, 2, 3, 4 }; // Element to be found int K = 3; // size of array int N = sizeof(arr) / sizeof(arr[0]); // Function Call findElement(arr, N, K); return 0;}
// C++ program to find element in stack#include <bits/stdc++.h>using namespace std; // Function to find element in stackvoid findElement(stack<int>& St, int K){ // Traverse the stack while (!St.empty()) { // Check if top is K if (St.top() == K) { cout << "Element found!"; return; } // Pop top element St.pop(); } cout << "Element Not found!";} // Driver Codeint main(){ // Initialise stack stack<int> St; // Insert Element in stack St.push(4); St.push(3); St.push(2); St.push(1); // Element to be found int K = 3; // Function Call findElement(St, K); return 0;}
// C++ program to find given element// in an queue#include <bits/stdc++.h>using namespace std; // Function to find element in queuevoid findElement(queue<int>& Q, int K){ // Traverse the stack while (!Q.empty()) { // Check if top is K if (Q.front() == K) { cout << "Element found!"; return; } // Pop top element Q.pop(); } cout << "Element Not found!";} // Driver Codeint main(){ // Initialise queue queue<int> Q; // Insert element Q.push(1); Q.push(2); Q.push(3); Q.push(4); // Element to be found int K = 3; // Print elements findElement(Q, K); return 0;}
// C++ program to traverse the// given linked list#include <bits/stdc++.h>using namespace std;struct Node { int data; Node* next;}; // Function that allocates a new// node with given dataNode* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a new node// at the end of linked listNode* insertEnd(Node* head, int data){ // If linked list is empty, // Create a new node if (head == NULL) return newNode(data); // If we have not reached the end // Keep traversing recursively else head->next = insertEnd(head->next, data); return head;} /// Function to traverse given LLbool traverse(Node* head, int K){ if (head == NULL) return false; // If node with value K is found // return true if (head->data == K) return true; return traverse(head->next, K);} // Driver Codeint main(){ // Given Linked List Node* head = NULL; head = insertEnd(head, 1); head = insertEnd(head, 2); head = insertEnd(head, 3); head = insertEnd(head, 4); // Element to be found int K = 3; // Function Call to traverse LL if (traverse(head, K)) { cout << "Element found!"; } else { cout << "Element Not found!"; }}
Element found!
Insertion: It is the operation which we apply on all the data-structures. Insertion means to add an element in the given data structure. The operation of insertion is successful when the required element is added to the required data-structure. It is unsuccessful in some cases when the size of the data structure is full and when there is no space in the data-structure to add any additional element. The insertion has the same name as an insertion in the data-structure as an array, linked-list, graph, tree. In stack, this operation is called Push. In the queue, this operation is called Enqueue.Below is the program to illustrate insertion in stack:
Array
Stack
Queue
LinkedList
// C++ program for insertion in array#include <iostream>using namespace std; // Function to print the array elementvoid printArray(int arr[], int N){ // Traverse the element of arr[] for (int i = 0; i < N; i++) { // Print the element cout << arr[i] << ' '; }} // Driver Codeint main(){ // Initialise array int arr[4]; // size of array int N = 4; // Insert elements in array for (int i = 1; i < 5; i++) { arr[i - 1] = i; } // Print array element printArray(arr, N); return 0;}
// C++ program for insertion in array#include <bits/stdc++.h>using namespace std; // Function to print the element in stackvoid printStack(stack<int>& St){ // Traverse the stack while (!St.empty()) { // Print top element cout << St.top() << ' '; // Pop top element St.pop(); }} // Driver Codeint main(){ // Initialise stack stack<int> St; // Insert Element in stack St.push(4); St.push(3); St.push(2); St.push(1); // Print elements in stack printStack(St); return 0;}
// C++ program for insertion in queue#include <bits/stdc++.h>using namespace std; // Function to print the// element in queuevoid printQueue(queue<int>& Q){ // Traverse the stack while (!Q.empty()) { // Print top element cout << Q.front() << ' '; // Pop top element Q.pop(); }} // Driver Codeint main(){ // Initialise queue queue<int> Q; // Insert element Q.push(1); Q.push(2); Q.push(3); Q.push(4); // Print elements printQueue(Q); return 0;}
// C++ program for insertion in LL#include <bits/stdc++.h>using namespace std;struct Node { int data; Node* next;}; // Function that allocates a new// node with given dataNode* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a new node// at the end of linked listNode* insertEnd(Node* head, int data){ // If linked list is empty, // Create a new node if (head == NULL) return newNode(data); // If we have not reached the end // Keep traversing recursively else head->next = insertEnd(head->next, data); return head;} /// Function to traverse given LLvoid traverse(Node* head){ if (head == NULL) return; // If head is not NULL, // print current node and // recur for remaining list cout << head->data << " "; traverse(head->next);} // Driver Codeint main(){ // Given Linked List Node* head = NULL; head = insertEnd(head, 1); head = insertEnd(head, 2); head = insertEnd(head, 3); head = insertEnd(head, 4); // Function Call to traverse LL traverse(head);}
1 2 3 4
Deletion: It is the operation which we apply on all the data-structures. Deletion means to delete an element in the given data structure. The operation of deletion is successful when the required element is deleted from the data structure. The deletion has the same name as a deletion in the data-structure as an array, linked-list, graph, tree, etc. In stack, this operation is called Pop. In Queue this operation is called Dequeue.Below is the program to illustrate dequeue in Queue:
Stack
Queue
LinkedList
// C++ program for insertion in array#include <bits/stdc++.h>using namespace std; // Function to print the element in stackvoid printStack(stack<int> St){ // Traverse the stack while (!St.empty()) { // Print top element cout << St.top() << ' '; // Pop top element St.pop(); }} // Driver Codeint main(){ // Initialise stack stack<int> St; // Insert Element in stack St.push(4); St.push(3); St.push(2); St.push(1); // Print elements before pop // operation on stack printStack(St); cout << endl; // Pop the top element St.pop(); // Print elements after pop // operation on stack printStack(St); return 0;}
// C++ program to illustrate dequeue// in queue#include <bits/stdc++.h>using namespace std; // Function to print the element// of the queuevoid printQueue(queue<int> myqueue){ // Traverse the queue and print // element at the front of queue while (!myqueue.empty()) { // Print the first element cout << myqueue.front() << ' '; // Dequeue the element from the // front of the queue myqueue.pop(); }} // Driver Codeint main(){ // Declare a queue queue<int> myqueue; // Insert element in queue from // 0 to 5 for (int i = 1; i < 5; i++) { // Insert element at the // front of the queue myqueue.push(i); } // Print element beforepop // from queue printQueue(myqueue); cout << endl; // Pop the front element myqueue.pop(); // Print element after pop // from queue printQueue(myqueue); return 0;}
// C++ program for insertion in LL#include <bits/stdc++.h>using namespace std;struct Node { int data; Node* next;}; // Function that allocates a new// node with given dataNode* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a new node// at the end of linked listNode* insertEnd(Node* head, int data){ // If linked list is empty, // Create a new node if (head == NULL) return newNode(data); // If we have not reached the end // Keep traversing recursively else head->next = insertEnd(head->next, data); return head;} /// Function to traverse given LLvoid traverse(Node* head){ if (head == NULL) return; // If head is not NULL, // print current node and // recur for remaining list cout << head->data << " "; traverse(head->next);} // Driver Codeint main(){ // Given Linked List Node* head = NULL; head = insertEnd(head, 1); head = insertEnd(head, 2); head = insertEnd(head, 3); head = insertEnd(head, 4); // Print before deleting the first // element from LL traverse(head); // Move head pointer to forward // to remove the first element // If LL has more than 1 element if (head->next != NULL) { head = head->next; } else { head = NULL; } cout << endl; // Print after deleting the first // element from LL traverse(head);}
1 2 3 4
2 3 4
sweetyty
Rajput-Ji
khushboogoyal499
sagartomar9927
arorakashish0911
Data Structures
Traversal
Arrays
Binary Search Tree
Data Structures
Graph
Hash
Heap
Linked List
Matrix
Queue
Searching
Sorting
Stack
Strings
Tree
Data Structures
Linked List
Arrays
Searching
Hash
Strings
Stack
Sorting
Matrix
Traversal
Graph
Queue
Binary Search Tree
Tree
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Binary Search Tree | Set 1 (Search and Insertion)
Binary Search Tree | Set 2 (Delete)
AVL Tree | Set 1 (Insertion)
A program to check if a binary tree is BST or not
Sorted Array to Balanced BST | [
{
"code": null,
"e": 24916,
"s": 24888,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 25359,
"s": 24916,
"text": "Data Structure is the way of storing data in computer’s memory so that it can be used easily and efficiently. There are different data-structures used for the stor... |
Find first repeating character using JavaScript | We have an array of string / number literals that may/may not contain repeating characters.
Our job is to write a function that takes in the array and returns the index of the first repeating
character. If the array contains no repeating characters, we should return -1.
So, let’s write the code for this function. We will iterate over the array using a for loop and use a
map to store distinct characters as key and their index as value, if during iteration we encounter
a repeating key we return its index otherwise at the end of the loop we return -1.
The code for this will be −
const arr = [12,4365,76,43,76,98,5,31,4];
const secondArr = [6,8,9,32,1,76,98,0,65,878,90];
const findRepeatingIndex = (arr) => {
const map = {};
for(let i = 0; i < arr.length; i++){
if(map[arr[i]]){
return map[arr[i]];
}else{
map[arr[i]] = i;
}
}
return -1;
};
console.log(findRepeatingIndex(arr));
console.log(findRepeatingIndex(secondArr));
The output in the console will be −
2
-1 | [
{
"code": null,
"e": 1333,
"s": 1062,
"text": "We have an array of string / number literals that may/may not contain repeating characters.\nOur job is to write a function that takes in the array and returns the index of the first repeating\ncharacter. If the array contains no repeating characters, w... |
Check if a given key exists in Java HashMap | Use the containsKey() method and check if a given key exists in the HashMap or not.
Let us first create HashMap and add some elements −
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Now, let’s say we need to check whether the key “Bag” exists or not, For that, use the containsKey() method like this −
hm.containsKey("Bag")
The following is an example to check if a given key exists in HashMap −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
// Get a set of the entries
Set set = hm.entrySet();
System.out.println("Elements in HashMap...");
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
System.out.println("Does Bag exist in the HashMap = "+hm.containsKey("Bag"));
}
}
Elements in HashMap...
Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000
Does Bag exist in the HashMap = true | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Use the containsKey() method and check if a given key exists in the HashMap or not."
},
{
"code": null,
"e": 1198,
"s": 1146,
"text": "Let us first create HashMap and add some elements −"
},
{
"code": null,
"e": 1455,
... |
How do we take password input in HTML forms? | To take password input in HTML form, use the <input> tag with type attribute as a password. This is also a single-line text input but it masks the character as soon as a user enters it.
You can try to run the following code to take password input in HTML forms −
Live Demo
<!DOCTYPE html>
<html>
<body>
<head>
<title>HTML Forms</title>
</head>
<p>Add your details:</p>
<form>
Student Username:<br> <input type="text" name="name">
<br>
Password:<br> <input type="password" name="password">
<br>
</form>
</body>
</html> | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "To take password input in HTML form, use the <input> tag with type attribute as a password. This is also a single-line text input but it masks the character as soon as a user enters it."
},
{
"code": null,
"e": 1325,
"s": 1248,
"text... |
What is evaluation order of function parameters in C? | We pass different arguments into some functions. Now one questions may come in our mind, that what the order of evaluation of the function parameters. Is it left to right, or right to left?
To check the evaluation order we will use a simple program. Here some parameters are passing. From the output we can find how they are evaluated.
#include<stdio.h>
void test_function(int x, int y, int z) {
printf("The value of x: %d\n", x);
printf("The value of y: %d\n", y);
printf("The value of z: %d\n", z);
}
main() {
int a = 10;
test_function(a++, a++, a++);
}
The value of x: 12
The value of y: 11
The value of z: 10
From this output we can easily understand the evaluation sequence. At first the z is taken, so it is holding 10, then y is taken, so it is 11, and finally x is taken. So the value is 12. | [
{
"code": null,
"e": 1252,
"s": 1062,
"text": "We pass different arguments into some functions. Now one questions may come in our mind, that what the order of evaluation of the function parameters. Is it left to right, or right to left?"
},
{
"code": null,
"e": 1398,
"s": 1252,
"... |
Employee Management System using doubly linked list in C - GeeksforGeeks | 12 Oct, 2021
Design and implement a menu-driven program in C for the below operations on DLL of employee data with fields: SSN, name, department, designation, Salary, Phone Number:
Create a DLL of N employee’s data by using end insertion.
Display the status of DLL and count the number of nodes in it.
Perform insertion and deletion at end of DLL.
Perform insertion and deletion at front of DLL.
Demonstrate how this DLL can be used as a double-ended queue.
Approach:
For storing the data of the employee, create a user define datatype which will store the information regarding Employee. Below is the declaration of the data type:
struct node {
struct node* prev;
int ssn;
long int phno;
float sal;
char name[20], dept[10], desg[20];
struct node* next;
}
Building the Employee’s table: For building the employee table the idea is to use the above struct datatype which will use to store the information regarding the employee and every new employee’s details will be added as a linked list node.
Deleting in the record: Since, a doubly-linked list is used to store the data, therefore to delete the data at any index just link the next to the next of the deleted data and link the previous node of the next data of the deleted node to its previous data.
Searching in the record: For searching in the record based on any parameter, the idea is to traverse the data and if at any index the value parameters match with the record stored, print all the information of that employee.
Below is the C-program to demonstrate employers details using a Doubly Linked List:
C
// C-program to demonstrate employer// details using a Doubly-linked list#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Global declarationint count = 0; // Structure declarationstruct node { struct node* prev; int ssn; long int phno; float sal; char name[20], dept[10], desg[20]; struct node* next;} * h, *temp, *temp1, *temp2, *temp4; // Function to create nodevoid create(){ int ssn; long int phno; float sal; char name[20], dept[10], desg[20]; temp = (struct node*)malloc(sizeof(struct node)); temp->prev = NULL; temp->next = NULL; printf("\n enter ssn, name, depart" "ment, designation, salary " "and phno of employee:\n"); scanf("%d %s %s %s %f %ld", &ssn, name, dept, desg, &sal, &phno); temp->ssn = ssn; strcpy(temp->name, name); strcpy(temp->dept, dept); strcpy(temp->desg, desg); temp->sal = sal; temp->phno = phno; count++;} // Function to insert at beginningvoid insertbeg(){ // If DLL is empty if (h == NULL) { create(); h = temp; temp1 = h; } // Else create a new node and // update the links else { create(); temp->next = h; h->prev = temp; h = temp; }} // Function to insert at endvoid insertend(){ // If DLL is empty if (h == NULL) { create(); h = temp; temp1 = h; } // Else create a new node and // update the links else { create(); temp1->next = temp; temp->prev = temp1; temp1 = temp; }} // Function to display from beginningvoid displaybeg(){ temp2 = h; if (temp2 == NULL) { printf("\n list is empty\n"); return; } printf("\n linked list elements " "from beginning:\n"); while (temp2 != NULL) { printf("%d %s %s %s %f %ld\n", temp2->ssn, temp2->name, temp2->dept, temp2->desg, temp2->sal, temp2->phno); temp2 = temp2->next; } // Print the count printf("number of employees=%d", count);} // Function to delete at endint deleteend(){ struct node* temp; temp = h; if (temp == NULL) { printf("list is empty\n"); return 0; } if (temp->next == NULL) { printf("%d %s %s %s %f %ld\n", temp->ssn, temp->name, temp->dept, temp->desg, temp->sal, temp->phno); free(temp); h = NULL; } else { temp = temp1; temp2 = temp1->prev; temp2->next = NULL; printf("%d %s %s %s %f %ld\n", temp->ssn, temp->name, temp->dept, temp->desg, temp->sal, temp->phno); free(temp); temp1 = temp2; } count--; return 0;} // Function to delete from beginningint deletebeg(){ struct node* temp; temp = h; if (temp == NULL) { printf("list is empty\n"); return 0; } if (temp->next == NULL) { printf("%d %s %s %s %f %ld\n", temp->ssn, temp->name, temp->dept, temp->desg, temp->sal, temp->phno); free(temp); h = NULL; } else { h = h->next; h->prev = NULL; printf("%d %s %s %s %f %ld\n", temp->ssn, temp->name, temp->dept, temp->desg, temp->sal, temp->phno); free(temp); } count--; return 0;} // Function displaying menusvoid employerDetails(){ int ch, n, i; h = NULL; temp = temp1 = NULL; printf("--------Menu------------\n"); printf("\n 1.create a DLL of n emp"); printf("\n 2.display from beginning"); printf("\n 3.insert at end"); printf("\n 4.delete at end"); printf("\n 5.insert at beginning"); printf("\n 6.delete at beginning"); printf("\n 7.to show DLL as queue"); printf("\n 8.exit\n"); printf("----------------------\n"); while (1) { printf("\n enter choice : "); scanf("%d", &ch); // Switch statements begins switch (ch) { case 1: printf("\n enter number of" " employees:"); scanf("%d", &n); for (i = 0; i < n; i++) insertend(); break; case 2: displaybeg(); break; case 3: insertend(); break; case 4: deleteend(); break; case 5: insertbeg(); break; case 6: deletebeg(); break; case 7: printf( "\n to show DLL as queue" " \n1.perform insert and" " deletion operation by " "calling insertbeg() and " "deleteend() respectively\n " "\t OR \n 2.perform insert " "and delete operations by "calling insertend() and " "deletebeg() respectively\n"); break; case 8: exit(0); default: printf("wrong choice\n"); } }} // Driver Codeint main(){ // Function Call employerDetails(); return 0;}
Output:
Explanation:
create():The create() function creates a doubly linked list node using dynamic memory allocation i.e., using malloc() function. Data inserted into it such as name, dept, designation, salary, Phno. into temp node.
insertbeg(): This function is used for inserting the node at the beginning of the doubly linked list. In this function, if h==NULL means the list is completely empty so need to create a new node. Otherwise, create a node and insert it at the beginning. Then make this node a new temp node.
insertend(): This function is used for inserting the node at the end of the doubly linked list. In this function, if h==NULL means the list is completely empty so need to create a new node. Otherwise, insert this temp after the temp1 node, lastly assign temp as temp1 for future use.
displaybeg(): This function is used for displaying the elements of the list from the beginning. It also helps to know the number of employees.
deleteend(): This function is useful for deleting the node from the end. Since memory is allocated dynamically for the node, need to explicitly write the function to free the node that is done by using free(temp).
deletebeg(): This function is useful for deleting the node from the beginning Since the memory is allocated dynamically for the node, need to explicitly write the function to free the node that is done by using free(temp).
main(): This is the main function that drives the whole program. It uses switch statements to operate all the functions which are required to run a successful program.
surinderdawra388
C Language
C Programs
Data Structures
Project
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses | [
{
"code": null,
"e": 23895,
"s": 23867,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 24063,
"s": 23895,
"text": "Design and implement a menu-driven program in C for the below operations on DLL of employee data with fields: SSN, name, department, designation, Salary, Phone Num... |
How to Save Output of Command in a File in Linux? - GeeksforGeeks | 17 Mar, 2021
When we run a command on a terminal on Linux it generates some output of that command. Sometimes we need the output result of the commands. Today we are going to see how to save the output of the command.
We can use the redirections operators to save the output of commands into files. Redirection operators redirect the output of a command to the file instead of the output terminal.
There are two main redirection operators in Linux:
>
>>
Example 1:
The first operator is “>” which is used to redirect the output of a command to the file, but this operator erases all existing data in that file and overwrites the command output,
Let’s see one example of > redirection operator:
In the above image, we can see that the previous content of the output.txt file gets erased and the output of the ls command is written into the file.
Example 2:
Now let’s see about the second redirection operator is >>. Using this operator we can append the output of the command to the file. It does not erase any previous content of the file.
Let’s see the example of >> operator
In the above image, we can see that the output of the command is appended to the output.txt file without erasing the content stored in that file.
If the file mentioned after the Redirection operator in not exist then it will create automatically.
When we use the redirection operator the output is going to the file only the redirection operator does not print it on the terminal. To see the output on the terminal and also save it into the file we can use the tee command. It sends the output of the file as well as to the terminal.
First, let’s see how to use the tee operator using the pipeline. Following is the syntax of using the tee operator:
command | tee outfile.txt
Now let’s see one example of the tee command:
We can see in the above image the output is redirected to the terminal as well as the output.txt file.
To append the output of the command to the file use the –a option with the tee command. Here is the syntax of the command:
command | tee outfile.txt
Now Let’s see one example of this command
In this image, we can see that the output of cowsay command is stored in the output.txt file without erasing the existing data of the file.
linux-command
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Selenium on MacOS?
How to Set Java Path in Windows and Linux?
How to Create and Setup Spring Boot Project in Eclipse IDE?
AWK command in Unix/Linux with examples
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24944,
"s": 24913,
"text": " \n17 Mar, 2021\n"
},
{
"code": null,
"e": 25149,
"s": 24944,
"text": "When we run a command on a terminal on Linux it generates some output of that command. Sometimes we need the output result of the commands. Today we are going t... |
How to Install Lightgbm on Windows? - GeeksforGeeks | 26 Oct, 2021
In this article, we will learn how to install Lightgbm in Python on Windows .
LightGBM is a gradient boosting framework that uses tree based learning algorithms. It is designed to be distributed and efficient with the following advantages:
Faster training speed and higher efficiency.
Lower memory usage.
Better accuracy.
Support of parallel, distributed, and GPU learning.
Capable of handling large-scale data.
Follow the below steps to install the Lightgbm package on Windows using pip:
Step 1: Install the latest Python3 in Windows
Step 2: Check if pip and python are correctly installed.
python --version
pip --version
Step 3: Upgrade your pip to avoid errors during installation.
pip install --upgrade pip
Step 4: Enter the following command to install Lightgbm using pip.
pip install lightgbm
Follow the below steps to install the Lightgbm on Windows using the setup.py file:
Step 1: Download the latest source package of Lightgbm for python3 from here.
curl https://files.pythonhosted.org/packages/fe/a2/cf319c151fe2cd863c57bca972c837ea5bf2aa01fd2313aa39ee478a46e5/lightgbm-3.3.0.tar.gz > lightgbm-3.3.0.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf lightgbm-3.3.0.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
cd lightgbm-3.3.0
python setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import lightgbm
If there is any error while importing the module then is not installed properly.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS? | [
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 24639,
"s": 24561,
"text": "In this article, we will learn how to install Lightgbm in Python on Windows ."
},
{
"code": null,
"e": 24801,
"s": 24639,
"text": "LightGBM is ... |
Print a String in wave pattern in C++ | In this problem, we are given a string and an integer n. Our task is to print the given string in a wave pattern of n lines.
Let’s take an example to understand the problem,
Input: Tutorial n = 3
Output:
T r
U o i s
t l
Wave patterns are printed by printing each character of the string one by one in the next line and tab space away from the next element till the nth line. And the printing tab spaces to the upper line till the first line and follow the same pattern until the string has characters.
The below code gives the implementation of our solution,
Live Demo
#include<bits/stdc++.h>
using namespace std;
void printWavePattern(string s, int n) {
if (n==1) {
cout<<s;
return;
}
int len=s.length();
char a[len][len]={ };
int row=0;
bool down;
for (int i=0; i<len; i++) {
a[row][i]=s[i];
if (row==n-1)
down=false;
else if (row==0)
down=true;
(down)?(row++):(row--);
}
for (int i=0; i<n; i++) {
for (int j=0; j<len; j++) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
int main() {
string str = "TutorialsPoint";
int n = 4;
cout<<n<<" Line wave pattern '"<<str<<"' is:\n";
printWavePattern(str, n);
}
4 Line wave pattern 'TutorialsPoint' is −
T a n
u i l i t
t r s o
o P | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "In this problem, we are given a string and an integer n. Our task is to print the given string in a wave pattern of n lines."
},
{
"code": null,
"e": 1236,
"s": 1187,
"text": "Let’s take an example to understand the problem,"
},
... |
How to Get First Row of Pandas DataFrame? - GeeksforGeeks | 30 Nov, 2021
In this article, we will discuss how to get the first row of the pandas dataframe
This method is used to access the row by using row numbers. We can get the first row by using 0 indexes.
Syntax:
dataframe.iloc[0]
where dataframe is the input dataframe
we can also provide the range index.
Syntax:
dataframe.iloc[:1]
Here the rows will be extracted from the start till the index -1 mentioned after the right side of :.
Example: Python code to get the first row of the dataframe by using iloc[] function
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using row positionprint(data.iloc[0]) print("---------------") # get first row using slice operatorprint(data.iloc[:1])
Output:
id 7058
name sravan
subjects java
Name: 0, dtype: object
---------------
id name subjects
0 7058 sravan java
Example 2: Get the first row for a particular column
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using row positionprint(data['name'].iloc[0]) print("---------------") # get first row using slice operatorprint(data['subjects'].iloc[:1])
Output:
sravan
---------------
0 java
Name: subjects, dtype: object
This function will default return the first 5 rows of the dataframe. to get only first row we have to specify 1
Syntax:
dataframe.head(1)
Example 1: Program to get the first row of the dataset
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using head() functionprint(data.head(1))
Output:
id name subjects
0 7058 sravan java
Example 2: Get the first row for a particular column
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using head() functionprint(data['id'].head(1))
Output:
0 7058
Name: id, dtype: int64
This method is used to get the first row with index function.
Syntax:
dataframe.loc[dataframe.index[0]]
where,
dataframe is the input dataframe
index is the function to get first row
Example: Program to get the first row of the dataset
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using loc() functiondata.loc[data.index[0]]
Output:
id 7058
name sravan
subjects java
Name: 0, dtype: object
This will return the first row in the form of an array. Works similar to iloc().
Syntax:
dataframe.values[0]
dataframe.values[:1]
Example: Program to get first row of the dataset
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using loc() functionprint(data.values[:1]) # get first row using loc() functionprint(data.values[:1]) # get particular columnprint(data['name'].values[:1])
Output:
[[7058 'sravan' 'java']]
[[7058 'sravan' 'java']]
['sravan']
This function takes row and column index to display data in the dataframe
Syntax:
dataframe.iat[row_index, column_index]
where
dataframe is the input dataframe
row_index is the row number
column_index is the column number
Example: Program to get the first row of the dataset
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using iat() function of# first row 2 nd columnprint(data.iat[0, 1]) # get first row using iat() function of# first row 1 st columnprint(data.iat[0, 0]) # get first row using iat() function of# first row 3 rd columnprint(data.iat[0, 2])
Output:
sravan
7058
java
This function takes column names along with a first-row index to display the first row of the dataframe.
Syntax:
dataframe.at[row_index, column_name]
where
dataframe is the input dataframe
row_index – 0 to get the first row
column_name is the name of the column
Example: Program to get the first row of the dataset
Python3
# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # get first row using iat() function of# first row 2 nd columnprint(data.at[0, 'name']) # get first row using iat() function of# first row 1 st columnprint(data.at[0, 'id']) # get first row using iat() function of# first row 3 rd columnprint(data.at[0, 'subjects'])
Output:
sravan
7058
java
kapoorsagar226
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
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
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 23983,
"s": 23901,
"text": "In this article, we will discuss how to get the first row of the pandas dataframe"
},
{
"code": null,
"e": 24088,
"s": 23983,
"text": "This met... |
Count of submatrix with sum X in a given Matrix - GeeksforGeeks | 05 May, 2021
Given a matrix of size N x M and an integer X, the task is to find the number of sub-squares in the matrix with sum of elements equal to X.Examples:
Input: N = 4, M = 5, X = 10, arr[][]={{2, 4, 3, 2, 10}, {3, 1, 1, 1, 5}, {1, 1, 2, 1, 4}, {2, 1, 1, 1, 3}} Output: 3 Explanation: {10}, {{2, 4}, {3, 1}} and {{1, 1, 1}, {1, 2, 1}, {1, 1, 1}} are subsquares with sum 10.Input: N = 3, M = 4, X = 8, arr[][]={{3, 1, 5, 3}, {2, 2, 2, 6}, {1, 2, 2, 4}} Output: 2 Explanation: Sub-squares {{2, 2}, {2, 2}} and {{3, 1}, {2, 2}} have sum 8.
Naive Approach: The simplest approach to solve the problem is to generate all possible sub-squares and check sum of all the elements of the sub-square equals to X.Time Complexity: O(N3 * M3) Auxiliary Space: O(1)Efficient Approach: To optimize the above naive approach the sum of all the element of all the matrix till each cell has to be made. Below are the steps:
Precalculate the sum of all rectangles with its upper left corner at (0, 0) and lower right at (i, j) in O(N * M) computational complexity.
Now, it can be observed that, for every upper left corner, there can be at most one square with sum X since elements of the matrix are positive.
Keeping this in mind we can use binary search to check if there exists a square with sum X.
For every cell (i, j) in the matrix, fix it as the upper left corner of the subsquare. Then, traverse over all possible subsquares with (i, j) as the upper left corner and increase count if sum is equal to X or not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Size of a column#define m 5 // Function to find the count of submatrix// whose sum is Xint countSubsquare(int arr[][m], int n, int X){ int dp[n + 1][m + 1]; memset(dp, 0, sizeof(dp)); // Copying arr to dp and making // it indexed 1 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i + 1][j + 1] = arr[i][j]; } } // Precalculate and store the sum // of all rectangles with upper // left corner at (0, 0); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // Calculating sum in // a 2d grid dp[i][j] += dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; } } // Stores the answer int cnt = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // Fix upper left corner // at {i, j} and perform // binary search on all // such possible squares // Minimum length of square int lo = 1; // Maximum length of square int hi = min(n - i, m - j) + 1; // Flag to set if sub-square // with sum X is found bool found = false; while (lo <= hi) { int mid = (lo + hi) / 2; // Calculate lower // right index if upper // right corner is at {i, j} int ni = i + mid - 1; int nj = j + mid - 1; // Calculate the sum of // elements in the submatrix // with upper left column // {i, j} and lower right // column at {ni, nj}; int sum = dp[ni][nj] - dp[ni][j - 1] - dp[i - 1][nj] + dp[i - 1][j - 1]; if (sum >= X) { // If sum X is found if (sum == X) { found = true; } hi = mid - 1; // If sum > X, then size of // the square with sum X // must be less than mid } else { // If sum < X, then size of // the square with sum X // must be greater than mid lo = mid + 1; } } // If found, increment // count by 1; if (found == true) { cnt++; } } } return cnt;} // Driver Codeint main(){ int N = 4, X = 10; // Given Matrix arr[][] int arr[N][m] = { { 2, 4, 3, 2, 10 }, { 3, 1, 1, 1, 5 }, { 1, 1, 2, 1, 4 }, { 2, 1, 1, 1, 3 } }; // Function Call cout << countSubsquare(arr, N, X) << endl; return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Size of a columnstatic final int m = 5; // Function to find the count of submatrix// whose sum is Xstatic int countSubsquare(int arr[][], int n, int X){ int [][]dp = new int[n + 1][m + 1]; // Copying arr to dp and making // it indexed 1 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i + 1][j + 1] = arr[i][j]; } } // Precalculate and store the sum // of all rectangles with upper // left corner at (0, 0); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // Calculating sum in // a 2d grid dp[i][j] += dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; } } // Stores the answer int cnt = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // Fix upper left corner // at {i, j} and perform // binary search on all // such possible squares // Minimum length of square int lo = 1; // Maximum length of square int hi = Math.min(n - i, m - j) + 1; // Flag to set if sub-square // with sum X is found boolean found = false; while (lo <= hi) { int mid = (lo + hi) / 2; // Calculate lower // right index if upper // right corner is at {i, j} int ni = i + mid - 1; int nj = j + mid - 1; // Calculate the sum of // elements in the submatrix // with upper left column // {i, j} and lower right // column at {ni, nj}; int sum = dp[ni][nj] - dp[ni][j - 1] - dp[i - 1][nj] + dp[i - 1][j - 1]; if (sum >= X) { // If sum X is found if (sum == X) { found = true; } hi = mid - 1; // If sum > X, then size of // the square with sum X // must be less than mid } else { // If sum < X, then size of // the square with sum X // must be greater than mid lo = mid + 1; } } // If found, increment // count by 1; if (found == true) { cnt++; } } } return cnt;} // Driver Codepublic static void main(String[] args){ int N = 4, X = 10; // Given Matrix arr[][] int arr[][] = { { 2, 4, 3, 2, 10 }, { 3, 1, 1, 1, 5 }, { 1, 1, 2, 1, 4 }, { 2, 1, 1, 1, 3 } }; // Function Call System.out.print(countSubsquare(arr, N, X) + "\n");}} // This code is contributed by sapnasingh4991
# Python3 program for the above approach # Size of a columnm = 5 # Function to find the count of# submatrix whose sum is Xdef countSubsquare(arr, n, X): dp = [[ 0 for x in range(m + 1)] for y in range(n + 1)] # Copying arr to dp and making # it indexed 1 for i in range(n): for j in range(m): dp[i + 1][j + 1] = arr[i][j] # Precalculate and store the sum # of all rectangles with upper # left corner at (0, 0); for i in range(1, n + 1): for j in range(1, m + 1): # Calculating sum in # a 2d grid dp[i][j] += (dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]) # Stores the answer cnt = 0 for i in range(1, n + 1): for j in range(1, m + 1): # Fix upper left corner # at {i, j} and perform # binary search on all # such possible squares # Minimum length of square lo = 1 # Maximum length of square hi = min(n - i, m - j) + 1 # Flag to set if sub-square # with sum X is found found = False while (lo <= hi): mid = (lo + hi) // 2 # Calculate lower right # index if upper right # corner is at {i, j} ni = i + mid - 1 nj = j + mid - 1 # Calculate the sum of # elements in the submatrix # with upper left column # {i, j} and lower right # column at {ni, nj}; sum = (dp[ni][nj] - dp[ni][j - 1] - dp[i - 1][nj] + dp[i - 1][j - 1]) if (sum >= X): # If sum X is found if (sum == X): found = True hi = mid - 1 # If sum > X, then size of # the square with sum X # must be less than mid else: # If sum < X, then size of # the square with sum X # must be greater than mid lo = mid + 1 # If found, increment # count by 1; if (found == True): cnt += 1 return cnt # Driver Codeif __name__ =="__main__": N, X = 4, 10 # Given matrix arr[][] arr = [ [ 2, 4, 3, 2, 10 ], [ 3, 1, 1, 1, 5 ], [ 1, 1, 2, 1, 4 ], [ 2, 1, 1, 1, 3 ] ] # Function call print(countSubsquare(arr, N, X)) # This code is contributed by chitranayal
// C# program for the above approachusing System; class GFG{ // Size of a columnstatic readonly int m = 5; // Function to find the count of submatrix// whose sum is Xstatic int countSubsquare(int [,]arr, int n, int X){ int [,]dp = new int[n + 1, m + 1]; // Copying arr to dp and making // it indexed 1 for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { dp[i + 1, j + 1] = arr[i, j]; } } // Precalculate and store the sum // of all rectangles with upper // left corner at (0, 0); for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { // Calculating sum in // a 2d grid dp[i, j] += dp[i - 1, j] + dp[i, j - 1] - dp[i - 1, j - 1]; } } // Stores the answer int cnt = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { // Fix upper left corner // at {i, j} and perform // binary search on all // such possible squares // Minimum length of square int lo = 1; // Maximum length of square int hi = Math.Min(n - i, m - j) + 1; // Flag to set if sub-square // with sum X is found bool found = false; while (lo <= hi) { int mid = (lo + hi) / 2; // Calculate lower // right index if upper // right corner is at {i, j} int ni = i + mid - 1; int nj = j + mid - 1; // Calculate the sum of // elements in the submatrix // with upper left column // {i, j} and lower right // column at {ni, nj}; int sum = dp[ni, nj] - dp[ni, j - 1] - dp[i - 1, nj] + dp[i - 1, j - 1]; if (sum >= X) { // If sum X is found if (sum == X) { found = true; } hi = mid - 1; // If sum > X, then size of // the square with sum X // must be less than mid } else { // If sum < X, then size of // the square with sum X // must be greater than mid lo = mid + 1; } } // If found, increment // count by 1; if (found == true) { cnt++; } } } return cnt;} // Driver Codepublic static void Main(String[] args){ int N = 4, X = 10; // Given Matrix [,]arr int [,]arr = { { 2, 4, 3, 2, 10 }, { 3, 1, 1, 1, 5 }, { 1, 1, 2, 1, 4 }, { 2, 1, 1, 1, 3 } }; // Function call Console.Write(countSubsquare(arr, N, X) + "\n");}} // This code is contributed by amal kumar choubey
<script> // Javascript program for the above approach // Size of a column var m = 5; // Function to find the count of submatrix // whose sum is X function countSubsquare(arr , n , X) { var dp = Array(n + 1); for(var i =0;i<n+1;i++) dp[i] = Array(m + 1).fill(0); // Copying arr to dp and making // it indexed 1 for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { dp[i + 1][j + 1] = arr[i][j]; } } // Precalculate and store the sum // of all rectangles with upper // left corner at (0, 0); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Calculating sum in // a 2d grid dp[i][j] += dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; } } // Stores the answer var cnt = 0; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Fix upper left corner // at {i, j} and perform // binary search on all // such possible squares // Minimum length of square var lo = 1; // Maximum length of square var hi = Math.min(n - i, m - j) + 1; // Flag to set if sub-square // with sum X is found var found = false; while (lo <= hi) { var mid = parseInt((lo + hi) / 2); // Calculate lower // right index if upper // right corner is at {i, j} var ni = i + mid - 1; var nj = j + mid - 1; // Calculate the sum of // elements in the submatrix // with upper left column // {i, j} and lower right // column at {ni, nj]; var sum = dp[ni][nj] - dp[ni][j - 1] - dp[i - 1][nj] + dp[i - 1][j - 1]; if (sum >= X) { // If sum X is found if (sum == X) { found = true; } hi = mid - 1; // If sum > X, then size of // the square with sum X // must be less than mid } else { // If sum < X, then size of // the square with sum X // must be greater than mid lo = mid + 1; } } // If found, increment // count by 1; if (found == true) { cnt++; } } } return cnt; } // Driver Code var N = 4, X = 10; // Given Matrix arr var arr = [ [ 2, 4, 3, 2, 10 ], [ 3, 1, 1, 1, 5 ], [ 1, 1, 2, 1, 4 ], [ 2, 1, 1, 1, 3 ] ]; // Function Call document.write(countSubsquare(arr, N, X) + "<br/>"); // This code contributed by umadevi9616 </script>
3
Time Complexity: O(N * M * log(max(N, M))) Auxiliary Space: O(N * M)
ukasp
sapnasingh4991
Amal Kumar Choubey
umadevi9616
prefix-sum
submatrix
Competitive Programming
Dynamic Programming
Mathematical
Matrix
Searching
prefix-sum
Searching
Dynamic Programming
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bits manipulation (Important tactics)
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Formatted output in Java
Breadth First Traversal ( BFS ) on a 2D array
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 24996,
"s": 24968,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25147,
"s": 24996,
"text": "Given a matrix of size N x M and an integer X, the task is to find the number of sub-squares in the matrix with sum of elements equal to X.Examples: "
},
{
... |
Gulp - Watch | The Watch method is used to monitor your source files. When any changes to the source file is made, the watch will run an appropriate task. You can use the ‘default’ task to watch for changes to HTML, CSS, and JavaScript files.
In the previous chapter you have learnt how to gulp combining tasks using default task. We used gulp-minify-css, gulp-autoprefixer and gulp-concatplugins, and created styles task to minify CSS files.
To watch CSS file, we need to update the ‘default’ task as shown in the following code:
gulp.task('default', ['styles'], function() {
// watch for CSS changes
gulp.watch('src/styles/*.css', function() {
// run styles upon changes
gulp.run('styles');
});
});
All the CSS files under work/src/styles/ folder will be watched and upon changes made to these files, the styles task will be executed.
Run the ‘default’ task using the following command.
gulp
After executing the above command, you will receive the following output.
C:\work>gulp
[17:11:28] Using gulpfile C:\work\gulpfile.js
[17:11:28] Starting 'styles'...
[17:11:28] Finished 'styles' after 22 ms
[17:11:28] Starting 'default'...
[17:11:28] Finished 'default' after 21 ms
Whenever any changes are made to CSS files, you will receive the following output.
C:\work>gulp
[17:11:28] Using gulpfile C:\work\gulpfile.js
[17:11:28] Starting 'styles'...
[17:11:28] Finished 'styles' after 22 ms
[17:11:28] Starting 'default'...
[17:11:28] Finished 'default' after 21 ms
gulp.run() has been deprecated. Use task dependencies or gulp.watch task
triggering instead.
[17:18:46] Starting 'styles'...
[17:18:46] Finished 'styles' after 5.1 ms
The Watch process will remain active and respond to your changes. You can press Ctrl+Cto terminate the monitoring process and return to the command line.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2044,
"s": 1816,
"text": "The Watch method is used to monitor your source files. When any changes to the source file is made, the watch will run an appropriate task. You can use the ‘default’ task to watch for changes to HTML, CSS, and JavaScript files."
},
{
"code": nul... |
Java Program to find all angles of a triangle | To find the angles of a triangle we can use sin/cosine rules according to cosine rule −
cos A = (b^2 + c^2 - a^2)/2bc
where A, B , C are the vertices and a, b, c are the sides of the given triangle then, angles of the triangle when the sides a, b, c given are −
angleAtA = acos((b^2 + c^2 - a^2)/(2bc))
angleAtB = acos((a^2 + c^2 - b^2)/(2ac))
angleAtC = acos((a^2 + b^2 - c^2)/(2ab)) | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To find the angles of a triangle we can use sin/cosine rules according to cosine rule −"
},
{
"code": null,
"e": 1180,
"s": 1150,
"text": "cos A = (b^2 + c^2 - a^2)/2bc"
},
{
"code": null,
"e": 1324,
"s": 1180,
"t... |
C++ Bidirectional Iterators | The iterators that have the privilege to access the sequence of elements of a range from both the directions that are from the end and from the beginning are known as bidirectional iterators. iterators can work on data types like list map and sets.
Bidirectional iterators have the same properties as forwarding iterators, with the only difference that they can also be decremented −
Where X is a bidirectional iterator, a and b are objects of this iterator type, and t is an object of the type pointed by the iterator type (or some other type that can be assigned to the lvalue returned by dereferencing an object of type X).
The concept of Bidirectional iterators in C++.
The bidirectional iterators support all of the features of forwarding iterators, and also prefix and postfix decrement operators.
The bidirectional iterators support all of the features of forwarding iterators, and also prefix and postfix decrement operators.
This type of iterator can access elements in both directions, like towards the end and towards the beginning.
This type of iterator can access elements in both directions, like towards the end and towards the beginning.
The random access iterator is also a type of bidirectional iterator.
The random access iterator is also a type of bidirectional iterator.
Bidirectional iterators have features of forwarding iterator, but the only difference is this iterator can also be decremented.
Bidirectional iterators have features of forwarding iterator, but the only difference is this iterator can also be decremented.
Input: 1 2 3 4 5 6 7 8 9 10
Output: 10 9 8 7 6 5 4 3 2 1
#include <iostream>
#include<iterator>
#include<vector>
using namespace std;
int main() {
vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> ::iterator it;
vector<int> :: reverse_iterator rev_it;
for(it = vec.begin(); it != vec.end(); it++)
cout<<*it<<" ";
cout<< endl;
for(rev_it = vec.rbegin(); rev_it!= vec.rend(); rev_it++)
cout<<*rev_it<<" ";
}
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1 | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "The iterators that have the privilege to access the sequence of elements of a range from both the directions that are from the end and from the beginning are known as bidirectional iterators. iterators can work on data types like list map and sets."
}... |
IMS DB - Control Blocks | IMS Control Blocks define the structure of the IMS database and a program's access to them. The following diagram shows the structure of IMS control blocks.
DL/I uses the following three types of Control Blocks −
Database Descriptor (DBD)
Program Specification Block (PSB)
Access Control Block (ACB)
Points to note −
DBD describes the complete physical structure of the database once all the segments have been defined.
DBD describes the complete physical structure of the database once all the segments have been defined.
While installing a DL/I database, one DBD must be created as it is required to access the IMS database.
While installing a DL/I database, one DBD must be created as it is required to access the IMS database.
Applications can use different views of the DBD. They are called Application Data Structures and they are specified in the Program Specification Block.
Applications can use different views of the DBD. They are called Application Data Structures and they are specified in the Program Specification Block.
The Database Administrator creates a DBD by coding DBDGEN control statements.
The Database Administrator creates a DBD by coding DBDGEN control statements.
DBDGEN is a Database Descriptor Generator. Creating control blocks is the responsibility of the Database Administrator. All the load modules are stored in the IMS library. Assembly Language macro statements are used to create control blocks. Given below is a sample code that shows how to create a DBD using DBDGEN control statements −
PRINT NOGEN
DBD NAME=LIBRARY,ACCESS=HIDAM
DATASET DD1=LIB,DEVICE=3380
SEGM NAME=LIBSEG,PARENT=0,BYTES=10
FIELD NAME=(LIBRARY,SEQ,U),BYTES=10,START=1,TYPE=C
SEGM NAME=BOOKSEG,PARENT=LIBSEG,BYTES=5
FIELD NAME=(BOOKS,SEQ,U),BYTES=10,START=1,TYPE=C
SEGM NAME=MAGSEG,PARENT=LIBSEG,BYTES=9
FIELD NAME=(MAGZINES,SEQ),BYTES=8,START=1,TYPE=C
DBDGEN
FINISH
END
Let us understand the terms used in the above DBDGEN −
When you execute the above control statements in JCL, it creates a physical structure where LIBRARY is the root segment, and BOOKS and MAGZINES are its child segments.
When you execute the above control statements in JCL, it creates a physical structure where LIBRARY is the root segment, and BOOKS and MAGZINES are its child segments.
The first DBD macro statement identifies the database. Here, we need to mention the NAME and ACCESS which is used by DL/I to access this database.
The first DBD macro statement identifies the database. Here, we need to mention the NAME and ACCESS which is used by DL/I to access this database.
The second DATASET macro statement identifies the file that contains the database.
The second DATASET macro statement identifies the file that contains the database.
The segment types are defined using the SEGM macro statement. We need to specify the PARENT of that segment. If it is a Root segment, then mention PARENT=0.
The segment types are defined using the SEGM macro statement. We need to specify the PARENT of that segment. If it is a Root segment, then mention PARENT=0.
The following table shows parameters used in FIELD macro statement −
Name
Name of the field, typically 1 to 8 characters long
Bytes
Length of the field
Start
Position of field within segment
Type
Data type of the field
Type C
Character data type
Type P
Packed decimal data type
Type Z
Zoned decimal data type
Type X
Hexadecimal data type
Type H
Half word binary data type
Type F
Full word binary data type
The fundamentals of PSB are as given below −
A database has a single physical structure defined by a DBD but the application programs that process it can have different views of the database. These views are called application data structure and are defined in the PSB.
A database has a single physical structure defined by a DBD but the application programs that process it can have different views of the database. These views are called application data structure and are defined in the PSB.
No program can use more than one PSB in a single execution.
No program can use more than one PSB in a single execution.
Application programs have their own PSB and it is common for application programs that have similar database processing requirements to share a PSB.
Application programs have their own PSB and it is common for application programs that have similar database processing requirements to share a PSB.
PSB consists of one or more control blocks called Program Communication Blocks (PCBs). The PSB contains one PCB for each DL/I database the application program will access. We will discuss more about PCBs in the upcoming modules.
PSB consists of one or more control blocks called Program Communication Blocks (PCBs). The PSB contains one PCB for each DL/I database the application program will access. We will discuss more about PCBs in the upcoming modules.
PSBGEN must be performed to create a PSB for the program.
PSBGEN must be performed to create a PSB for the program.
PSBGEN is known as Program Specification Block Generator. The following example creates a PSB using PSBGEN −
PRINT NOGEN
PCB TYPE=DB,DBDNAME=LIBRARY,KEYLEN=10,PROCOPT=LS
SENSEG NAME=LIBSEG
SENSEG NAME=BOOKSEG,PARENT=LIBSEG
SENSEG NAME=MAGSEG,PARENT=LIBSEG
PSBGEN PSBNAME=LIBPSB,LANG=COBOL
END
Let us understand the terms used in the above DBDGEN −
The first macro statement is the Program Communication Block (PCB) that describes the database Type, Name, Key-Length, and Processing Option.
The first macro statement is the Program Communication Block (PCB) that describes the database Type, Name, Key-Length, and Processing Option.
DBDNAME parameter on the PCB macro specifies the name of the DBD. KEYLEN specifies the length of the longest concatenated key. The program can process in the database. PROCOPT parameter specifies the program's processing options. For example, LS means only LOAD Operations.
DBDNAME parameter on the PCB macro specifies the name of the DBD. KEYLEN specifies the length of the longest concatenated key. The program can process in the database. PROCOPT parameter specifies the program's processing options. For example, LS means only LOAD Operations.
SENSEG is known as Segment Level Sensitivity. It defines the program's access to parts of the database and it is identified at the segment level. The program has access to all the fields within the segments to which it is sensitive. A program can also have field-level sensitivity. In this, we define a segment name and the parent name of the segment.
SENSEG is known as Segment Level Sensitivity. It defines the program's access to parts of the database and it is identified at the segment level. The program has access to all the fields within the segments to which it is sensitive. A program can also have field-level sensitivity. In this, we define a segment name and the parent name of the segment.
The last macro statement is PCBGEN. PSBGEN is the last statement telling there are no more statements to process. PSBNAME defines the name given to the output PSB module. The LANG parameter specifies the language in which the application program is written, e.g., COBOL.
The last macro statement is PCBGEN. PSBGEN is the last statement telling there are no more statements to process. PSBNAME defines the name given to the output PSB module. The LANG parameter specifies the language in which the application program is written, e.g., COBOL.
Listed below are the points to note about access control blocks −
Access Control Blocks for an application program combines the Database Descriptor and the Program Specification Block into an executable form.
Access Control Blocks for an application program combines the Database Descriptor and the Program Specification Block into an executable form.
ACBGEN is known as Access Control Blocks Generator. It is used to generate ACBs.
ACBGEN is known as Access Control Blocks Generator. It is used to generate ACBs.
For online programs, we need to pre-build ACBs. Hence the ACBGEN utility is executed before executing the application program.
For online programs, we need to pre-build ACBs. Hence the ACBGEN utility is executed before executing the application program.
For batch programs, ACBs can be generated at execution time too.
For batch programs, ACBs can be generated at execution time too.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2103,
"s": 1946,
"text": "IMS Control Blocks define the structure of the IMS database and a program's access to them. The following diagram shows the structure of IMS control blocks."
},
{
"code": null,
"e": 2159,
"s": 2103,
"text": "DL/I uses the following t... |
Ngx-Bootstrap - Environment Setup | In this chapter, you will learn in detail about setting up the working environment of ngx-bootstrap on your local computer. As ngx-bootstrap is primarily for angular projects, make sure you have Node.js and npm and angular installed on your system.
First create a angular project to test ngx-bootstrap components using following commands.
ng new ngxbootstrap
It will create an angular project named ngxbootstrap.
You can use the following command to install ngx-bootstrap in newly created project−
npm install ngx-bootstrap
You can observe the following output once ngx-bootstrap is successfully installed −
+ ngx-bootstrap@5.6.1
added 1 package from 1 contributor and audited 1454 packages in 16.743s
Now, to test if bootstrap works fine with Node.js, create the test component using following command −
ng g component test
CREATE src/app/test/test.component.html (19 bytes)
CREATE src/app/test/test.component.spec.ts (614 bytes)
CREATE src/app/test/test.component.ts (267 bytes)
CREATE src/app/test/test.component.css (0 bytes)
UPDATE src/app/app.module.ts (388 bytes)
Clear content of app.component.html and update it following contents.
app.component.html
<app-test></app-test>
Update content of app.module.ts to include ngx-bootstrap accordion module. We'll add other module in subsequent chapters. Update it following contents.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { AccordionModule } from 'ngx-bootstrap/accordion'
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserAnimationsModule,
BrowserModule,
AccordionModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Update content of index.html to include bootstrap.css. Update it following contents.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ngxbootstrap</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
In next chapter, we'll update test component to use ngx-bootstrap components.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2349,
"s": 2100,
"text": "In this chapter, you will learn in detail about setting up the working environment of ngx-bootstrap on your local computer. As ngx-bootstrap is primarily for angular projects, make sure you have Node.js and npm and angular installed on your system."
}... |
What is the search() function in Python? | In Python, search() is a method of the module re.
Syntax of search()
re.search(pattern, string):
It is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. Unlike in re.match() method, here searching for pattern ‘Tutorials’ in the string ‘TP Tutorials Point TP’ will return a match.
import re
result = re.search(r'Tutorials', 'TP Tutorials Point TP')
print result.group(0)
Tutorials
Here you can see that, search() method is able to find a pattern from any position of the string but it only returns the first occurrence of the search pattern. | [
{
"code": null,
"e": 1112,
"s": 1062,
"text": "In Python, search() is a method of the module re."
},
{
"code": null,
"e": 1131,
"s": 1112,
"text": "Syntax of search()"
},
{
"code": null,
"e": 1159,
"s": 1131,
"text": "re.search(pattern, string):"
},
{
... |
HTML <font> Tag | The <font> tag in HTML is used to set font color, font family and font size. Following is the attributes −
color: Set the color of the font.
face: Set the font face i.e. family.
size: Set the font size
Note − The <font> tag isn’t supported in HTML5.
Let us now see an example to implement the <font> tag in HTML −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Playing with Fonts</h2>
<p>Displaying different fonts below:</p>
<p><font face="arial" size="20" color="yellow">Demo Text!</font></p>
<p><font size="10" color="gray">Demo Text!</font></p>
<p><font size="15" face="verdana" color="magento">Demo Text!</font></p>
<p><font size="8" face="calibri" color="magento">Demo Text!</font></p>
</body>
</html>
In the above example, we have set the font using the font tag attributes −
<font size="8" face="calibri" color="magento">
Demo Text!
</font>
Above, we have set the font size with −
font size="8"
We have set the font face with face attribute −
font face="calibri"
The font color with color attribute −
font color="magento" | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The <font> tag in HTML is used to set font color, font family and font size. Following is the attributes −"
},
{
"code": null,
"e": 1203,
"s": 1169,
"text": "color: Set the color of the font."
},
{
"code": null,
"e": 1240... |
Understanding Hypothesis Testing. A simple yet detailed dive into all the... | by Shubhangi Hora | Towards Data Science | Hypothesis testing is an important mathematical concept that’s used in the field of data science. While it’s really easy to call a random method from a python library that’ll carry out the test for you, it’s both necessary and interesting to know what is actually happening behind the scenes! What is hypothesis testing, why do we need it, what does it do and how does it really work? Let’s find out!
Hypothesis testing is a statistical method to determine whether a hypothesis that you have holds true or not. The hypothesis can be with respect to two variables within a dataset, an association between two groups or a situation.
The method evaluates two mutually exclusive statements (two events that cannot occur simultaneously) to determine which statement is best supported by the sample data and make an informed decision.
The building blocks of hypothesis testing are:
Hypotheses — null and alternateStatistical testsProbability distributionsTest statisticsCritical valuesLevel of significance (alpha)P-value
Hypotheses — null and alternate
Statistical tests
Probability distributions
Test statistics
Critical values
Level of significance (alpha)
P-value
The process of hypothesis testing involves two hypotheses — a null hypothesis and an alternate hypothesis.
The null hypothesis is a statement that assumes there is no relationship between two variables, no association between two groups or no change in the current situation — hence ‘null’. It is denoted by H0.
The alternate hypothesis is the opposite of the null hypothesis because it assumes that there is some relationship between two variables or there is some change in the current situation — hence ‘alternate’. It is denoted by Ha or H1.
The conclusion of hypothesis testing is whether the null hypothesis is not rejected (so you accept that there is no change) or is rejected (so you reject that there is no change).
Let’s understand this with an example.
There’s a dataset that contains information on patients who’ve been admitted to a hospital in the past year. Two features present in this dataset are location and total amount spent. We believe there’s a difference in the total amount spent during admission based on where a person lives — this statement is your alternate hypothesis, since it assumes a relationship between location and the amount spent in the hospital.
Hence, the null hypothesis will be that there is no difference in the amount spent at the hospital based on where a person lives.
Now we need to figure out whether we should or should not reject the null hypothesis. How do we do that?
Statistical tests help us in rejecting or not rejecting our null hypothesis by providing us with a test statistic (a single numeric value) from our sample data. This test statistic measures the extent to which the sample data agrees with the null hypothesis — if it agrees then the null hypothesis is not rejected, else it is rejected.
There are multiple statistical tests that exist for different use cases. The selection of which statistical test to use your hypothesis testing depends on several factors, such as — the distribution of the sample (whether it is normally distributed (follows the normal distribution)), what the sample size is, whether the variance is known, the type of data that you have, amongst some other things. Each test has its own test statistic based on the probability model/distribution that the test follows.
For example —
Statistical tests are of two types — one-tailed and two-tailed.
The concept of tails is related to probability distributions.
A probability distribution is a statistical function whose output is the probabilities of the occurrences of different events (possible outcomes) of an experiment.
For example:
A probability distribution is both in the form of data and a graph, but the graph is a better way to understand what tails are.
The tails of a distribution are the endings of the curve / graph on the sides of the distribution. The right end is known as the right tail or the upper tail, and the left end as the left tail or the lower tail.
It is not necessary for a distribution to have both tails in all situations, it could have just one. The number of tails is dependent on your null and alternate hypotheses.
Thus we have one-tailed distributions and two-tailed distributions.
So, a one-tailed statistical test is one whose distribution has only one tail — either the left (left-tailed test) or the right (right-tailed test). A two-tailed statistical test is one whose distribution has two tails — both left and right.
The purpose of a tail in statistical tests is to see whether the test statistic obtained falls within the tail or outside it. The tail region is known as the region of rejection — which makes sense since the null hypothesis is rejected if the test statistic falls within this area. If it falls outside it then the null hypothesis is accepted.
Determining where the tail begins is done with the help of a parameter known as the level of significance — alpha. It is the probability of rejecting the null hypothesis when the null hypothesis is true. The most common value for alpha is 5%, i.e. 0.05. This means that you face a 5% risk of rejecting the null hypothesis, i.e. believing there is a difference in the current situation when there actually isn’t.
In terms of our distribution, alpha is the area of the distribution that makes up the region of rejection — hence it is the tail(s). Since the tails are at the end of the distribution, we are literally saying, with the level of significance, how far away from the null hypothesis our test statistic needs to be for us to actually reject the null hypothesis.
So, if we were to select a right-tailed test and our level of significance was 5%, then the 5% of the area of distribution on the right end of the curve would be our region of rejection. Using this, we calculate the value on the x-axis which demarcates where the region of rejection begins — this is known as the critical value.
In the case of a two-tailed test, we would divide the level of significance by half — 2.5% — and this would be the area of each region of rejection on either side of the curve. Then we would have two critical values and the regions of rejection would also be known as the critical regions.
One-tailed tests are directional as there is only one region of rejection. You are looking for a test statistic that falls within that sole region of rejection. Two-tailed tests are nondirectional since there are two regions of rejection and if the test statistic falls in either of them then the null hypothesis is rejected.
For example, the sample mean age of patients at a dentist’s clinic is 18 — this is your null hypothesis (since this is the current scenario and you are assuming there is no change). Another dentist joins the practice and you believe that now the sample mean of patients will be greater than 18 — this is your alternate hypothesis. It is directional due to the ‘greater than’ — only if the sample mean is greater than 18 will you reject the null hypothesis. If it is less than 18, your null hypothesis will not be rejected.
If it were a two-tailed test, your alternate hypothesis would simply be that the sample mean age of patients is not equal to 18. The sample mean could be greater than or less than 18, either way the null hypothesis would be rejected, hence it is nondirectional.
So far, we have hypotheses, a statistical test based on a probability distribution, a level of significance from which we get the region of rejection from which we get the critical value, and a test statistic that falls somewhere within our distribution.
As mentioned before, the test statistic is compared with the critical value. The p-value is compared with the level of significance.
P-value is the probability that the test statistic you have obtained is by random chance which would mean the null hypothesis is actually true. If the p-value is lower than the level of significance then it is statistically significant and the null hypothesis is rejected, because it means that there is a less than 5% probability that the null hypothesis is true. If it is higher than the level of significance then the null hypothesis is not rejected.
In terms of the graphical representation of our probability distribution, the p-value is the area of the curve on the right of the test statistic.
A big plus point of the p-value is that it doesn’t need to be recalculated for different levels of significance since it is directly comparable. In the case of test statistics, they have to be compared with critical values which do need to be recalculated for different levels of significance (if the area of the regions of rejection change then the x-axis value for where the regions begin will also change). That’s why it’s always better to work with the p-value in hypothesis testing.
Despite the above mentioned advantage though, the p-value is still probabilistic. Hence there is a chance that the null hypothesis will be rejected even though it is true. Alpha (the level of significance) is the likelihood that this will happen. This error is known as a type I error or a false positive.
The opposite to the above error would be not rejecting the null hypothesis even though it is not true. This is known as a type II error or a false negative.
Both of these errors are inversely related, i.e. if you try to reduce one the other will increase. So how do you get the perfect situation? You don’t, you just have to decide which error is less risky in your situation. For example, it’s less risky to tell someone they are covid-19 positive when they’re actually negative — this is a false positive (type I error). A false negative would be saying someone doesn’t exhibit fraudulent behavior when they actually do.
Finally we have all the building blocks of hypothesis testing sorted so the process is also pretty clear. The steps for hypothesis testing are:
Formulating your hypothesesChoosing a level of significanceIdentifying a statistical testCalculating the test statisticCalculating the p-value and comparing it with the level of significanceConcluding — rejecting or not rejecting your null hypothesis
Formulating your hypotheses
Choosing a level of significance
Identifying a statistical test
Calculating the test statistic
Calculating the p-value and comparing it with the level of significance
Concluding — rejecting or not rejecting your null hypothesis
Let’s go through these steps with an example that we used above about the mean age of patients that visit a dentist. We know that the mean age is 18 and the standard deviation is 8. Let’s assume the data follows a normal distribution. We think that the mean age isn’t 18, but is in fact larger than 18.
Since we have directionality in our alternate hypothesis, we need a right-tailed statistical test.
We are comparing the sample mean age, so we can use the z-test to determine whether our alternate hypothesis is probable or not.
Our level of significance is 5% and we are performing a right-tailed test so the right tail of our curve is the region of rejection.
Our sample data is 30 patients at random and we calculate the sample mean age.
So we have:
Now we need to calculate our test statistic, which in the case of the z-test is the z-score. The formula for z-score is
So our z-score is
The critical value of the normal distribution with alpha as 0.05 is 1.645. So we can already see that our test statistic is greater than our critical value, hence we can reject the null hypothesis. But as mentioned before, the p-value is the best way to determine whether or not we should reject the null hypothesis, so let’s calculate that too.
The probability of getting a value of 2.05 on the normal distribution is 0.9798. Since the p-value is the area to the right of the test statistic, it is calculated by subtracting 0.9798 from 1.
A p-value of 0.0202 is less than the 0.05 and hence we can reject our null hypothesis and conclude that it is more probable for the sample mean to be greater than 18.
Let’s actually implement all of this in python now!
We’re going to use a covid-19 datatset. It contains region wise confirmed cases and deaths from early 2020. It also contains temperature, humidity, latitude and longitude.
The first step is to import all the required packages:
import pandas as pdimport statsmodels.api as sm
We’ll be using pandas to read our data and stasmodels to actually carry out our hypothesis test.
Read the data into a dataframe:
covid = pd.read_csv(“Covid-19.csv”)covid = covid.drop([“Unnamed: 0”], axis=1)covid.head()
I believe that there is a relationship between temperature and the number of confirmed covid-19 cases — is the average temperature in regions with confirmed covid-19 cases greater than 12 degrees?
The first step of hypothesis testing is to formulate the hypotheses. Ours would be:
Since our alternate hypothesis is directional, we will be performing a one-tailed statistical test (a right-tailed test) — the z-test.
The level of significance will be 0.05, the test statistic is the z-score and the critical value is 1.645.
It’s really easy to calculate the test statistic and the p-value using the statsmodels ztest method. Let’s wrap this functionality in a function of our own and add the comparison between alpha and the p-value.
def hyptest(data, value, alternate, alpha): z, p = sm.stats.ztest(data, value=value, alternative=alternate) result = 'null hypothesis rejected!' if p < alpha else 'null hypothesis not rejected' return z, p, result
Now we call our function — pass the temperature column (since that’s the variable present in our hypothesis), the number 12 as value since that is the metric we are testing for, and “larger” in the alternative parameter since our alternate hypothesis is that the average is larger than the value.
hyptest(covid.Temperature, 12, "larger", 0.05)(1.0033989581188794, 0.15783420330389508, 'null hypothesis not rejected')
The results are the z-score, the p-value and the conclusion respectively. Since the p-value is greater than 0.05, we do not reject our null hypothesis.
And that’s how you carry out a hypothesis test!
Some key things to remember are:
hypothesis testing is done on a sample of the whole population — hence sample data. (if you want to determine whether age impacts the likelihood of getting admitted to the hospital, the ‘population’ would be every single person on earth. A ‘sample’ is a number of people chosen at random from this population)
the output of hypothesis testing is probabilistic since it is performed on a sample and not a population. So you can never say with complete certainty that the null hypothesis is true or not. You simply reject it or don’t reject it.
the null hypothesis is always written with equality — =, ≤ or ≥
the alternate hypothesis is always written with ≠, < or >
the p-value is affected by the sample size — if the sample size increases then the p-value will decrease if the null hypothesis is to be rejected.
Please do let me know your thoughts about this article in the comments below or reach out to me on LindkedIn and we can connect!
The raw data has been taken from John Hopkins’ GitHub repository and then modified to get the temperature of the region. The code used to perform the test and to create the graphs can be found here. | [
{
"code": null,
"e": 573,
"s": 172,
"text": "Hypothesis testing is an important mathematical concept that’s used in the field of data science. While it’s really easy to call a random method from a python library that’ll carry out the test for you, it’s both necessary and interesting to know what is ... |
SignUp form using Node and MongoDB | In this article, we will create a simple user sign-up form having some parameters. On clicking SAVE, all the user details will be saved in the MongoDB database.
Before proceeding to create the sign-up form, the following dependencies must be succesfully installed on your system.
Check and install express by using the following command. Express is used to set middlewares to respond to HTTP requests
Check and install express by using the following command. Express is used to set middlewares to respond to HTTP requests
npm install express --save
Setup the "body-parser" node module for reading the HTTP POST data.
Setup the "body-parser" node module for reading the HTTP POST data.
npm install body-parser --save
Setup "mongoose", as it sits on top of Node's MongoDB driver.
Setup "mongoose", as it sits on top of Node's MongoDB driver.
npm install mongoose --save
Create the following files and copy paste the code-snippet with respect to each file given below −app.jspublic (Create a new folder and paste the below files inside this folder.)index.htmlsuccess.htmlstyle.css
Create the following files and copy paste the code-snippet with respect to each file given below −
app.js
app.js
public (Create a new folder and paste the below files inside this folder.)index.htmlsuccess.htmlstyle.css
public (Create a new folder and paste the below files inside this folder.)
index.html
index.html
success.html
success.html
style.css
style.css
Now, run the following command to run the application.
Now, run the following command to run the application.
node app.js
app.js
var express=require("express");
var bodyParser=require("body-parser");
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tutorialsPoint');
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
console.log("connection succeeded");
})
var app=express()
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/sign_up', function(req,res){
var name = req.body.name;
var email =req.body.email;
var pass = req.body.password;
var phone =req.body.phone;
var data = {
"name": name,
"email":email,
"password":pass,
"phone":phone
}
db.collection('details').insertOne(data,function(err, collection){
if (err) throw err;
console.log("Record inserted Successfully");
});
return res.redirect('success.html');
})
app.get('/',function(req,res){
res.set({
'Access-control-Allow-Origin': '*'
});
return res.redirect('index.html');
}).listen(3000)
console.log("server listening at port 3000");
index.html
<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
</div>
<div class="main">
<form action="/sign_up" method="post">
<h1>Welcome to Tutorials Point - SignUp</h1>
<input class="box" type="text" name="name" id="name" placeholder="Name" required /><br>
<input class="box" type="email" name="email" id="email" placeholder="E-Mail " required /><br>
<input class="box" type="password" name="password" id="password" placeholder="Password " required/><br>
<input class="box" type="text" name="phone" id="phone" placeholder="Phone Number " required/><br>
<br>
<input type="submit" id="submitDetails" name="submitDetails" class="registerbtn" value="Submit" /> <br>
</form>
</div>
<div class="">
</div>
</div>
</div>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 main">
<h1> Signup Successful</h1>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html>
style.css
.main{
padding:20px;
font-family: 'Helvetica', serif;
box-shadow: 5px 5px 7px 5px #888888;
}
.main h1{
font-size: 40px;
text-align:center;
font-family: 'Helvetica', serif;
}
input{
font-family: 'Helvetica', serif;
width: 100%;
font-size: 20px;
padding: 12px 20px;
margin: 8px 0;
border: none;
border-bottom: 2px solid #4CAF50;
}
input[type=submit] {
font-family: 'Helvetica', serif;
width: 100%;
background-color: #4CAF50;
border: none;
color: white;
padding: 16px 32px;
margin: 4px 2px;
border-radius: 10px;
}
.registerbtn {
background-color: #4CAF50;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
Now, try this link on your web browser. You will see a registration page.
http://127.0.0.1:3000/index.html OR http://localhost:3000/index.html
C:\Users\tutorialsPoint\> node app.js
server listening at port 3000
(node:73542) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:73542) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
connection succeeded
Sign-up Page
Success Page
Record Inserted Succesfully in mongoDB | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "In this article, we will create a simple user sign-up form having some parameters. On clicking SAVE, all the user details will be saved in the MongoDB database."
},
{
"code": null,
"e": 1342,
"s": 1223,
"text": "Before proceeding to ... |
Program to find number of squares in a chessboard in C++ | In this problem, we are given the size of a chessboard. Our task is to create a program to find number of squares in a chessboard in C++.
Problem Description − To find the number of squares in a chessboard. We will have to calculate all the combinations of the square that are inside the chessboard i.e. we will consider squares of side 1x1, 2x2, 3x3 ... nxn.
Let’s take an example to understand the problem,
Input: n = 4.
Output: 30
Squares of size 1x1 -> 16
Squares of size 2x2 -> 9
Squares of size 3x3 -> 4
Squares of size 4x4 -> 1
Total number of squares = 16+9+4+1 = 30
Solution Approach:
A simple approach is by using the sum formula for nxn grid.
Let’s deduct the general formula for the sum,
sum(1) = 1
sum(2) = 1 + 4 = 5
sum(3) = 1 + 4 + 9 = 14
sum(4) = 1 + 4 + 9 + 16 = 30
The sum is can be generalised as
sum = 12 + 22 + 32 + 42 + ... n2
sum = ( (n*(n+1)*((2*n) + 1))/6 )
#include <iostream>
using namespace std;
int calcSquaresCount(int n){
int squareCount = ( (n * (n+1) * (2*n + 1))/6 );
return squareCount;
}
int main() {
int n = 6;
cout<<"The total number of squares of size "<<n<<"X"<<n<<" is
"<<calcSquaresCount(n);
}
The total number of squares of size 6X6 is 91 | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "In this problem, we are given the size of a chessboard. Our task is to create a program to find number of squares in a chessboard in C++."
},
{
"code": null,
"e": 1422,
"s": 1200,
"text": "Problem Description − To find the number of ... |
Using R and Python in Google Sheets Formulas | by Sam Terfa | Towards Data Science | Google’s version of spreadsheets called Google Sheets has a hidden gem which significantly increases the power of your spreadsheets called Google Apps Script. Google Apps Script uses Javascript to call other Google services, create interactive pop-up dialogs, and even make API calls. With a bit of setup, you can create spreadsheet formulas for others to use that execute R, Python, or practically any programming language code! While Shiny and Dash are great ways to share your work, following the instructions in this article, you will be able to create R and Python dashboards directly inside Google Sheets. As a bonus, these same methods allow you to insert R and Python functionality into other Google services such as Docs, Forms and Slides!
Matrix Multiplication
Matrix Multiplication
2. Plotting (base R)
3. Plotting (ggplot2)
4. Deploying a Model
5. Any R Script!
Under the hood, each custom function is a Google Apps script that makes an API call to an endpoint I have set up in Google Cloud Run. If you can set up API endpoints that run R, Python, or any other language scripts, you can import those powers into a Google spreadsheet. This is phenomenal!
The following 6 steps are arranged from easiest to hardest and will simply get you up and running with your own custom spreadsheet function powered by R or Python APIs. There is a lot more to Google Apps script, creating your own APIs, and Google Cloud Run which can be covered in another post.
Create a Spreadsheet in Google DriveTools menu-> Script Editor
Create a Spreadsheet in Google Drive
Tools menu-> Script Editor
3. Copy and paste the following code into the editor. Adapt to your needs.
/** * Run an R, Python, or other language script on spreadsheet data. * * @param var1 The value or cell contents to pass to your API. * @param var2 The value or cell contents to pass to your API. * @return The results of the API call you're about to make. * @customfunction */function myCustomFunction(var1 = null, var2 = null){ // Assuming your API endpoint is like {baseURL}/{endpoint}. var baseURL = '(Copy and paste API base url w/o trailing /)'; var endpoint = 'myCustomFunction'; // Encode the variable values as JSON (or XML, or something else). // See Google Apps Script UrlFetchApp documentation. var data = { 'var1': var1, 'var2': var2, }// Set up the API call. Use POST requests to pass variables.// You can pass variables as query params of GET requests instead. var options = { 'method' : 'post', 'contentType': 'application/json', 'payload' : JSON.stringify(data) }; // Make the API call. NOTE: Trailing slashes are important! var response = UrlFetchApp.fetch(baseURL + '/' + endpoint + '/', options); // Parse the response. data = JSON.parse(response.getContentText()); // I return "Error: {the error}" on script errors. // Not necessary, but it shows useful error messages in cells. if(String(data).substring(0,6) == "Error:"){ throw(String(data)); } return(data);}
4. Create a plain text file with no extension named “Dockerfile”.Put it in its own folder on your hard drive. Don’t get nervous; you do not need Docker on your system to follow these steps (but you should absolutely be using Docker in your daily work!)
Copy and paste one of the following into your Dockerfile.
R Example 1: Here’s a Dockerfile for an R API using the amazing Plumber package. This does not come with Tidyverse, but it creates slim images.
FROM trestletech/plumberCOPY [".", "./"]ENTRYPOINT ["R", "-e", "pr <- plumber::plumb(commandArgs()[4]); pr$run(host='0.0.0.0', port=as.numeric(Sys.getenv('PORT')), swagger = T)"]CMD ["Plumber.R"]
R Example 2: Here’s a Dockerfile for an R API which DOES come with Tidyverse and Tensorflow (based on the rocker/ml image). This creates bloated images and comes with RStudio. It isn’t meant for production.
FROM samterfa/rmlsheetsCOPY [".", "./"]ENTRYPOINT ["Rscript", "-e", "pr <- plumber::plumb(commandArgs()[9]); pr$run(host='0.0.0.0', port=as.numeric(Sys.getenv('PORT')), swagger = T)"]CMD ["Plumber.R"]
Python Example: Here’s a Dockerfile using the aptly named Fast API .
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7RUN pip install pandasCOPY [".", "./"]
5. Create the scripts that will power your custom function. Add the following file to the same folder as your Dockerfile. Note that cell references from Google Sheets are passed in as single values for individual cells, or as nested lists for multiple cells.
R API File: Create a file named Plumber.R. You can copy and paste the following as a sample.
# Swagger docs at ...s/__swagger__/ (needs trailing slash!)if(Sys.getenv('PORT') == '') Sys.setenv(PORT = 8000)#' @apiTitle R Google Sheets Formulas#' @apiDescription These endpoints allow the user to create custom functions in Google spreadsheets which call R functions.#* Return the product of 2 matrices#* @param var1 An array of values representing the first matrix.#* @param var2 An array of values representing the second matrix.#* @post /myCustomFunction/function(var1, var2){ err <- tryCatch({ return(data.matrix(var1) %*% data.matrix(var2)) }, error = function(e) e) return(paste0('Error: ', err$message))}#* Confirmation Message#* @get /function(msg=""){ "My API Deployed!"}
Python API File: Create a file named Main.py. You can copy and paste the following as a sample.
from fastapi import FastAPIfrom pydantic import BaseModelclass Matrices(BaseModel): var1: list var2: list app = FastAPI()@app.post("/myCustomFunction/")def myCustomFunction(matrices: Matrices): import sys import numpy as np try: var1 = np.matrix(matrices.var1) var2 = np.matrix(matrices.var2) results = np.matmul(var1, var2) return np.array(results).tolist() except: e_type, e_value, e_traceback = sys.exc_info() return 'Error: ' + str(e_type) + ' ' + str(e_value)@app.get("/")def myAPIdeployed(): return "My API Deployed!"
NOTE: To run an arbitrary R or Python script inside a Google Sheet, the script needs to determine whether passed arrays include column names or not. The code is a bit unwieldy but I’ve included an R attempt at the end of this article.
6. Deploy your API (to Google Cloud Run)If you already know how to deploy an R or Python API, you’ve probably already stopped reading this article and are off to the races! For the rest of us, I will guide you through using Google Cloud Run to host your API.
Mark Edmondson has created a phenomenal R package called googleCloudRunner. This package handles auth, creates builds, and deploys containers to Google Cloud Run. It’s truly remarkable. If you don’t have R installed, you can follow these project setup instructions, and these deployment instructions keeping in mind that we are trying to deploy our Dockerfile from above. From here on, I will assume you have R running and googleCloudRunner installed.
Go to https://console.cloud.google.com/
Agree to Terms and Services if you’ve never created a project before.
Click Select a Project and then NEW PROJECT.
Name & create the project. I like Rscripts, Pyscripts, or something like that.
Make sure the project name is in the upper left dropdown.
Click on the menu to the left of the dropdown, click Billing, and then Add billing account. I promise, it’s very cheap!
For the rest of the set up, follow Mark Edmondson’s instructions here.
Identify the path to the folder containing your Dockerfile and API file. Let’s call it “/users/me/my/api/path”.
Using R, run the following to deploy your API! The name of the service created inside Google Cloud Run will be the name of the last folder in the folder path, so make sure you like the name and that its name is lowercase.
googleCloudRunner::cr_deploy_run(local = "/users/me/my/api/path")# Wait, that's it? Just that?
A browser will open showing you the progress of your build. If there is an error, you can use the log messages to determine what went wrong. Common issues are missing service account permissions and code problems. If you are comfortable with Docker, you can test locally to make sure there are no code problems. If successful, you should see a message (if you copy and pasted my code).
Once it’s launched, you need to copy and paste your API URL from above into your Google Apps Script.
Try it out! Create two numerical arrays in a Google Sheet which could multiply as matrices, start typing “=myCustomFunction(”, highlight the cells, and be impressed with yourself.
Free API Swagger webpagesThese are automagically generated for you because you used the R package Plumber or the Python-based FastAPI.
Free API Swagger webpagesThese are automagically generated for you because you used the R package Plumber or the Python-based FastAPI.
R version is at {YourBaseURL}/__swagger__/
Python version is at {YourBaseURL}/docs
2. samterfa/rpysheets GitHub RepoThis repo contains all the files listed above plus some bonus material. The bonus material includes the generalized rscript function, as well as the MNIST digit prediction function. If you want to use prediction with large models, you do face a 30 second time limit by Google Sheets. You may also need to beef up your Google Cloud Run service. | [
{
"code": null,
"e": 921,
"s": 172,
"text": "Google’s version of spreadsheets called Google Sheets has a hidden gem which significantly increases the power of your spreadsheets called Google Apps Script. Google Apps Script uses Javascript to call other Google services, create interactive pop-up dial... |
How to draw 2D Heatmap using Matplotlib in python? - GeeksforGeeks | 26 Nov, 2020
A 2-D Heatmap is a data visualization tool that helps to represent the magnitude of the phenomenon in form of colors. In python, we can plot 2-D Heatmaps using Matplotlib package. There are different methods to plot 2-D Heatmaps, some of them are discussed below.
Method 1: Using matplotlib.pyplot.imshow() Function
Syntax: matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None,vmax=None, origin=None, extent=None, shape=<deprecated parameter>, filternorm=1, filterrad=4.0,imlim=<deprecated parameter>, resample=None, url=None, \*, data=None, \*\*kwargs)
Python3
# Program to plot 2-D Heat map# using matplotlib.pyplot.imshow() methodimport numpy as npimport matplotlib.pyplot as plt data = np.random.random(( 12 , 12 ))plt.imshow( data , cmap = 'autumn' , interpolation = 'nearest' ) plt.title( "2-D Heat Map" )plt.show()
Output:
Method 2: Using Seaborn Library
For this we use seaborn.heatmap() function
Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, robust=False,annot=None,fmt=’.2g’, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, cbar_kws=None, cbar_ax=None,square=False, xticklabels=’auto’, yticklabels=’auto’, mask=None, ax=None, **kwargs)
Python3
# Program to plot 2-D Heat map# using seaborn.heatmap() methodimport numpy as npimport seaborn as snsimport matplotlib.pylab as plt data_set = np.random.rand( 10 , 10 )ax = sns.heatmap( data_set , linewidth = 0.5 , cmap = 'coolwarm' ) plt.title( "2-D Heat Map" )plt.show()
Output:
Method 3: Using matplotlib.pyplot.pcolormesh() Function
Syntax: matplotlib.pyplot.pcolormesh(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, shading=’flat’, antialiased=False, data=None, **kwargs)
Python3
# Program to plot 2-D Heat map# using matplotlib.pyplot.pcolormesh() methodimport matplotlib.pyplot as pltimport numpy as np Z = np.random.rand( 15 , 15 ) plt.pcolormesh( Z , cmap = 'summer' ) plt.title( '2-D Heat Map' )plt.show()
Output:
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24687,
"s": 24659,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24952,
"s": 24687,
"text": "A 2-D Heatmap is a data visualization tool that helps to represent the magnitude of the phenomenon in form of colors. In python, we can plot 2-D Heatmaps using Mat... |
Logic functions and Minimization - GeeksforGeeks | 19 Nov, 2018
= PQ + QR’ + PR’
= PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’
= PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’
= PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4)
= m2 + m4 + m6 + m7
A)
B)
C)
D)
A) m(4, 6)
B) m(4, 8)
C) m(6, 8)
D) m(4, 6, 8)
m(6,8)+m(1,6,15)
m(1,6,8,15)an
= (P + Q’)(PQ’ + PR)(P’R’ + Q’)
= (PPQ’ + PPR + PQ’Q’ + PQ’R) (P’R’ + Q’)
= (PQ’ + PR + PQ’ + PQ’R) (P’R’ + Q’)
= (PP’Q’R’ + PP’R’R + PP’Q’R’ + PP’Q’RR’ + PQ’Q’ + PQ’R + PQ’Q’ + PQ’Q’R)
= (0 + 0 + 0 + 0 + PQ’ + PQ’R + PQ’ + PQ’R)
= PQ’ + PQ’R
= PQ'(1 + R)
= PQ’
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to set background images in ReactJS ?
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Alter Multiple Columns at Once in SQL Server?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File | [
{
"code": null,
"e": 27610,
"s": 27582,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 27769,
"s": 27610,
"text": "= PQ + QR’ + PR’ \n= PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’\n= PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’ \n= PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4) \n= m2 + m4 + m6 + m7 "... |
Convert DataFrame to Matrix with Column Names in R - GeeksforGeeks | 21 Apr, 2021
Data frames and matrices are R objects, both of which allow tabular storage of the data into well organized cells. However, the data in a data frame can consist of different data types, that is the cells may contain data belonging to a combination of data types. Matrices, on the other hand, strictly allow a singular data type value to be stored across all its data elements. These are interconvertible into each other, if they satisfy the following conditions :
Data frame should not have NA or missing values.
The data type stored across all the columns should be of the same type, that is either numeric or character type.
The data.matrix() method in R Programming language used to convert a data frame to a numeric matrix. All the variables contained in a data frame are translated to corresponding numeric modes followed by their binding to form columns of a matrix. However, the character values are not retained and are converted to equivalent integer values in order to preserve the uniformity of the data type of the matrix. The column names are preserved during the interconversion.
Syntax: data.matrix(dataframe, rownames.force = NA)
Parameters :
dataframe – the data frame to convert to a matrix
rownames.force – logical determining whether the resulting matrix should have character (rather than NULL) row names.
Example 1:
R
# declaring a data frame in Rdata_frame = data.frame(C1= c(5:8), C2 = c("ab","b","C","d")) print("Original data frame")print(data_frame) # converting the data frame into matrix mat = data.matrix(data_frame) print ("matrix of the above data frame")print (mat)
Output:
[1] “Original data frame”
C1 C2
1 5 ab
2 6 b
3 7 C
4 8 d
[1] “matrix of the above data frame”
C1 C2
[1,] 5 1
[2,] 6 2
[3,] 7 3
[4,] 8 4
However, there is an exception to this transformation, that is, in case the data supplied as input is completely numeric, including integers and floating-point decimals, then the same data is returned as output without any interconversion.
Example 2:
R
# declaring a data frame in Rdata_frame = data.frame(C1= c(5:8),C2 = c(1.2,6,5.7,0.5)) print("Original data frame")print(data_frame) # converting the data frame into matrix mat = data.matrix(data_frame) print ("matrix of the above data frame")print (mat)
Output:
[1] “Original data frame”
C1 C2
1 5 1.2
2 6 6.0
3 7 5.7
4 8 0.5
[1] “matrix of the above data frame”
C1 C2
[1,] 5 1.2
[2,] 6 6.0
[3,] 7 5.7
[4,] 8 0.5
The boolean data type, TRUE is returned as 1 in the matrix form and FALSE as 0.
Example 3:
R
# declaring a data frame in Rdata_frame = data.frame(C1= c(5:7),C2 = c(1,6,TRUE), C3=c(FALSE,TRUE,FALSE)) print("Original data frame")print(data_frame) # converting the data frame into matrix mat = data.matrix(data_frame) print ("matrix of the above data frame")print (mat)
Output:
[1] “Original data frame”
C1 C2 C3
1 5 1 FALSE
2 6 6 TRUE
3 7 1 FALSE
[1] “matrix of the above data frame”
C1 C2 C3
[1,] 5 1 0
[2,] 6 6 1
[3,] 7 1 0
Picked
R DataFrame-Programs
R Matrix-Programs
R-DataFrame
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25316,
"s": 24851,
"text": "Data frames and matrices are R objects, both of which allow tabular storage of the data into well organized cells. However, the data in a data frame can consist of... |
Python - Read csv file with Pandas without header? | To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.
Let’s say the following are the contents of our CSV file opened in Microsoft Excel −
At first, import the required library −
import pandas as pd
Load data from a CSV file into a Pandas DataFrame. This will display the headers as well −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
While loading, use the header parameter and set None to load the CSV without header −
pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv", header=None)
Following is the code −
import pandas as pd
# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
print("\nReading the CSV file...\n",dataFrame)
# Load data from a CSV file and hide the header
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv", header=None)
print("\nReading the CSV file (without header)...\n",dataFrame)
This will produce the following output −
Reading the CSV file...
Car Reg_Price Units
0 BMW 2500 100
1 Lexus 3500 80
2 Audi 2500 120
3 Jaguar 2000 70
4 Mustang 2500 110
Reading the CSV file (without header)...
0 1 2
0 Car Reg_Price Units
1 BMW 2500 100
2 Lexus 3500 80
3 Audi 2500 120
4 Jaguar 2000 70
5 Mustang 2500 110 | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method."
},
{
"code": null,
"e": 1252,
"s": 1167,
"text": "Let’s say the following are the contents of our CSV file opened in Microsoft ... |
abs() in Python - GeeksforGeeks | 13 Sep, 2021
Python abs() function is used to return the absolute value of a number, i.e., it will remove the negative sign of the number.
Syntax: abs(number)number: Can be an integer, a floating-point
number or a complex number
The abs() takes only one argument, a number whose absolute value is to be returned. The argument can be an integer, a floating-point number, or a complex number.
If the argument is an integer or floating-point number, abs() returns the absolute value in integer or float.
In the case of a complex number, abs() returns only the magnitude part and that can also be a floating-point number.
The abs() function make any negative number to positive, while positive numbers are unaffected. The absolute value of any number is always positive. For any positive number, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the negative number.
In this example, we pass float, int, and complex data into abs() function and it will return absolute value.
Python3
# Python code to illustrate# abs() built-in function # floating point numberfloat = -54.26print('Absolute value of float is:', abs(float)) # An integerint = -94print('Absolute value of integer is:', abs(int)) # A complex numbercomplex = (3 - 4j)print('Absolute value or Magnitude of complex is:', abs(complex))
Output:
Absolute value of float is: 54.26
Absolute value of integer is: 94
Absolute value or Magnitude of complex is: 5.0
This equation shows the relationship between speed, distance traveled and time taken:
Speed is distance divided by the time taken.
And we know speed, time and distance are never negative, for this we will use abs() methods to calculate the exact time, distance, and speed.
Formula used:
Distance = Speed * Time
Time = Distance / Speed
Speed = Distance / Time
Examples:
Input : distance(km) : 48.5 time(hr) : 2.6
Output : Speed(km / hr) : 18.653846153
Input : speed(km / hr) : 46.0 time(hr) : 3.2
Output : Distance(km) : 147.2
Input : distance(km) : 48.5 speed(km / hr) : 46.0
Output : Time(hr) : 1.0543
Code:
Python3
# Python3 Program to calculate speed,# distance and time # Function to calculate speeddef cal_speed(dist, time): print(" Distance(km) :", dist) print(" Time(hr) :", time) return dist / time # Function to calculate distance traveleddef cal_dis(speed, time): print(" Time(hr) :", time) print(" Speed(km / hr) :", speed) return speed * time # Function to calculate time takendef cal_time(dist, speed): print(" Distance(km) :", dist) print(" Speed(km / hr) :", speed) return speed * dist # Driver Code# Calling function cal_speed()print(" The calculated Speed(km / hr) is :", cal_speed(abs(45.9), abs(2.0)))print("") # Calling function cal_dis()print(" The calculated Distance(km) :", cal_dis(abs(62.9), abs(2.5)))print("") # Calling function cal_time()print(" The calculated Time(hr) :", cal_time(abs(48.0), abs(4.5)))
Output:
Distance(km) : 45.9
Time(hr) : 2.0
The calculated Speed(km / hr) is : 22.95
Time(hr) : 2.5
Speed(km / hr) : 62.9
The calculated Distance(km) : 157.25
Distance(km) : 48.0
Speed(km / hr) : 4.5
The calculated Time(hr) : 216.0
AdityaPandey1
sheetal18june
kumar_satyam
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 23662,
"s": 23634,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 23790,
"s": 23662,
"text": "Python abs() function is used to return the absolute value of a number, i.e., it will remove the negative sign of the number. "
},
{
"code": null,
"e"... |
What is a Tick in python? | The floating-point numbers in units of seconds for time interval are indicated by Tick in python. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch). You can use the time module to use functions for working with times, and for converting between representations. For example, if you want to print the current time in ticks, you'd write:
import time
ticks = time.time()
print("Ticks since 12:00am, January 1, 1970: ", ticks)
This will give the output −
Ticks since 12:00 am, January 1, 1970: 1514482031.2905385 | [
{
"code": null,
"e": 1439,
"s": 1062,
"text": "The floating-point numbers in units of seconds for time interval are indicated by Tick in python. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch). You can use the time module to use functions for working with t... |
Redis - Server Flushdb Command | Redis FLUSHDB deletes all the keys of the currently selected DB. This command never fails.
String reply.
Following is the basic syntax of Redis FLUSHDB command.
redis 127.0.0.1:6379> FLUSHDB
redis 127.0.0.1:6379> FLUSHDB
OK
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2136,
"s": 2045,
"text": "Redis FLUSHDB deletes all the keys of the currently selected DB. This command never fails."
},
{
"code": null,
"e": 2150,
"s": 2136,
"text": "String reply."
},
{
"code": null,
"e": 2206,
"s": 2150,
"text": "Follow... |
Boxplots in R Language - GeeksforGeeks | 10 Dec, 2021
A box graph is a chart that is used to display information in the form of distribution by drawing boxplots for each of them. This distribution of data based on five sets (minimum, first quartile, median, third quartile, maximum).
Boxplots are created in R by using the boxplot() function.
Syntax: boxplot(x, data, notch, varwidth, names, main)
Parameters:
x: This parameter sets as a vector or a formula.
data: This parameter sets the data frame.
notch: This parameter is the label for horizontal axis.
varwidth: This parameter is a logical value. Set as true to draw width of the box proportionate to the sample size.
main: This parameter is the title of the chart.
names: This parameter are the group labels that will be showed under each boxplot.
To understand how we can create a boxplot:
We use the data set “mtcars”.
Let’s look at the columns “mpg” and “cyl” in mtcars.
R
input <- mtcars[, c('mpg', 'cyl')]print(head(input))
Output:
Creating the Boxplot graph.
Take the parameters which are required to make boxplot.
Now we draw a graph for the relation between “mpg” and “cyl”.
R
# Plot the chart.boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data")
Output:
Here we are creating multiple boxplots. The individual data for which a boxplot representation is required is based on the function.
R
set.seed(20000) data <- data.frame( A = rpois(900, 3), B = rnorm(900), C = runif(900) ) # Applying boxplot functionboxplot(data)
Output:
To draw a boxplot using a notch:
With the help of notch, we can find out how the medians of different data groups match with each other.
We are using xlab as “Quantity of Cylinders” and ylab as “Miles Per Gallon”.
Python3
# Plot the chart.boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data", notch = TRUE, varwidth = TRUE, col = c("green", "red", "blue"), names = c("High", "Medium", "Low") )
Output:
Akanksha_Rai
kumar_satyam
Picked
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Adding elements in a vector in R programming - append() method
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr | [
{
"code": null,
"e": 29044,
"s": 29016,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 29274,
"s": 29044,
"text": "A box graph is a chart that is used to display information in the form of distribution by drawing boxplots for each of them. This distribution of data based on fiv... |
How to specify a port to run a create-react-app based project ? | 09 Nov, 2021
When we create a new react app using the npx create-react-app command, the default port for the app is 3000. We can access the app from the localhost:3000.
In some situations, users need to run 2 or more react apps on their computer simultaneously but 2 react apps can’t be run on the same port. So, users need to change the default port of one of the react app.
Creating React Application:
Step 1: Create a new react application running the below command to your terminal.
npx create-react-app testapp
Step 2: Move to the project directory by running the below command to the terminal.
cd testapp
Project structure: It will look like this.
Implementation: There are several methods to change the default port of the react app. In this tutorial, we will go through each method one by one.
Note: Following is the common for code all method for root file i.e App.js and output is also given below.
Example:In App.js file, we will add some basic HTML code to render on the webpage.
App.js
import React, { Component } from "react"; class App extends Component { render() { return ( <div> <h1>GeeksForGeeks</h1> <h2>Server is currently running on port 5000</h2> </div> ); }} export default App;
Output:
Method 1: Create an environment variable
This is the simplest method to change the default port of the react app. We need to create the .env file inside the project directory and add the environment variable. Users need to add the below code inside the .env file.
PORT=<specify_port_of_your_choice>
Example:
PORT=5000
Now, run the project using the npm start command, and react app will automatically start to run on the port of your choice.
Method 2: Edit the package.json file
In this method, we have to edit a single line of code inside the package.json file. Here, The user will find the code like “start”: “react-scripts start” inside the “scripts” object. In the below image, you can see the default view of the “scripts” object.
Users need to edit the first line of the “scripts” object and they have to add the below code there.
"start": "set PORT=<specify_port_of_your_choice> && react-scripts start"
Example:
"start": "set PORT=5000 && react-scripts start"
After editing the package.json file, your “scripts” object should look like the below image.
Method 3: Install and add cross-env package
First, we need to install the “cross-env” package in the project directory. So, open the terminal and run the below command inside the project directory.
yarn add -D cross-env
After installing the cross-env package, the user needs to edit the first line of the “scripts” object inside the package.json file. Users need to change the below code by removing the first line inside the “Scripts” object.
"start": "cross-env PORT=<specify_port_of_your_choice> react-scripts start"
Example:
"start": "cross-env PORT=5000 react-scripts start"
Your “Scripts” object should look like the below image after making changes inside the code.
Method 4: Specify port with the run command
In this method, We don’t need to edit any files inside the react app. We have to just mention the port with the run command of the react project. the user has to use the below command to run the project instead of npm start.
PORT=<specify_port_of_your_choice> npm start
Example:
PORT=5000 npm start
When the user will run the react project using the above command, it will start on the port of the user’s choice.
simmytarika5
Picked
React-Questions
ReactJS
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": "\n09 Nov, 2021"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "When we create a new react app using the npx create-react-app command, the default port for the app is 3000. We can access the app from the localhost:3000."
},
{
"code... |
Python program to create a dictionary from a string | 21 Jun, 2020
Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary.So, let us discuss how we can tackle this problem.Method # 1: Using eval()If we get a string input which completely resembles a dictionary object(if the string looks like dictionary as in python) then we can easily convert it to dictionary usingeval() in Python.
# Python3 code to convert # a string to a dictionary # Initializing String string = "{'A':13, 'B':14, 'C':15}" # eval() convert string to dictionaryDict = eval(string)print(Dict)print(Dict['A'])print(Dict['C'])
{'C': 15, 'B': 14, 'A': 13}
13
15
Method # 2: Using generator expressions in pythonIf we get a string input does not completely resemble a dictionary object then we can use generator expressions to convert it to a dictionary.
# Python3 code to convert # a string to a dictionary # Initializing String string = "A - 13, B - 14, C - 15" # Converting string to dictionaryDict = dict((x.strip(), y.strip()) for x, y in (element.split('-') for element in string.split(', '))) print(Dict)print(Dict['A'])print(Dict['C'])
{'C': '15', 'A': '13', 'B': '14'}
13
15
The code given above does not convert integers to an int type,
if integers keys are there then just line 8 would work
string = "11 - 13, 12 - 14, 13 - 15" Dict = dict((x.strip(), int(y.strip())) for x, y in (element.split('-') for element in string.split(', '))) print(Dict)
{'13': 15, '12': 14, '11': 13}
Picked
Python dictionary-programs
Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary.So, let us discuss how we can tackle this ... |
time command in Linux with examples | 13 Aug, 2021
time command in Linux is used to execute a command and prints a summary of real-time, user CPU time and system CPU time spent by executing a command when it terminates. ‘real‘ time is the time elapsed wall clock time taken by a command to get executed, while ‘user‘ and ‘sys‘ time are the number of CPU seconds that command uses in user and kernel mode respectively.
Syntax:
time [option] [COMMAND]
Example:
In the above example, sleep 3 is used to create a dummy job which lasts 3 seconds.
Options:
time -p : This option is used to print time in POSIX format.
help time : it displays help information.
kapoorsagar226
linux-command
Linux-system-commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 421,
"s": 53,
"text": "time command in Linux is used to execute a command and prints a summary of real-time, user CPU time and system CPU time spent by executing a command when it terminates. ‘real... |
How to check the schema of PySpark DataFrame? | 17 Jun, 2021
In this article, we are going to check the schema of pyspark dataframe. We are going to use the below Dataframe for demonstration.
Method 1: Using df.schema
Schema is used to return the columns along with the type.
Syntax: dataframe.schema
Where, dataframe is the input dataframe
Code:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 2"], ["3", "bobby", "company 3"], ["4", "rohith", "company 2"], ["5", "gnanesh", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframe columnsdataframe.schema
Output:
StructType(List(StructField(Employee ID,StringType,true),
StructField(Employee NAME,StringType,true),
StructField(Company Name,StringType,true)))
Method 2: Using schema.fields
It is used to return the names of the columns
Syntax: dataframe.schema.fields
where dataframe is the dataframe name
Code:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 2"], ["3", "bobby", "company 3"], ["4", "rohith", "company 2"], ["5", "gnanesh", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframe columnsdataframe.schema.fields
Output:
[StructField(Employee ID,StringType,true),
StructField(Employee NAME,StringType,true),
StructField(Company Name,StringType,true)]
Method 3: Using printSchema()
It is used to return the schema with column names
Syntax: dataframe.printSchema()
where dataframe is the input pyspark dataframe
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 2"], ["3", "bobby", "company 3"], ["4", "rohith", "company 2"], ["5", "gnanesh", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframe columnsdataframe.printSchema()
Output:
root
|-- Employee ID: string (nullable = true)
|-- Employee NAME: string (nullable = true)
|-- Company Name: string (nullable = true)
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "In this article, we are going to check the schema of pyspark dataframe. We are going to use the below Dataframe for demonstration."
},
{
"code": null,
"e": 185,
... |
Leftmost and rightmost indices of the maximum and the minimum element of an array | 23 Jun, 2022
Given an array arr[], the task is to find the leftmost and the rightmost indices of the minimum and the maximum element from the array where arr[] consists of non-distinct elements.Examples:
Input: arr[] = {2, 1, 1, 2, 1, 5, 6, 5} Output: Minimum left : 1 Minimum right : 4 Maximum left : 6 Maximum right : 6 Minimum element is 1 which is present at indices 1, 2 and 4. Maximum element is 6 which is present only at index 6.Input: arr[] = {0, 1, 0, 2, 7, 5, 6, 7} Output: Minimum left : 0 Minimum right : 2 Maximum left : 4 Maximum right : 7
Method 1: When the array is unsorted.
Initialize the variable leftMin = rightMin = leftMax = rightMax = arr[0] and min = max = arr[0].
Start traversing the array from 1 to n – 1. If arr[i] < min then a new minimum is found. Update leftMin = rightMin = i.Else arr[i] = min then another copy of the current minimum is found. Update the rightMin = i.If arr[i] > max then a new maximum is found. Update leftMax = rightMax = i.Else arr[i] = max then another copy of the current maximum is found. Update the rightMax = i.
If arr[i] < min then a new minimum is found. Update leftMin = rightMin = i.
Else arr[i] = min then another copy of the current minimum is found. Update the rightMin = i.
If arr[i] > max then a new maximum is found. Update leftMax = rightMax = i.
Else arr[i] = max then another copy of the current maximum is found. Update the rightMax = i.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach #include<bits/stdc++.h>using namespace std; void findIndices(int arr[], int n){ int leftMin = 0, rightMin = 0; int leftMax = 0, rightMax = 0; int min = arr[0], max = arr[0]; for (int i = 1; i < n; i++) { // If found new minimum if (arr[i] < min) { leftMin = rightMin = i; min = arr[i]; } // If arr[i] = min then rightmost index // for min will change else if (arr[i] == min) rightMin = i; // If found new maximum if (arr[i] > max) { leftMax = rightMax = i; max = arr[i]; } // If arr[i] = max then rightmost index // for max will change else if (arr[i] == max) rightMax = i; } cout << "Minimum left : " << leftMin << "\n"; cout << "Minimum right : " << rightMin <<"\n"; cout << "Maximum left : " << leftMax <<"\n"; cout << "Maximum right : " << rightMax <<"\n";} // Driver codeint main(){ int arr[] = { 2, 1, 1, 2, 1, 5, 6, 5 }; int n = sizeof(arr)/sizeof(arr[0]); findIndices(arr, n);} // This code is contributed// by ihritik
// Java implementation of the approachpublic class GFG { public static void findIndices(int arr[], int n) { int leftMin = 0, rightMin = 0; int leftMax = 0, rightMax = 0; int min = arr[0], max = arr[0]; for (int i = 1; i < n; i++) { // If found new minimum if (arr[i] < min) { leftMin = rightMin = i; min = arr[i]; } // If arr[i] = min then rightmost index // for min will change else if (arr[i] == min) rightMin = i; // If found new maximum if (arr[i] > max) { leftMax = rightMax = i; max = arr[i]; } // If arr[i] = max then rightmost index // for max will change else if (arr[i] == max) rightMax = i; } System.out.println("Minimum left : " + leftMin); System.out.println("Minimum right : " + rightMin); System.out.println("Maximum left : " + leftMax); System.out.println("Maximum right : " + rightMax); } // Driver code public static void main(String[] args) { int arr[] = { 2, 1, 1, 2, 1, 5, 6, 5 }; int n = arr.length; findIndices(arr, n); }}
# Python3 implementation of the approach def findIndices(arr, n) : leftMin, rightMin = 0, 0 leftMax, rightMax = 0, 0 min_element = arr[0] max_element = arr[0] for i in range(n) : # If found new minimum if (arr[i] < min_element) : leftMin = rightMin = i min_element = arr[i] # If arr[i] = min then rightmost # index for min will change elif (arr[i] == min_element) : rightMin = i # If found new maximum if (arr[i] > max_element) : leftMax = rightMax = i max_element = arr[i] # If arr[i] = max then rightmost # index for max will change elif (arr[i] == max_element) : rightMax = i print("Minimum left : ", leftMin) print("Minimum right : ", rightMin) print("Maximum left : ", leftMax ) print("Maximum right : ", rightMax) # Driver codeif __name__ == "__main__" : arr = [ 2, 1, 1, 2, 1, 5, 6, 5 ] n = len(arr) findIndices(arr, n) # This code is contributed by Ryuga
// C# implementation of the approachusing System;class GFG { static void findIndices(int []arr, int n) { int leftMin = 0, rightMin = 0; int leftMax = 0, rightMax = 0; int min = arr[0], max = arr[0]; for (int i = 1; i < n; i++) { // If found new minimum if (arr[i] < min) { leftMin = rightMin = i; min = arr[i]; } // If arr[i] = min then rightmost index // for min will change else if (arr[i] == min) rightMin = i; // If found new maximum if (arr[i] > max) { leftMax = rightMax = i; max = arr[i]; } // If arr[i] = max then rightmost index // for max will change else if (arr[i] == max) rightMax = i; } Console.WriteLine("Minimum left : " + leftMin); Console.WriteLine("Minimum right : " + rightMin); Console.WriteLine("Maximum left : " + leftMax); Console.WriteLine("Maximum right : " + rightMax); } // Driver code public static void Main() { int []arr = { 2, 1, 1, 2, 1, 5, 6, 5 }; int n = arr.Length; findIndices(arr, n); }}// This code is contributed// By ihritik
<?php// PHP implementation of the approachfunction findIndices($arr, $n){ $leftMin = 0; $rightMin = 0; $leftMax = 0; $rightMax = 0; $min = $arr[0]; $max = $arr[0]; for ($i = 1; $i < $n; $i++) { // If found new minimum if ($arr[$i] < $min) { $leftMin = $rightMin = $i; $min = $arr[$i]; } // If arr[i] = min then rightmost // index for min will change else if ($arr[$i] == $min) $rightMin = $i; // If found new maximum if ($arr[$i] > $max) { $leftMax = $rightMax = $i; $max = $arr[$i]; } // If arr[i] = max then rightmost // index for max will change else if ($arr[$i] == $max) $rightMax = $i; } echo "Minimum left : ", $leftMin, "\n"; echo "Minimum right : ", $rightMin,"\n"; echo "Maximum left : ", $leftMax, "\n"; echo "Maximum right : ", $rightMax, "\n";} // Driver code$arr = array( 2, 1, 1, 2, 1, 5, 6, 5 );$n = sizeof($arr); findIndices($arr, $n); // This code is contributed// by Sachin?>
<script> // Javascript implementation of the approach function findIndices(arr,n) { let leftMin = 0, rightMin = 0; let leftMax = 0, rightMax = 0; let min = arr[0], max = arr[0]; for (let i = 1; i < n; i++) { // If found new minimum if (arr[i] < min) { leftMin = rightMin = i; min = arr[i]; } // If arr[i] = min then rightmost index // for min will change else if (arr[i] == min) rightMin = i; // If found new maximum if (arr[i] > max) { leftMax = rightMax = i; max = arr[i]; } // If arr[i] = max then rightmost index // for max will change else if (arr[i] == max) rightMax = i; } document.write("Minimum left : " + leftMin+"<br>"); document.write("Minimum right : " + rightMin+"<br>"); document.write("Maximum left : " + leftMax+"<br>"); document.write("Maximum right : " + rightMax+"<br>"); } // Driver code let arr=[2, 1, 1, 2, 1, 5, 6, 5 ]; let n = arr.length; findIndices(arr, n); // This code is contributed by unknown2108 </script>
Minimum left : 1
Minimum right : 4
Maximum left : 6
Maximum right : 6
Time Complexity: O(n)Auxiliary Space: O(1)
Method 2: When the array is sorted.
When the array is sorted then leftMin = 0 and rightMax = n – 1.
In order to find the rightMin, apply a modified binary search: Set i = 1.While arr[i] = min update rightMin = i and i = i * 2.Finally do a linear search for the rest of the elements from rightMin + 1 to n – 1 while arr[i] = min.Return rightMin in the end.
Set i = 1.
While arr[i] = min update rightMin = i and i = i * 2.
Finally do a linear search for the rest of the elements from rightMin + 1 to n – 1 while arr[i] = min.
Return rightMin in the end.
Similarly, for leftMax repeat the above steps but in reverse i.e. from n – 1 and update i = i / 2 after every iteration.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above idea#include<bits/stdc++.h>using namespace std; // Function to return the index of the rightmost// minimum element from the arrayint getRightMin(int arr[], int n){ // First element is the minimum in a sorted array int min = arr[0]; int rightMin = 0; int i = 1; while (i < n) { // While the elements are equal to the minimum // update rightMin if (arr[i] == min) rightMin = i; i *= 2; } i = rightMin + 1; // Final check whether there are any elements // which are equal to the minimum while (i < n && arr[i] == min) { rightMin = i; i++; } return rightMin;} // Function to return the index of the leftmost// maximum element from the array int getLeftMax(int arr[], int n){ // Last element is the maximum in a sorted array int max = arr[n - 1]; int leftMax = n - 1; int i = n - 2; while (i > 0) { // While the elements are equal to the maximum // update leftMax if (arr[i] == max) leftMax = i; i /= 2; } i = leftMax - 1; // Final check whether there are any elements // which are equal to the maximum while (i >= 0 && arr[i] == max) { leftMax = i; i--; } return leftMax;} // Driver codeint main(){ int arr[] = { 0, 0, 1, 2, 5, 5, 6, 8, 8 }; int n = sizeof(arr)/sizeof(arr[0]); // First element is the leftmost minimum in a sorted array cout << "Minimum left : " << 0 <<"\n"; cout << "Minimum right : " << getRightMin(arr, n) << "\n"; cout << "Maximum left : " << getLeftMax(arr, n) <<"\n"; // Last element is the rightmost maximum in a sorted array cout << "Maximum right : " << (n - 1);} // This code is contributed by ihritik
// Java implementation of above ideapublic class GFG { // Function to return the index of the rightmost // minimum element from the array public static int getRightMin(int arr[], int n) { // First element is the minimum in a sorted array int min = arr[0]; int rightMin = 0; int i = 1; while (i < n) { // While the elements are equal to the minimum // update rightMin if (arr[i] == min) rightMin = i; i *= 2; } i = rightMin + 1; // Final check whether there are any elements // which are equal to the minimum while (i < n && arr[i] == min) { rightMin = i; i++; } return rightMin; } // Function to return the index of the leftmost // maximum element from the array public static int getLeftMax(int arr[], int n) { // Last element is the maximum in a sorted array int max = arr[n - 1]; int leftMax = n - 1; int i = n - 2; while (i > 0) { // While the elements are equal to the maximum // update leftMax if (arr[i] == max) leftMax = i; i /= 2; } i = leftMax - 1; // Final check whether there are any elements // which are equal to the maximum while (i >= 0 && arr[i] == max) { leftMax = i; i--; } return leftMax; } // Driver code public static void main(String[] args) { int arr[] = { 0, 0, 1, 2, 5, 5, 6, 8, 8 }; int n = arr.length; // First element is the leftmost minimum in a sorted array System.out.println("Minimum left : " + 0); System.out.println("Minimum right : " + getRightMin(arr, n)); System.out.println("Maximum left : " + getLeftMax(arr, n)); // Last element is the rightmost maximum in a sorted array System.out.println("Maximum right : " + (n - 1)); }}
# Python 3 implementation of above idea # Function to return the index of the# rightmost minimum element from the arraydef getRightMin(arr, n): # First element is the minimum # in a sorted array min = arr[0] rightMin = 0 i = 1 while (i < n): # While the elements are equal to # the minimum update rightMin if (arr[i] == min): rightMin = i i *= 2 i = rightMin + 1 # Final check whether there are any # elements which are equal to the minimum while (i < n and arr[i] == min): rightMin = i i += 1 return rightMin # Function to return the index of the# leftmost maximum element from the arraydef getLeftMax(arr, n): # Last element is the maximum # in a sorted array max = arr[n - 1] leftMax = n - 1 i = n - 2 while (i > 0): # While the elements are equal to # the maximum update leftMax if (arr[i] == max): leftMax = i i = int(i / 2) i = leftMax - 1 # Final check whether there are any # elements which are equal to the maximum while (i >= 0 and arr[i] == max): leftMax = i i -= 1 return leftMax # Driver codeif __name__ == '__main__': arr = [0, 0, 1, 2, 5, 5, 6, 8, 8] n = len(arr) # First element is the leftmost # minimum in a sorted array print("Minimum left :", 0) print("Minimum right :", getRightMin(arr, n)) print("Maximum left :", getLeftMax(arr, n)) # Last element is the rightmost maximum # in a sorted array print("Maximum right :", (n - 1)) # This code is contributed by# Surendra_Gangwar
// C# implementation of above idea using System;public class GFG { // Function to return the index of the rightmost // minimum element from the array public static int getRightMin(int []arr, int n) { // First element is the minimum in a sorted array int min = arr[0]; int rightMin = 0; int i = 1; while (i < n) { // While the elements are equal to the minimum // update rightMin if (arr[i] == min) rightMin = i; i *= 2; } i = rightMin + 1; // Final check whether there are any elements // which are equal to the minimum while (i < n && arr[i] == min) { rightMin = i; i++; } return rightMin; } // Function to return the index of the leftmost // maximum element from the array public static int getLeftMax(int []arr, int n) { // Last element is the maximum in a sorted array int max = arr[n - 1]; int leftMax = n - 1; int i = n - 2; while (i > 0) { // While the elements are equal to the maximum // update leftMax if (arr[i] == max) leftMax = i; i /= 2; } i = leftMax - 1; // Final check whether there are any elements // which are equal to the maximum while (i >= 0 && arr[i] == max) { leftMax = i; i--; } return leftMax; } // Driver code public static void Main() { int []arr = { 0, 0, 1, 2, 5, 5, 6, 8, 8 }; int n = arr.Length; // First element is the leftmost minimum in a sorted array Console.WriteLine("Minimum left : " + 0); Console.WriteLine("Minimum right : " + getRightMin(arr, n)); Console.WriteLine("Maximum left : " + getLeftMax(arr, n)); // Last element is the rightmost maximum in a sorted array Console.WriteLine("Maximum right : " + (n - 1)); }} // This code is contributed by ihritik
<?php// PHP implementation of above idea // Function to return the index of the// rightmost minimum element from the arrayfunction getRightMin($arr, $n){ // First element is the minimum // in a sorted array $min = $arr[0]; $rightMin = 0; $i = 1; while ($i < $n) { // While the elements are equal to // the minimum update rightMin if ($arr[$i] == $min) $rightMin = $i; $i *= 2; } $i = $rightMin + 1; // Final check whether there are any // elements which are equal to the minimum while ($i < $n && $arr[$i] == $min) { $rightMin = $i; $i++; } return $rightMin;} // Function to return the index of the// leftmost maximum element from the arrayfunction getLeftMax($arr, $n){ // Last element is the maximum in // a sorted array $max = $arr[$n - 1]; $leftMax = $n - 1; $i = $n - 2; while ($i > 0) { // While the elements are equal to // the maximum update leftMax if ($arr[$i] == $max) $leftMax = $i; $i /= 2; } $i = $leftMax - 1; // Final check whether there are any // elements which are equal to the maximum while ($i >= 0 && $arr[$i] == $max) { $leftMax = $i; $i--; } return $leftMax;} // Driver code$arr = array(0, 0, 1, 2, 5, 5, 6, 8, 8 );$n = sizeof($arr); // First element is the leftmost// minimum in a sorted arrayecho "Minimum left : ", 0, "\n";echo "Minimum right : ", getRightMin($arr, $n), "\n";echo "Maximum left : ", getLeftMax($arr, $n), "\n"; // Last element is the rightmost// maximum in a sorted arrayecho "Maximum right : ", ($n - 1), "\n"; // This code is Contributed// by Mukul singh?>
<script> // Javascript implementation of above idea // Function to return the index of the rightmost // minimum element from the array function getRightMin(arr, n) { // First element is the minimum in a sorted array let min = arr[0]; let rightMin = 0; let i = 1; while (i < n) { // While the elements are equal to the minimum // update rightMin if (arr[i] == min) rightMin = i; i *= 2; } i = rightMin + 1; // Final check whether there are any elements // which are equal to the minimum while (i < n && arr[i] == min) { rightMin = i; i++; } return rightMin; } // Function to return the index of the leftmost // maximum element from the array function getLeftMax(arr, n) { // Last element is the maximum in a sorted array let max = arr[n - 1]; let leftMax = n - 1; let i = n - 2; while (i > 0) { // While the elements are equal to the maximum // update leftMax if (arr[i] == max) leftMax = i; i = parseInt(i / 2, 10); } i = leftMax - 1; // Final check whether there are any elements // which are equal to the maximum while (i >= 0 && arr[i] == max) { leftMax = i; i--; } return leftMax; } let arr = [ 0, 0, 1, 2, 5, 5, 6, 8, 8 ]; let n = arr.length; // First element is the leftmost minimum in a sorted array document.write("Minimum left : " + 0 + "</br>"); document.write("Minimum right : " + getRightMin(arr, n) + "</br>"); document.write("Maximum left : " + getLeftMax(arr, n) + "</br>"); // Last element is the rightmost maximum in a sorted array document.write("Maximum right : " + (n - 1)); // This code is contributed by suresh07.</script>
Minimum left : 0
Minimum right : 1
Maximum left : 7
Maximum right : 8
Time Complexity: O(n) As linear search is applied for a set of elements so the worst case time complexity will be O(n).Auxiliary Space: O(1)
ihritik
ankthon
Sach_Code
Code_Mech
SURENDRA_GANGWAR
unknown2108
suresh07
amankr0211
Arrays
Searching
Sorting
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Binary Search
Search, insert and delete in an unsorted array
Median of two sorted arrays of different sizes
Two Pointers Technique
Search, insert and delete in a sorted array | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 245,
"s": 52,
"text": "Given an array arr[], the task is to find the leftmost and the rightmost indices of the minimum and the maximum element from the array where arr[] consists of non-distinct el... |
Basic configuration of Adaptive Security Appliance (ASA) | 09 Nov, 2021
Prerequisite – Adaptive security appliance (ASA) Adaptive Security Appliance (ASA) is a Cisco security appliance that combines classic firewall features with VPN, Intrusion Prevention, and antivirus capabilities. It has the capability to provide threat defense before the attacks spread into the networks.
As an administrator, we have to ensure protection against unauthorized access to our firewall. We can set login passwords, enable passwords for this. Also, we will discuss configuring an IP address on the ASA interface.
Administrative Configuration –
Bring up the interface and assign an IP address to ASA. To configure an IP address on the interface of an ASA, we have to configure 4 things:
1. Bring up the interface – After entering into global interface mode, use the command no shut to bring up the interface.
2. Assign an IP address to the interface of ASA – After bringing up the interface, assign an IP address by the command
IP address IP_address Subnet_Mask
It’s the same way by which we assign an IP address to the router’s interface. But the difference is that we can assign an IP address to the ASA interface without the subnet mask also.
IP address IP_address
Now, if we don’t give a subnet mask, it automatically takes a classful subnet mask. for example, if we assign 192.168.1.1 to the ASA interface it will automatically take 255.255.255.0 as a subnet mask.
3. Assign a nameif to the ASA interface – In ASA, we also assign a name to the interface otherwise the interface will be down. The most common names are INSIDE OUTSIDE or DMZ. These names are used while applying a policy but have no role in forwarding the traffic. We can assign a name to an ASA interface by the command:
nameif NAME
NAME is the name you want to give to an interface.
4. Assign a security level to the interface – The security level is an integer value ranging from 0 to 100. It tells the trustworthiness of an interface i.e which interface is most trusted. 0 means less trusted while 100 means the most trusted. If we provide the name INSIDE to an interface, it will automatically provide security level 100 to it and if we provide any other name like OUTSIDE or DMZ, it will assign automatically 0 to it but can be changed manually. We can assign a security level to an interface by the command:
Security-level {value}
Here is an example where we will provide IP address 192.268.1.1 and subnet mask 255.255.255.0, name as INSIDE and security-level as 100.
asa(config)#int e0
asa(config-if)#no shut
asa(config-if)#ip address 192.168.1.1 255.255.255.0
asa(config-if)#nameif INSIDE
asa(config-if)#security level 100
Giving hostname to ASA – It is used to set a name to a device stating an identity to a device. It is given by the same command that is used on the router:-
asa(config)#hostname ciscoasa
ciscoasa(config)#
Setting passwords – As ASA is a security device, by default it will ask for a password while we try to enter privilege mode. By default, no password is set therefore by simply clicking enter, we can enter the privilege mode.
enable password – The enable password is used for securing privilege mode. In routers, this password is shown in clear text in running configuration but in ASA, this password is encrypted (therefore no enable secret is required.) The password is a case-sensitive password of up to 16 alphanumeric and special characters. We can set an enable password by
asa(config)#enable password GeeksforGeeks
Or by the command
asa(config)#enable passwd GeeksforGeeks
Where GeeksforGeeks is the password. If we want to disable this password or set a password to default then simply enter the command.
asa(config)#enable password
login password – This password is used for taking access to ASA by using Telnet or SSH. By default, the login password is “Cisco”. We can change it by the command
asa(config)#password GeeksforGeeks
or
asa(config)#passwd GeeksforGeeks
Where GeeksforGeeks is the login password.
Using a local database for login: A local database is configured on the device (username and password) so that it can be used for login purposes. It is configured in the same manner as it is configured on the router. A local database can be configured on the device using the command
asa(config)#username SAURABH password GeeksforGeeks
Where SAURABH is username and password is GeeksforGeeks. If we want the ASA to use its local database for its login purpose then we can use the command
asa(config)#aaa authentication serial console LOCAL
Here, note that LOCAL is case-sensitive
chhabradhanvi
23603vaibhav2021
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
GSM in Wireless Communication
Socket Programming in Python
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 335,
"s": 28,
"text": "Prerequisite – Adaptive security appliance (ASA) Adaptive Security Appliance (ASA) is a Cisco security appliance that combines classic firewall features with VPN, Intrusion Pr... |
Face detection using Cascade Classifier using OpenCV-Python | 18 Oct, 2021
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today’s world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion recognition), video surveillance, etc.
One of the popular algorithms for facial detection is “haarcascade”. It is computationally less expensive, a fast algorithm, and gives high accuracy.
Haarcascade file can be download from here: haarcascade_frontalface_default.xml
It works in four stages:
Haar-feature selection: A Haar-like feature consists of dark regions and light regions. It produces a single value by taking the difference of the sum of the intensities of the dark regions and the sum of the intensities of light regions. It is done to extract useful elements necessary for identifying an object. The features proposed by viola and jones are:
Creation of Integral Images: A given pixel in the integral image is the sum of all the pixels on the left and all the pixels above it. Since the process of extracting Haar-like features involves calculating the difference of dark and light rectangular regions, the introduction of Integral Images reduces the time needed to complete this task significantly.
AdaBoost Training: This algorithm selects the best features from all features. It combines multiple “weak classifiers” (best features) into one “strong classifier”. The generated “strong classifier” is basically the linear combination of all “weak classifiers”.
Cascade Classifier: It is a method for combining increasingly more complex classifiers like AdaBoost in a cascade which allows negative input (non-face) to be quickly discarded while spending more computation on promising or positive face-like regions. It significantly reduces the computation time and makes the process more efficient.
OpenCV comes with lots of pre-trained classifiers. Those XML files can be loaded by cascadeClassifier method of the cv2 module. Here we are going to use haarcascade_frontalface_default.xml for detecting faces.
Step 1: Loading the image
Python
img = cv2.imread('Photos/cric.jpg')
Step 2: Converting the image to grayscale
Initially, the image is a three-layer image (i.e., RGB), So It is converted to a one-layer image (i.e., grayscale).
Python
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Step 3: Loading the required haar-cascade XML classifier file
CascadeClassifier method in cv2 module supports the loading of haar-cascade XML files. Here, we need “haarcascade_frontalface_default.xml” for face detection.
Python
haar_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
Step 4: Applying the face detection method on the grayscale image
This is done using the cv2::CascadeClassifier::detectMultiScale method, which returns boundary rectangles for the detected faces (i.e., x, y, w, h). It takes two parameters namely, scaleFactor and minNeighbors. ScaleFactor determines the factor of increase in window size which initially starts at size “minSize”, and after testing all windows of that size, the window is scaled up by the “scaleFactor”, and the window size goes up to “maxSize”. If the “scaleFactor” is large, (e.g., 2.0), there will be fewer steps, so detection will be faster, but we may miss objects whose size is between two tested scales. (default scale factor is 1.3). Higher the values of the “minNeighbors”, less will be the number of false positives, and less error will be in terms of false detection of faces. However, there is a chance of missing some unclear face traces as well.
Python
faces_rect = haar_cascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=9)
Step 5: Iterating through rectangles of detected faces
Rectangles are drawn around the detected faces by the rectangle method of the cv2 module by iterating over all detected faces.
Python
for (x, y, w, h) in faces_rect: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), thickness=2) cv2.imshow('Detected faces', img)cv2.waitKey(0)
Below is the implementation:
Python
# Importing OpenCV packageimport cv2 # Reading the imageimg = cv2.imread('Photos/cric4.jpg') # Converting image to grayscalegray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Loading the required haar-cascade xml classifier filehaar_cascade = cv2.CascadeClassifier('Haarcascade_frontalface_default.xml') # Applying the face detection method on the grayscale imagefaces_rect = haar_cascade.detectMultiScale(gray_img, 1.1, 9) # Iterating through rectangles of detected facesfor (x, y, w, h) in faces_rect: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow('Detected faces', img) cv2.waitKey(0)
Output:
Picked
Python-OpenCV
TrueGeek-2021
Python
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 442,
"s": 54,
"text": "In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today’s worl... |
How to Convert Kotlin Code to Java Code in Android Studio? | 29 Dec, 2021
Java programming language is the oldest and most preferred language for Android app development. However, during Google I/O 2017, Kotlin has been declared as an official language for Android development by the Google Android Team. Kotlin has gained popularity among developers very quickly because of its similarities as well as interoperable with the Java language. One can mix code of Java and Kotlin while designing an Android project. The syntax of Java and Kotlin differs in many aspects but their compilation process is almost the same. Code of both the languages gets compiled into bytecode that is executable on Java Virtual Machine(JVM). Thus if one can derive the bytecode of compiled Kotlin file, it can be decompiled in order to produce the equivalent Java code. Android Studio does exactly the same to carry out the code conversion from Kotlin to Java. Developers may have many reasons to convert the Kotlin code into Java such as:
To integrate features that are easy to implement in Java language.
To resolve some performance issue that is difficult to locate in Kotlin.
To remove the Kotlin code from the project files.
Step 1: Open Kotlin Class/File
Open the Kotlin Class/File which is to be converted into Java. Consider the code of the MainActivity file mentioned below for the conversion.
Kotlin
import android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // declaring variable for TextView component private var textView: TextView? = null // declaring variable to store // the number of button click private var count = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning ID of textView2 to the variable textView = findViewById(R.id.textView2) // initializing the value of count with 0 count = 0 } // function to perform operations // when button is clicked fun buttonOnClick(view: View?) { // increasing count by one on // each tap on the button count++ // changing the value of the // textView with the current // value of count variable textView!!.text = Integer.toString(count) }}
Step 2: Navigate to Tools Menu
From the topmost toolbar of the Android Studio, select Tools and then navigate to Kotlin > Show Kotlin Bytecode. It will open a window at the right-hand side that will contain the line by line bytecode for the Kotlin file.
Step 3: Decompile bytecode
In the bytecode window, checkbox the option “JVM 8 target” and click on Decompile. The Android Studio will generate the Java equivalent code for the Kotlin file. The produced java code will contain some additional information like metadata. Below is the generated Java code for the above mentioned Kotlin file.
Java
import android.os.Bundle;import android.view.View;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import kotlin.Metadata;import kotlin.jvm.internal.Intrinsics;import org.jetbrains.annotations.Nullable; @Metadata( mv = {1, 4, 1}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000,\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\b\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\u0018\u00002\u00020\u0001B\u0005¢\u0006\u0002\u0010\u0002J\u0010\u0010\u0007\u001a\u00020\b2\b\u0010\t\u001a\u0004\u0018\u00010\nJ\u0012\u0010\u000b\u001a\u00020\b2\b\u0010\f\u001a\u0004\u0018\u00010\rH\u0014R\u000e\u0010\u0003\u001a\u00020\u0004X\u0082\u000e¢\u0006\u0002\n\u0000R\u0010\u0010\u0005\u001a\u0004\u0018\u00010\u0006X\u0082\u000e¢\u0006\u0002\n\u0000 ̈\u0006\u000e"}, d2 = {"Lcom/example/javatokotlin/MainActivity;", "Landroidx/appcompat/app/AppCompatActivity;", "()V", "count", "", "textView", "Landroid/widget/TextView;", "buttonOnClick", "", "view", "Landroid/view/View;", "onCreate", "savedInstanceState", "Landroid/os/Bundle;", "app"})public final class MainActivity extends AppCompatActivity { private TextView textView; private int count; protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(1300009); this.textView = (TextView)this.findViewById(1000069); this.count = 0; } public final void buttonOnClick(@Nullable View view) { int var10001 = this.count++; TextView var10000 = this.textView; Intrinsics.checkNotNull(var10000); var10000.setText((CharSequence)Integer.toString(this.count)); }}
Note: The Kotlin to Java code conversion will not create a new file in the project directory from where one can access the Java code. Thus to use the Android Studio generated Java code, one needs to copy it from the displayed decompiled java file.
Operator overloading is not possible.
Classes written in Java are not made final by default.
More readable syntax.
Use of static methods and variables.
sumitgumber28
android
Technical Scripter 2020
Android
Java
Kotlin
Technical Scripter
TechTips
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 999,
"s": 54,
"text": "Java programming language is the oldest and most preferred language for Android app development. However, during Google I/O 2017, Kotlin has been declared as an official lang... |
Python3 Program for Left Rotation and Right Rotation of a String | 27 May, 2022
Given a string of size n, write functions to perform the following operations on a string-
Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n).
Left (Or anticlockwise) rotate the given string by d elements (where d <= n)
Right (Or clockwise) rotate the given string by d elements (where d <= n).
Examples:
Input : s = "GeeksforGeeks"
d = 2
Output : Left Rotation : "eksforGeeksGe"
Right Rotation : "ksGeeksforGee"
Input : s = "qwertyu"
d = 2
Output : Left rotation : "ertyuqw"
Right rotation : "yuqwert"
A Simple Solution is to use a temporary string to do rotations. For left rotation, first, copy last n-d characters, then copy first d characters in order to the temporary string. For right rotation, first, copy last d characters, then copy n-d characters.
Can we do both rotations in-place and O(n) time? The idea is based on a reversal algorithm for rotation.
// Left rotate string s by d (Assuming d <= n)
leftRotate(s, d)
reverse(s, 0, d-1); // Reverse substring s[0..d-1]
reverse(s, d, n-1); // Reverse substring s[d..n-1]
reverse(s, 0, n-1); // Reverse whole string.
// Right rotate string s by d (Assuming d <= n)
rightRotate(s, d)
// We can also call above reverse steps
// with d = n-d.
leftRotate(s, n-d)
Below is the implementation of the above steps :
Python3
# Python3 program for Left# Rotation and Right# Rotation of a String # In-place rotates s towards left by ddef leftrotate(s, d): tmp = s[d : ] + s[0 : d] return tmp # In-place rotates s# towards right by ddef rightrotate(s, d): return leftrotate(s, len(s) - d) # Driver codeif __name__=="__main__": str1 = "GeeksforGeeks" print(leftrotate(str1, 2)) str2 = "GeeksforGeeks" print(rightrotate(str2, 2)) # This code is contributed by Rutvik_56
Output:
Left rotation: eksforGeeksGe
Right rotation: ksGeeksforGee
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time Auxiliary Space: O(1), as we are not using any extra space.
Please refer complete article on Left Rotation and Right Rotation of a String for more details!
rohitsingh57
rohan07
rotation
Python
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 144,
"s": 53,
"text": "Given a string of size n, write functions to perform the following operations on a string-"
},
{
"code": null,
"e": 295,
"s": 144,
"text": "Left (Or antic... |
Python | Reverse a numpy array | 21 Feb, 2019
As we know Numpy is a general-purpose array-processing package which provides a high-performance multidimensional array object, and tools for working with these arrays. Let’s discuss how can we reverse a numpy array.Method #1: Using shortcut Method
# Python code to demonstrate# how to reverse numpy array# using shortcut method import numpy as np # initialising numpy arrayini_array = np.array([1, 2, 3, 6, 4, 5]) # printing initial ini_arrayprint("initial array", str(ini_array)) # printing type of ini_arrayprint("type of ini_array", type(ini_array)) # using shortcut method to reverseres = ini_array[::-1] # printing resultprint("final array", str(res))
Output:
initial array [1 2 3 6 4 5]
type of ini_array <class 'numpy.ndarray'>
final array [5 4 6 3 2 1]
Method #2: Using flipud function
# Python code to demonstrate# how to reverse numpy array# using flipud method import numpy as np # initialising numpy arrayini_array = np.array([1, 2, 3, 6, 4, 5]) # printing initial ini_arrayprint("initial array", str(ini_array)) # printing type of ini_arrayprint("type of ini_array", type(ini_array)) # using flipud method to reverseres = np.flipud(ini_array) # printing resultprint("final array", str(res))
Output:
initial array [1 2 3 6 4 5]
type of ini_array <class 'numpy.ndarray'>
final array [5 4 6 3 2 1]
Python numpy-arrayManipulation
Python numpy-program
Python-numpy
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
Python String | replace()
How to Install PIP on Windows ?
*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": "\n21 Feb, 2019"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "As we know Numpy is a general-purpose array-processing package which provides a high-performance multidimensional array object, and tools for working with these arrays. Let’s ... |
Python | Sympy Line.perpendicular_line method | 22 Jul, 2021
In Sympy, the function perpendicular_line() is used to create a new Line perpendicular to the given linear entity which passes through the given point p.
Syntax: Line.perpendicular_line(p)
Parameters:
p: Point
Returns:line
Example #1:
Python3
# import sympy and Point, Linefrom sympy import Point, Line p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) l1 = Line(p1, p2) # using perpendicular_line() methodl2 = l1.perpendicular_line(p3) # checking l2 is perpendicular to l1 using is_perpendicular() methodisPerpendicular = l1.is_perpendicular(l2) print(isPerpendicular)
Output:
True
Example #2:
Python3
# import sympy and Point3D, Line3Dfrom sympy import Point3D, Line3D p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0) l1 = Line3D(p1, p2) # using perpendicular_line() methodl2 = l1.perpendicular_line(p3) # checking l2 is perpendicular to l1 using is_perpendicular() methodisPerpendicular = l2 = l1.is_perpendicular(p3) print(isPerpendicular)
Output:
True
kalrap615
Python SymPy-Geometry
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "In Sympy, the function perpendicular_line() is used to create a new Line perpendicular to the given linear entity which passes through the given point p. "
},
{
"code... |
PHP | $_FILES Array (HTTP File Upload variables) | 06 Jun, 2022
How does the PHP file handle know some basic information like file-name, file-size, type of the file and a few attributes about the file which has been selected to be uploaded? Let’s have a look at what is playing behind the scene. $_FILES is a two-dimensional associative global array of items which are being uploaded via the HTTP POST method and holds the attributes of files such as:
Now see How does the array look like??
$_FILES[input-field-name][name]
$_FILES[input-field-name][tmp_name]
$_FILES[input-field-name][size]
$_FILES[input-field-name][type]
$_FILES[input-field-name][error]
Approach: Make sure you have XAMPP or WAMP installed on your machine. In this article, we will be using the XAAMP server.
Let us go through examples, of how this PHP array works in the first example.
Example 1 :
HTML
<?php echo "<pre>";print_r($_FILES);echo "</pre>"; ?> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload Image"></form>
In the above script, before uploading the file
Once when we select the file and upload then the function print_r will display the information of the PHP superglobal associative array $_FILES.
output array
Example 2: Add the HTML code followed by PHP script in different files. Let’s make an HTML form for uploading the file index.html
HTML
<!DOCTYPE html><html> <head> <title>GeeksForGeeks</title> <style type="text/css"> div { background: #4CB974; text-align: center; font-size: 20px; padding: 30px; color: #fff; font-family: sans-serif; } form { border: 1px solid #1f1f1f; padding: 20px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style></head> <body> <form action="file-upload-manager.php" method="post" enctype="multipart/form-data"> <!--multipart/form-data ensures that form data is going to be encoded as MIME data--> <h2>Upload File</h2> <input type="file" name="photo" id="fileSelect"><br><br> <input type="submit" name="submit" value="Upload"><br><br> <!-- name of the input fields are going to be used in our php script--> <div> This Video is made for GFG</div> </form></body> </html>
Now, time to write a PHP script which is able to handle the file uploading system. file-upload-manager.php
PHP
<?php // Check if the form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if file was uploaded without errors if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0) { $file_name = $_FILES["photo"]["name"]; $file_type = $_FILES["photo"]["type"]; $file_size = $_FILES["photo"]["size"]; $file_tmp_name = $_FILES["photo"]["tmp_name"]; $file_error = $_FILES["photo"]["error"]; echo "<div style='text-align: center; background: #4CB974; padding: 30px 0 10px 0; font-size: 20px; color: #fff'> File Name: " . $file_name . "</div>"; echo "<div style='text-align: center; background: #4CB974; padding: 10px; font-size: 20px; color: #fff'> File Type: " . $file_type . "</div>"; echo "<div style='text-align: center; background: #4CB974; padding: 10px; font-size: 20px; color: #fff'> File Size: " . $file_size . "</div>"; echo "<div style='text-align: center; background: #4CB974; padding: 10px; font-size: 20px; color: #fff'> File Error: " . $file_error . "</div>"; echo "<div style='text-align: center; background: #4CB974; padding: 10px; font-size: 20px; color: #fff'> File Temporary Name: " . $file_tmp_name . "</div>"; }}?>
Once we submit the form in the above script, we can later access the information via a PHP superglobal associative array $_FILES. Apart from using the $_FILES array, many in-built functions are playing a major role. After we are done with uploading a file, in the script we will check the request method of the server, if it is POST then it will proceed otherwise the system will throw an error. Later on, we accessed the $_FILES array to get the file name, file size, and type of the file. Once we got those pieces of information print the information of the file using echo.
Output:
Reference: http://php.net/manual/en/reserved.variables.files.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
sanjyotpanure
PHP-file-handling
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 442,
"s": 54,
"text": "How does the PHP file handle know some basic information like file-name, file-size, type of the file and a few attributes about the file which has been selected to be uploade... |
Docker - Containers | Containers are instances of Docker images that can be run using the Docker run command. The basic purpose of Docker is to run containers. Let’s discuss how to work with containers.
Running of containers is managed with the Docker run command. To run a container in an interactive mode, first launch the Docker container.
sudo docker run –it centos /bin/bash
Then hit Crtl+p and you will return to your OS shell.
You will then be running in the instance of the CentOS system on the Ubuntu server.
One can list all of the containers on the machine via the docker ps command. This command is used to return the currently running containers.
docker ps
docker ps
None
The output will show the currently running containers.
sudo docker ps
When we run the above command, it will produce the following result −
Let’s see some more variations of the docker ps command.
This command is used to list all of the containers on the system
docker ps -a
─a − It tells the docker ps command to list all of the containers on the system.
─a − It tells the docker ps command to list all of the containers on the system.
The output will show all containers.
sudo docker ps -a
When we run the above command, it will produce the following result −
With this command, you can see all the commands that were run with an image via a container.
docker history ImageID
ImageID − This is the Image ID for which you want to see all the commands that were run against it.
ImageID − This is the Image ID for which you want to see all the commands that were run against it.
The output will show all the commands run against that image.
sudo docker history centos
The above command will show all the commands that were run against the centos image.
When we run the above command, it will produce the following result −
70 Lectures
12 hours
Anshul Chauhan
41 Lectures
5 hours
AR Shankar
31 Lectures
3 hours
Abhilash Nelson
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
33 Lectures
4 hours
Mumshad Mannambeth
13 Lectures
53 mins
Musab Zayadneh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2521,
"s": 2340,
"text": "Containers are instances of Docker images that can be run using the Docker run command. The basic purpose of Docker is to run containers. Let’s discuss how to work with containers."
},
{
"code": null,
"e": 2661,
"s": 2521,
"text": "R... |
\dfrac - Tex Command | \dfrac - Used to draw fractions.
{ \dfrac #1 #2 }
\dfrac command draws fractions.
\dfrac a b
ab
\frac a b
ab
\dfrac{a-1}b-1
a−1b−1
\dfrac{a-1}{b-1}
a−1b−1
\dfrac a b
ab
\dfrac a b
\frac a b
ab
\frac a b
\dfrac{a-1}b-1
a−1b−1
\dfrac{a-1}b-1
\dfrac{a-1}{b-1}
a−1b−1
\dfrac{a-1}{b-1}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8019,
"s": 7986,
"text": "\\dfrac - Used to draw fractions."
},
{
"code": null,
"e": 8036,
"s": 8019,
"text": "{ \\dfrac #1 #2 }"
},
{
"code": null,
"e": 8068,
"s": 8036,
"text": "\\dfrac command draws fractions."
},
{
"code": null... |
Hierarchical Agglomerative Clustering Algorithm Example In Python | by Cory Maklin | Towards Data Science | Hierarchical clustering algorithms group similar objects into groups called clusters. There are two types of hierarchical clustering algorithms:
Agglomerative — Bottom up approach. Start with many small clusters and merge them together to create bigger clusters.
Divisive — Top down approach. Start with a single cluster than break it up into smaller clusters.
No assumption of a particular number of clusters (i.e. k-means)
May correspond to meaningful taxonomies
Once a decision is made to combine two clusters, it can’t be undone
Too slow for large data sets, O(n2 log(n))
Make each data point a cluster
Make each data point a cluster
2. Take the two closest clusters and make them one cluster
3. Repeat step 2 until there is only one cluster
We can use a dendrogram to visualize the history of groupings and figure out the optimal number of clusters.
Determine the largest vertical distance that doesn’t intersect any of the other clustersDraw a horizontal line at both extremitiesThe optimal number of clusters is equal to the number of vertical lines going through the horizontal line
Determine the largest vertical distance that doesn’t intersect any of the other clusters
Draw a horizontal line at both extremities
The optimal number of clusters is equal to the number of vertical lines going through the horizontal line
For eg., in the below case, best choice for no. of clusters will be 4.
Similar to gradient descent, you can tweak certain parameters to get drastically different results.
The linkage criteria refers to how the distance between clusters is calculated.
The distance between two clusters is the shortest distance between two points in each cluster
The distance between two clusters is the longest distance between two points in each cluster
The distance between clusters is the average distance between each point in one cluster to every point in other cluster
The distance between clusters is the sum of squared differences within all clusters
The method you use to calculate the distance between data points will affect the end result.
The shortest distance between two points. For example, if x=(a,b) and y=(c,d), the Euclidean distance between x and y is √(a−c)2+(b−d)2
Imagine you were in the downtown center of a big city and you wanted to get from point A to point B. You wouldn’t be able to cut across buildings, rather you’d have to make your way by walking along the various streets. For example, if x=(a,b) and y=(c,d), the Manhattan distance between x and y is |a−c|+|b−d|
Let’s take a look at a concrete example of how we could go about labelling data using hierarchical agglomerative clustering.
import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltfrom sklearn.cluster import AgglomerativeClusteringimport scipy.cluster.hierarchy as sch
In this tutorial, we use the csv file containing a list of customers with their gender, age, annual income and spending score.
If you want to follow along, you can get the dataset from the superdatascience website.
www.superdatascience.com
To display our data on a graph at a later point, we can only take two variables (annual income and spending score).
dataset = pd.read_csv('./data.csv')X = dataset.iloc[:, [3, 4]].values
Looking at the dendrogram, the highest vertical distance that doesn’t intersect with any clusters is the middle green one. Given that 5 vertical lines cross the threshold, the optimal number of clusters is 5.
dendrogram = sch.dendrogram(sch.linkage(X, method='ward'))
We create an instance of AgglomerativeClustering using the euclidean distance as the measure of distance between points and ward linkage to calculate the proximity of clusters.
model = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')model.fit(X)labels = model.labels_
The labels_ property returns an array of integers where the values correspond to the distinct categories.
We can use a shorthand notation to display all the samples belonging to a category as a specific color.
plt.scatter(X[labels==0, 0], X[labels==0, 1], s=50, marker='o', color='red')plt.scatter(X[labels==1, 0], X[labels==1, 1], s=50, marker='o', color='blue')plt.scatter(X[labels==2, 0], X[labels==2, 1], s=50, marker='o', color='green')plt.scatter(X[labels==3, 0], X[labels==3, 1], s=50, marker='o', color='purple')plt.scatter(X[labels==4, 0], X[labels==4, 1], s=50, marker='o', color='orange')plt.show() | [
{
"code": null,
"e": 317,
"s": 172,
"text": "Hierarchical clustering algorithms group similar objects into groups called clusters. There are two types of hierarchical clustering algorithms:"
},
{
"code": null,
"e": 435,
"s": 317,
"text": "Agglomerative — Bottom up approach. Start... |
What is the difference between deleteOne() and findOneAndDelete() operation in MongoDB? | The findOneAndDelete() deletes single documents from the collection on the basis of a filter and sort criteria as well as it returns the deleted document.
The deleteOne() removes single document from the collection.
Let us see an example and create a collection with documents −
> db.demo448.insertOne({"Name":"Chris","Age":21});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7a291cbbc41e36cc3caeca")
}
> db.demo448.insertOne({"Name":"David","Age":23});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7a2926bbc41e36cc3caecb")
}
> db.demo448.insertOne({"Name":"Bob","Age":22});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7a2930bbc41e36cc3caecc")
}
Display all documents from a collection with the help of find() method −
> db.demo448.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e7a2926bbc41e36cc3caecb"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }
Following is the query to implement deleteOne() −
> db.demo448.deleteOne({_id:ObjectId("5e7a2926bbc41e36cc3caecb")});
This will produce the following output −
{ "acknowledged" : true, "deletedCount" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo448.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }
Following is the query to implement findOneAndDelete() −
> db.demo448.findOneAndDelete({"_id":ObjectId("5e7a2930bbc41e36cc3caecc")});
This will produce the following output −
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }
Display all documents from a collection with the help of find() method −
> db.demo448.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 } | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "The findOneAndDelete() deletes single documents from the collection on the basis of a filter and sort criteria as well as it returns the deleted document."
},
{
"code": null,
"e": 1278,
"s": 1217,
"text": "The deleteOne() removes sin... |
How to use get parameter in Express.js ? - GeeksforGeeks | 10 Oct, 2021
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UPDATE, etc).
We can create an API endpoint receiving a GET request with the help of app.get() method.
Syntax:
app.get(route, (req, res) => {
// Code logic
});
Route parameters are the name URL segments that capture the value provided at their position. We can access these route parameters on our req.params object using the syntax shown below.
app.get(/:id, (req, res) => {
const id = req.params.id;
});
Project Setup:
Step 1: Install Node.js if you haven’t already.
Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command.
npm init -y
Step 3: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like the following.
app.js
const express = require('express');const app = express(); app.get('/', (req, res) => { res.send('<h1>Home page</h1>');}); app.get('/:id', (req, res) => { res.send(`<h1>${req.params.id}</h1>`);}); app.listen(3000, () => { console.log('Server is up on port 3000');});
Step to run the application: You can run your express server by using the following command on the command line.
node app.js
Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_id and you will view the following output.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
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?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 24844,
"s": 24531,
"text": "Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing... |
Dictionary to list of tuple conversion in Python | ging the collection type from one type to another is a very frequent need in python. In this article we will see how we create a tuple from the key value pairs that are present in a dictionary. Each of the key value pair becomes a tuple. So the final list is a list whose elements are tuples.
We sue the items method of the dictionary which allows us to iterate through each of the key value pairs. Then we use a for loop to pack those values in to a tuple. We put all these tuples to a final list.
Live Demo
dictA = {'Mon': '2 pm', 'Tue': '1 pm', 'Fri': '3 pm'}
# Using items()
res = [(k, v) for k, v in dictA.items()]
# Result
print(res)
Running the above code gives us the following result −
[('Mon', '2 pm'), ('Tue', '1 pm'), ('Fri', '3 pm')]
Another approach is to use the zip function. The zip function will pair the keys and values as tuples and then we convert the entire result to a list by applying list function.
Live Demo
dictA = {'Mon': '2 pm', 'Tue': '1 pm', 'Fri': '3 pm'}
# Using items()
res = list(zip(dictA.keys(), dictA.values()))
# Result
print(res)
Running the above code gives us the following result −
[('Mon', '2 pm'), ('Tue', '1 pm'), ('Fri', '3 pm')]
The append() can append the result into a list after fetching the pair of values to create a tuple. We iterate through a for loop to get the final result.
Live Demo
dictA = {'Mon': '2 pm', 'Tue': '1 pm', 'Fri': '3 pm'}
# Initialize empty list
res=[]
# Append to res
for i in dictA:
tpl = (i, dictA[i])
res.append(tpl)
# Result
print(res)
Running the above code gives us the following result −
[('Mon', '2 pm'), ('Tue', '1 pm'), ('Fri', '3 pm')] | [
{
"code": null,
"e": 1355,
"s": 1062,
"text": "ging the collection type from one type to another is a very frequent need in python. In this article we will see how we create a tuple from the key value pairs that are present in a dictionary. Each of the key value pair becomes a tuple. So the final li... |
R – if-else statement | 18 Oct, 2021
The if-statement in Programming Language alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the R else statement. We can use the else statement with the if statement to execute a block of code when the condition is false.
if (condition)
{
// Executes this block if
// condition is true
} else
{
// Executes this block if
// condition is false
}
Control falls into the if block.
The flow jumps to Condition.
Condition is tested. If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The if-block or the body inside the if is executed.
The else block or the body inside the else is executed.
Flow exits the if-else block.
Example 1:
R
x <- 5 # Check value is less than or greater than 10if(x > 10){ print(paste(x, "is greater than 10"))} else{ print(paste(x, "is less than 10"))}
Output:
[1] "5 is less than 10"
Here in the above code, Firstly, x is initialized to 5, then if-condition is checked(x > 10), and it yields false. Flow enters the else block and prints the statement “5 is less than 10”.
Example 2:
R
x <- 5 # Check if value is equal to 10if(x == 10){ print(paste(x, "is equal to 10"))} else{ print(paste(x, "is not equal to 10"))}
Output:
[1] "5 is not equal to 10"
The if-else statements can be nested together to form a group of statements and evaluate expressions based on the conditions one by one, beginning from the outer condition to the inner one by one respectively. An if-else statement within another if-else statement better justifies the definition.
if(condition1){
# execute only if condition 1 satisfies
if(condition 2){
# execute if both condition 1 and 2 satisfy
}
}else{
}
Example:
R
# creating valuesvar1 <- 6var2 <- 5var3 <- -4 # checking if-else if ladderif(var1 > 10 || var2 < 5){print("condition1")}else{if(var1 <4 ){ print("condition2")}else{ if(var2>10){ print("condition3") } else{ print("condition4") }}}
Output:
[1] "condition4"
kumar_satyam
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 424,
"s": 53,
"text": "The if-statement in Programming Language alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if ... |
Python – datetime.toordinal() Method with Example | 06 Sep, 2021
datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object.
If January 1 of year 1 has ordinal number 1 then, January 2 year 1 will have ordinal number 2, and so on.
Syntax:
datetimeObj.toordinal()
Parameters: None
Returns: Ordinal Value
Given below are some implementations for the same.
Example 1: Use datetime.toordinal() function to return the Gregorian ordinal for the given datetime object using date.today() class of datetime module.
Python3
# Python3 code to demonstrate# Getting Ordinal value using# toordinal(). # importing datetime module for today()import datetime # using date.today() to get todays datedateToday = datetime.date.today() # Using toordinal() to generate ordinal value.toOrdinal = dateToday.toordinal() # Prints Ordinal Value of Todays Date.print(f"Ordinal of date {dateToday} is {toOrdinal}")
Ordinal of date 2021-08-03 is 738005
Note: Attributes of DateTime class should be in given range otherwise it will show a ValueError
Example 2: Example to show the parameters needs to be in the range
Python3
# importing datetime classfrom datetime import datetime # Creating an instance of datetime.dateIs = datetime(189, 0, 0) # Using toordinal() methodtoOrdinal = dateIs.toordinal()print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")
Output:
Traceback (most recent call last):
File “/home/2ecd5f27fbc894dc8eeab3aa6559c7ab.py”, line 5, in <module>
dateIs = datetime(189,0,0)
ValueError: month must be in 1..12
Example 3: Use datetime.toordinal() function to return the Gregorian ordinal for the given DateTime object.
Python3
# importing datetime classfrom datetime import datetime # Creating an instance of datetime.dateIs = datetime(1, 1, 1, 0, 0, 0, 0) # Using toordinal() methodtoOrdinal = dateIs.toordinal()print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}") print() dateIs = datetime(9999, 12, 31, 23, 59, 59)toOrdinal = dateIs.toordinal()print(f"Ordinal value of Latemost Datetime {dateIs} is {toOrdinal}")
Output:
Ordinal value of Earliest Datetime 0001-01-01 00:00:00 is 1
Ordinal value of Latemost Datetime 9999-12-31 23:59:59 is 3652059
sagar0719kumar
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 305,
"s": 52,
"text": "datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has or... |
STL Priority Queue for Structure or Class | 01 Jun, 2022
STL priority_queue is the implementation of Heap Data-structure. By default, it’s a max heap and we can easily use it for primitive datatypes. There are some important applications of it which can be found here
Prerequisite: Prioirty_queue Basics
In this article, we will see how can we use priority_queue for custom datatypes like class or structure. suppose we have a structure name Person which consist of two variables Age and height and we want to store that in priority_queue then a simple method won’t work here.
Given below is an example of the declaration of struct Person:
C++
struct Person{int Age;float Height;}
On defining the Priority Queue as shown below, it’ll give us error since priority_queue doesn’t know on what order(min or max) we need to arrange the objects.
C++
priority_queue<Person> pq;
To rectify the error above, we will use operator overloading to define the priority. So that priority_queue can decide how to store the structure object.
Given below is the priority_queue implementation with the structure below:
C++
// program in c++ to use priority_queue with structure #include <iostream>#include <queue>using namespace std;#define ROW 5#define COL 2 struct Person { int age; float height; // this will used to initialize the variables // of the structure Person(int age, float height) : age(age), height(height) { }}; // this is an structure which implements the// operator overloadingstruct CompareHeight { bool operator()(Person const& p1, Person const& p2) { // return "true" if "p1" is ordered // before "p2", for example: return p1.height < p2.height; }}; int main(){ priority_queue<Person, vector<Person>, CompareHeight> Q; // When we use priority_queue with structure // then we need this kind of syntax where // CompareHeight is the function or comparison function float arr[ROW][COL] = { { 30, 5.5 }, { 25, 5 }, { 20, 6 }, { 33, 6.1 }, { 23, 5.6 } }; for (int i = 0; i < ROW; ++i) { Q.push(Person(arr[i][0], arr[i][1])); // insert an object in priority_queue by using // the Person structure constructor } while (!Q.empty()) { Person p = Q.top(); Q.pop(); cout << p.age << " " << p.height << "\n"; } return 0;}
Output :
33 6.1
20 6
23 5.6
30 5.5
25 5
Given below is the implementation of priority_queue using Class
C++
// program in c++ to use priority_queue with class#include <iostream>#include <queue>using namespace std; #define ROW 5#define COL 2 class Person { public: int age; float height; // this is used to initialize the variables of the class Person(int age, float height) : age(age), height(height) { }}; // we are doing operator overloading through thisbool operator<(const Person& p1, const Person& p2){ // this will return true when second person // has greater height. Suppose we have p1.height=5 // and p2.height=5.5 then the object which // have max height will be at the top(or // max priority) return p1.height < p2.height;} int main(){ priority_queue<Person> Q; float arr[ROW][COL] = { { 30, 5.5 }, { 25, 5 }, { 20, 6 }, { 33, 6.1 }, { 23, 5.6 } }; for (int i = 0; i < ROW; ++i) { Q.push(Person(arr[i][0], arr[i][1])); // insert an object in priority_queue by using // the Person class constructor } while (!Q.empty()) { Person p = Q.top(); Q.pop(); cout << p.age << " " << p.height << "\n"; } return 0;}
Output :
33 6.1
20 6
23 5.6
30 5.5
25 5
Akanksha_Rai
rollo1212
yukty2000
rajeev0719singh
sagartomar9927
vermaabhinav363
cpp-priority-queue
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 265,
"s": 54,
"text": "STL priority_queue is the implementation of Heap Data-structure. By default, it’s a max heap and we can easily use it for primitive datatypes. There are some important applic... |
DateTime.Equals() Method in C# | 16 Dec, 2021
This method is used to get a value indicating whether two DateTime objects, or a DateTime instance and another object or DateTime, have the same value. There are total 3 methods in the overload list of this method:
Equals(DateTime, DateTime)
Equals(DateTime)
Equals(Object)
Equals(DateTime, DateTime)
This method is used to return a value indicating whether two DateTime instances have the same date and time value.
Syntax:
public static bool Equals (DateTime t1, DateTime t2);
Parameters:
t1: The first object to compare.
t2: The second object to compare.
Return Value: This method returns true if the two values are equal; otherwise, false.
Below programs illustrate the use of DateTime.Equals(DateTime, DateTime) Method:
Example 1:
C#
// C# program to demonstrate the// DateTime.Equals(DateTime,// DateTime) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // creating object of DateTime DateTime date2 = new DateTime(2010, 1, 1, 4, 0, 14); // comparing date1 and date2 // using Equals() method; bool value = DateTime.Equals(date1, date2); // checking if (value) Console.Write("date1 is equals to date2. "); else Console.Write("date1 is not equals to date2. "); }}
Output:
date1 is not equals to date2.
Example 2:
C#
// C# program to demonstrate the// DateTime.Equals(DateTime,// DateTime) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15), new DateTime(2010, 1, 4, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15), new DateTime(2010, 1, 4, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15), new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date1, DateTime date2) { // comparing date1 and date2 // using Equals() method; bool value = DateTime.Equals(date1, date2); // checking if (value) Console.WriteLine(" {0:d} is equals to"+ " {1:d}. ", date1, date2); else Console.WriteLine(" {0:d} is not equals"+ " to {1:d}. ", date1, date2); }}
Output:
1/3/2010 is not equals to 1/4/2010.
1/5/2010 is not equals to 1/4/2010.
1/5/2010 is equals to 1/5/2010.
This method is used to return a value indicating whether the value of this instance is equal to the value of the specified DateTime instance.
Syntax:
public bool Equals (DateTime value);
Here, it takes the object to compare to this instance.
Return Value: This method returns true if the value parameter equals the value of this instance; otherwise, false.
Below programs illustrate the use of DateTime.Equals(DateTime) Method:
Example 1:
C#
// C# program to demonstrate the// DateTime.Equals(DateTime) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // creating object of DateTime DateTime date2 = new DateTime(2010, 1, 1, 4, 0, 14); // comparing date1 and date2 // using Equals() method; bool value = date1.Equals(date2); // checking if (value) Console.Write("date1 is equals to date2. "); else Console.Write("date1 is not equals to date2. "); }}
Output:
date1 is not equals to date2.
Example 2:
C#
// C# program to demonstrate the// DateTime.Equals(DateTime) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15), new DateTime(2010, 1, 4, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15), new DateTime(2010, 1, 4, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15), new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date1, DateTime date2) { // comparing date1 and date2 // using Equals() method; bool value = date1.Equals(date2); // checking if (value) Console.WriteLine(" {0:d} is equals to"+ " {1:d}. ", date1, date2); else Console.WriteLine(" {0:d} is not equals "+ "to {1:d}. ", date1, date2); }}
Output:
01/03/2010 is not equals to 01/04/2010.
01/05/2010 is not equals to 01/04/2010.
01/05/2010 is equals to 01/05/2010.
This method is used to return a value indicating whether this instance is equal to a specified object.
Syntax:
public override bool Equals (object value);
Here, it takes the object to compare to this instance.
Return Value: This method returns true if the value parameter equals the value of this instance otherwise it returns false.
Below programs illustrate the use of DateTime.Equals(Object) Method:
Example 1:
C#
// C# program to demonstrate the// DateTime.Equals(DateTime) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // creating object of DateTime DateTime date2 = new DateTime(2010, 1, 1, 4, 0, 14); // comparing date1 and date2 // using Equals() method; bool value = date1.Equals(date2); // checking if (value) Console.Write("date1 is equals to date2. "); else Console.Write("date1 is not equals to date2. "); }}
Output:
date1 is not equals to date2.
Example 2:
C#
// C# program to demonstrate the// DateTime.Equals(DateTime) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15), new DateTime(2010, 1, 4, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15), new DateTime(2010, 1, 4, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15), new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date1, DateTime date2) { // comparing date1 and date2 // using Equals() method; bool value = date1.Equals(date2); // checking if (value) Console.WriteLine(" {0:d} is equals "+ "to {1:d}. ", date1, date2); else Console.WriteLine(" {0:d} is not equals"+ " to {1:d}. ", date1, date2); }}
Output:
01/03/2010 is not equals to 01/04/2010.
01/05/2010 is not equals to 01/04/2010.
01/05/2010 is equals to 01/05/2010.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.equals?view=netframework-4.7.2
rajeev0719singh
sagartomar9927
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "This method is used to get a value indicating whether two DateTime objects, or a DateTime instance and another object or DateTime, have the same value. There are total 3 metho... |
Multiclass image classification using Transfer learning | 23 Jun, 2022
Image classification is one of the supervised machine learning problems which aims to categorize the images of a dataset into their respective categories or labels. Classification of images of various dog breeds is a classic image classification problem. So, we have to classify more than one class that’s why the name multi-class classification, and in this article, we will be doing the same by making use of a pre-trained model InceptionResNetV2, and customizing it.
Let’s first discuss some of the terminologies.
Transfer learning: Transfer learning is a popular deep learning method that follows the approach of using the knowledge that was learned in some task and applying it to solve the problem of the related target task. So, instead of creating a neural network from scratch we “transfer” the learned features which are basically the “weights” of the network. To implement the concept of transfer learning, we make use of “pre-trained models“.
Necessities for transfer learning: Low-level features from model A (task A) should be helpful for learning model B (task B).
Pre-trained model: Pre-trained models are the deep learning models which are trained on very large datasets, developed, and are made available by other developers who want to contribute to this machine learning community to solve similar types of problems. It contains the biases and weights of the neural network representing the features of the dataset it was trained on. The features learned are always transferrable. For example, a model trained on a large dataset of flower images will contain learned features such as corners, edges, shape, color, etc.
InceptionResNetV2: InceptionResNetV2 is a convolutional neural network that is 164 layers deep, trained on millions of images from the ImageNet database, and can classify images into more than 1000 categories such as flowers, animals, etc. The input size of the images is 299-by-299.
Dataset description:
The dataset used comprises of 120 breeds of dogs in total.
Each image has a file name which is its unique id.
Train dataset ( train.zip ): contains 10,222 images which are to be used for training our model
Test dataset (test.zip ): contains 10,357 images which we have to classify into the respective categories or labels.
labels.csv: contains breed names corresponding to the image id.
sample_submission.csv: contains correct form of sample submission to be made
All the above mentioned files can be downloaded from here.
NOTE: For better performance use GPU.
We first import all the necessary libraries.
Python3
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt from sklearn.metrics import classification_report, confusion_matrix # deep learning librariesimport tensorflow as tfimport kerasfrom keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras import applicationsfrom keras.models import Sequential, load_modelfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Flatten, Dense, Dropoutfrom keras.preprocessing import image import cv2 import warningswarnings.filterwarnings('ignore')
Loading datasets and image folders
Python3
from google.colab import drivedrive.mount("/content/drive") # datasetslabels = pd.read_csv("/content/drive/My Drive/dog/labels.csv")sample = pd.read_csv('/content/drive/My Drive/dog/sample_submission.csv') # folders pathstrain_path = "/content/drive/MyDrive/dog/train"test_path = "/content/drive/MyDrive/dog/test"
Displaying the first five records of labels dataset to see its attributes.
Python3
labels.head()
Output:
Adding ‘.jpg’ extension to each id
This is done in order to fetch the images from the folder since the image name and id’s are the same so adding .jpg extension will help us in retrieving images easily.
Python3
def to_jpg(id): return id+".jpg" labels['id'] = labels['id'].apply(to_jpg)sample['id'] = sample['id'].apply(to_jpg)
Augmenting data:
It’s a pre-processing technique in which we augment the existing dataset with transformed versions of the existing images. We can perform scaling, rotations, increasing brightness, and other affine transformations. This is a useful technique as it helps the model to generalize the unseen data well.
ImageDataGenerator class is used for this purpose which provides a real-time augmentation of data.a
Description of few of its parameters that are used below:
rescale: rescales values by the given factor
horizontal flip: randomly flip inputs horizontally.
validation_split: this is the fraction of images reserved for validation (between 0 and 1).
Python3
# Data agumentation and pre-processing using tensorflowgen = ImageDataGenerator( rescale=1./255., horizontal_flip = True, validation_split=0.2 # training: 80% data, validation: 20% data ) train_generator = gen.flow_from_dataframe( labels, # dataframe directory = train_path, # images data path / folder in which images are there x_col = 'id', y_col = 'breed', subset="training", color_mode="rgb", target_size = (331,331), # image height , image width class_mode="categorical", batch_size=32, shuffle=True, seed=42,) validation_generator = gen.flow_from_dataframe( labels, # dataframe directory = train_path, # images data path / folder in which images are there x_col = 'id', y_col = 'breed', subset="validation", color_mode="rgb", target_size = (331,331), # image height , image width class_mode="categorical", batch_size=32, shuffle=True, seed=42,)
Output:
Let’s see what a single batch of data looks like.
Python3
x,y = next(train_generator)x.shape # input shape of one record is (331,331,3) , 32: is the batch size
Output:
(32, 331, 331, 3)
Plotting images from the train dataset
Python3
a = train_generator.class_indicesclass_names = list(a.keys()) # storing class/breed names in a list def plot_images(img, labels): plt.figure(figsize=[15, 10]) for i in range(25): plt.subplot(5, 5, i+1) plt.imshow(img[i]) plt.title(class_names[np.argmax(labels[i])]) plt.axis('off') plot_images(x,y)
Output:
Building our Model
This is the main step where the neural convolution model is built.
Python3
# load the InceptionResNetV2 architecture with imagenet weights as basebase_model = tf.keras.applications.InceptionResNetV2( include_top=False, weights='imagenet', input_shape=(331,331,3) ) base_model.trainable=False# For freezing the layer we make use of layer.trainable = False# means that its internal state will not change during training.# model's trainable weights will not be updated during fit(),# and also its state updates will not run. model = tf.keras.Sequential([ base_model, tf.keras.layers.BatchNormalization(renorm=True), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(120, activation='softmax') ])
BatchNormalization :
It is a normalization technique which is done along mini-batches instead of the full data set.
It is used to speed up training and use higher learning rates.
It maintains the mean output close to 0 and the output standard deviation close to 1.
GlobalAveragePooling2D :
It takes a tensor of size (input width) x (input height) x (input channels) and computes the average value of all values across the entire (input width) x (input height) matrix for each of the (input channels).
The dimensionality of the images is reduced by reducing the number of pixels in the output from the previous neural network layer.
By using this we get a 1-dimensional tensor of size (input channels) as our output.
2D Global average pooling operation. Here ‘Depth’ = ‘Filters’
Dense Layers: These layers are regular fully connected neural network layers connected after the convolutional layers.
Drop out layer: is also used whose function is to randomly drop some neurons from the input unit so as to prevent overfitting. The value of 0.5 indicates that 0.5 fractions of neurons have to be dropped.
Compile the model:
Before training our model we first need to configure it and that is done by model.compile() which defines the loss function, optimizers, and metrics for prediction.
Python3
model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])# categorical cross entropy is taken since its used as a loss function for# multi-class classification problems where there are two or more output labels.# using Adam optimizer for better performance# other optimizers such as sgd can also be used depending upon the model
Displaying a summary report of the model
By displaying the summary we can check our model to confirm that everything is as expected.
Python3
model.summary()
Output:
Defining callbacks to preserve the best results:
Callback: It is an object that can perform actions at various stages of training (for example, at the start or end of an epoch, before or after a single batch, etc).
Python3
early = tf.keras.callbacks.EarlyStopping( patience=10, min_delta=0.001, restore_best_weights=True)# early stopping call back
Training the model: It means that we are finding a set of values for weights and biases that have a low loss on average across all the records.
Python3
batch_size=32STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_sizeSTEP_SIZE_VALID = validation_generator.n//validation_generator.batch_size # fit modelhistory = model.fit(train_generator, steps_per_epoch=STEP_SIZE_TRAIN, validation_data=validation_generator, validation_steps=STEP_SIZE_VALID, epochs=25, callbacks=[early]
Output:
Save the model
We can save the model for further use.
Python3
model.save("Model.h5")
Visualizing the model’s performance
Python3
# store resultsacc = history.history['accuracy']val_acc = history.history['val_accuracy']loss = history.history['loss']val_loss = history.history['val_loss'] # plot results# accuracyplt.figure(figsize=(10, 16))plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['font.size'] = 14plt.rcParams['axes.grid'] = Trueplt.rcParams['figure.facecolor'] = 'white'plt.subplot(2, 1, 1)plt.plot(acc, label='Training Accuracy')plt.plot(val_acc, label='Validation Accuracy')plt.legend(loc='lower right')plt.ylabel('Accuracy')plt.title(f'\nTraining and Validation Accuracy. \nTrain Accuracy: {str(acc[-1])}\nValidation Accuracy: {str(val_acc[-1])}')
Output: Text(0.5, 1.0, ‘\nTraining and Validation Accuracy. \nTrain Accuracy: 0.9448809027671814\nValidation Accuracy: 0.9022817611694336’)
Python3
# lossplt.subplot(2, 1, 2)plt.plot(loss, label='Training Loss')plt.plot(val_loss, label='Validation Loss')plt.legend(loc='upper right')plt.ylabel('Cross Entropy')plt.title(f'Training and Validation Loss. \nTrain Loss: {str(loss[-1])}\nValidation Loss: {str(val_loss[-1])}')plt.xlabel('epoch')plt.tight_layout(pad=3.0)plt.show()
Output:
A line graph of training vs validation accuracy and loss was also plotted. The graph indicates that the accuracies of validation and training were almost consistent with each other and above 90%. The loss of the CNN model is a negative lagging graph which indicates that the model is behaving as expected with a reducing loss after each epoch.
Evaluating the accuracy of the model
Python3
accuracy_score = model.evaluate(validation_generator)print(accuracy_score)print("Accuracy: {:.4f}%".format(accuracy_score[1] * 100)) print("Loss: ",accuracy_score[0])
Output:
Viewing the Test Image
Python3
test_img_path = test_path+"/000621fb3cbb32d8935728e48679680e.jpg" img = cv2.imread(test_img_path)resized_img = cv2.resize(img, (331, 331)).reshape(-1, 331, 331, 3)/255 plt.figure(figsize=(6,6))plt.title("TEST IMAGE")plt.imshow(resized_img[0])
Output:
Making predictions on the test data
Python3
predictions = [] for image in sample.id: img = tf.keras.preprocessing.image.load_img(test_path +'/'+ image) img = tf.keras.preprocessing.image.img_to_array(img) img = tf.keras.preprocessing.image.smart_resize(img, (331, 331)) img = tf.reshape(img, (-1, 331, 331, 3)) prediction = model.predict(img/255) predictions.append(np.argmax(prediction)) my_submission = pd.DataFrame({'image_id': sample.id, 'label': predictions})my_submission.to_csv('submission.csv', index=False) # Submission file ouputprint("Submission File: \n---------------\n")print(my_submission.head()) # Displaying first five predicted output
Output:
jatingrg2399
Deep-Learning
Machine Learning
Python
Software Engineering
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 524,
"s": 54,
"text": "Image classification is one of the supervised machine learning problems which aims to categorize the images of a dataset into their respective categories or labels. Classific... |
Large Fibonacci Numbers in Java | 20 Oct, 2020
Given a number n, find n-th Fibonacci Number. Note that n may be large.
Examples:
Input : 100
Output : 354224848179261915075
Input : 500
Output : 139423224561697880139724382870
407283950070256587697307264108962948325571622
863290691557658876222521294125
Prerequisite: BigInteger Class in Java, Fibonacci numbersFibonacci of large number may contain more than 100 digits, it can be easily handled by BigInteger in Java. BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.
JAVA
// Java program to compute n-th Fibonacci// number where n may be large.import java.io.*;import java.util.*;import java.math.*; public class Fibonacci{ // Returns n-th Fibonacci number static BigInteger fib(int n) { BigInteger a = BigInteger.valueOf(0); BigInteger b = BigInteger.valueOf(1); BigInteger c = BigInteger.valueOf(1); for (int j=2 ; j<=n ; j++) { c = a.add(b); a = b; b = c; } return (b); } public static void main(String[] args) { int n = 100; System.out.println("Fibonacci of " + n + "th term" + " " +"is" +" " + fib(n)); }}
Fibonacci of 100th term is 354224848179261915075
Note that the above solution takes O(n) time, we can find the n-th Fibonacci number in O(log n) time. As an exercise, find the n-th Fibonacci number for large n in O(log n) time.This article is contriBigInteger.valueOf (1);but by Pramod 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.
nutan1510
Fibonacci
large-numbers
Java
Mathematical
Mathematical
Java
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 125,
"s": 53,
"text": "Given a number n, find n-th Fibonacci Number. Note that n may be large."
},
{
"code": null,
"e": 135,
"s": 125,
"text": "Examples:"
},
{
"code": n... |
How to send email with Nodemailer using Gmail account in Node.js ? | 13 Jun, 2022
Nodemailer is the Node.js npm module that allows to send email easily. In this article, we will cover each steps to send email using Gmail account with the help of nodemailer.
Installations: Go to the project folder and use the following command.
Create a package.json file.
npm init -y
Install nodemailer
npm install nodemailer -S
Create server.js file directly or use command
touch server.js
Approach:
Include the nodemailer module in the code using require(‘nodemailer’).
Use nodemailer.createTransport() function to create a transporter who will send mail. It contains the service name and authentication details (user ans password).
Declare a variable mailDetails that contains the sender and receiver email id, subject and content of the mail.
Use mailTransporter.sendMail() function to send email from sender to receiver. If message sending failed or contains error then it will display error message otherwise message send successfully.
Example:
javascript
const nodemailer = require('nodemailer'); let mailTransporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'xyz@gmail.com', pass: '*************' }}); let mailDetails = { from: 'xyz@gmail.com', to: 'abc@gmail.com', subject: 'Test mail', text: 'Node.js testing mail for GeeksforGeeks'}; mailTransporter.sendMail(mailDetails, function(err, data) { if(err) { console.log('Error Occurs'); } else { console.log('Email sent successfully'); }});
Now open the link https://myaccount.google.com/lesssecureapps to Allow less secure apps: ON. Then use node server.js command to run the above code. It will send the email using gmail account.
Output:
Terminal to run code:
Sent mail:
Note 1: To use this code in any file we just have to import this file and call send() function.
var mail = require('./config/mailer')();
mail.send();
Note 2: To send HTML formatted text in your email, use the “html” property instead of the “text” property in sendMail function.
{ from:'"admin" ',
to: "user@gmail.com",
subject:'GeeksforGeeks Promotion',
html:' <p> html code </p>'
}
Note 3: To send an email to more than one receiver, add them to the “to” property in sendMail function, separated by commas.
{ from:'”admin” ‘,
to: ” user1@gmail.com, user2@gmail.com, user3@yahoo.in “,
subject:’GeeksforGeeks Promotion’,
text:’Check out GeeksforGeeks’+’best site to prepare for interviews and competitive exams.’
}
alphaenlightner
Node.js-Basics
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": "\n13 Jun, 2022"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "Nodemailer is the Node.js npm module that allows to send email easily. In this article, we will cover each steps to send email using Gmail account with the help of nodemailer.... |
How to plot an angle in Python using Matplotlib ? | 04 Feb, 2021
In this article, we will learn how to plot an angle in Python. As we know that to draw an angle, there must be two intersecting lines so that angle can be made between those two lines at an intersecting point. In this, we plot an angle on two Intersecting Straight lines. So, lets first discuss some concepts :
NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays.
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
In this matplotlib is used to plot angle graphically and it fits best with Numpy whereas NumPy is numerical Python which is used to perform Advance Mathematics.
Plot two Intersecting lines.Find the point of Intersection marked with a color.Plot a circle in such a way that the point of Intersection of two lines is the same as Center of Circle.Mark it as a point where the circle will intersect with straight lines and plot that two points where we find the angle between them.Calculate the angle and plot the angle.
Plot two Intersecting lines.
Find the point of Intersection marked with a color.
Plot a circle in such a way that the point of Intersection of two lines is the same as Center of Circle.
Mark it as a point where the circle will intersect with straight lines and plot that two points where we find the angle between them.
Calculate the angle and plot the angle.
1. Plot two Intersecting lines
In this, the first two lines of Code shows that matplotlib and NumPy Framework of Python is imported, from where we will use inbuilt functions in further code.
After that, the slope and intercept are taken in order to plot two Straight lines. After that line-space ( l ) returns number spaces evenly with respect to the interval.
After that plt.figure() is used to create the area where we plot the angle and it’s dimension is given in the code.
After that In order to plot the Straight lines, we have to define the axis. Here : X-axis : 0-6 and Y-axis : 0-6
The title is given to the figure box using plt.title().
After that two lines are plotted as shown in the output below:
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # slope and interceptsa1, b1 = (1/4), 1.0a2, b2 = (3/4), 0.0 # The numpy.linspace() function returns# number spaces evenly w.r.t intervall = np.linspace(-6, 6, 100) # use to create new figureplt.figure(figsize=(8, 8)) # plottingplt.xlim(0, 6)plt.ylim(0, 6)plt.title('Plot an angle using Python')plt.plot(l, l*a1+b1)plt.plot(l, l*a2+b2)plt.show()
Output :
2. Find the point of Intersection and marked with a color
Here x0,y0 denote the intersecting point of two Straight lines. The plotted two Straight lines are written as :
y1 = a1*x + b1
y2 = a2*x + b2.
On solving the above equations we get,
x0 = (b2-b1) / (a1-a2) -(i)
y0 =a1*x0 + b1 -(ii)
From above equation (i) and (ii) we will get the point of intersection of Two Straight lines and after that, the color =’midnightblue’ is assigned to the point of intersection using plot.scatter() function.
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # slope and interceptsa1, b1 = (1/4), 1.0a2, b2 = (3/4), 0.0 # The numpy.linspace() function returns# number spaces evenly w.r.t intervall = np.linspace(-6, 6, 100) # use to create new figureplt.figure(figsize=(8, 8)) # plottingplt.xlim(0, 6)plt.ylim(0, 6)plt.title('Plot an angle using Python')plt.plot(l, l*a1+b1)plt.plot(l, l*a2+b2) # intersection pointx0 = (b2-b1)/(a1-a2)y0 = a1*x0 + b1plt.scatter(x0, y0, color='midnightblue')
Output:
3. Plot a circle in such a way that the point of intersection of two lines is the same as the Center of Circle
Here we plot a circle using the parametric equation of a Circle. The parametric equation of a circle is :
x1= r*cos(theta)
x2=r*sin(theta)
If we want that the circle is not in the origin then we use :
x1= r*cos(theta) + h
x2=r*sin(theta) + k
Here h and k are the coordinates of the center of the circle. So we use this above equation where h =x0 and k =y0 as shown. Also, here we provide the color to the circle ” blue” and its style is marked as “dotted”.
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # slope and interceptsa1, b1 = (1/4), 1.0a2, b2 = (3/4), 0.0 # The numpy.linspace() function returns# number spaces evenly w.r.t intervall = np.linspace(-6, 6, 100) # use to create new figureplt.figure(figsize=(8, 8)) # plottingplt.xlim(0, 6)plt.ylim(0, 6)plt.title('Plot an angle using Python')plt.plot(l, l*a1+b1)plt.plot(l, l*a2+b2) # intersection pointx0 = (b2-b1)/(a1-a2)y0 = a1*x0 + b1plt.scatter(x0, y0, color='midnightblue') # circle for angletheta = np.linspace(0, 2*np.pi, 100)r = 1.0x1 = r * np.cos(theta) + x0x2 = r * np.sin(theta) + y0plt.plot(x1, x2, color='green', linestyle='dotted')
Output:
4. Mark it as a point where the circle will intersect with straight lines and plot those two points where we find the angle between them
Now, let’s find the points where the circle is intersecting the two straight lines. Read the comments below and understand how to mark points. After that color i.e. “crimson” color is provided where the circle will intersect two straight lines. After that names are provided to the points as Point_P1, Point_P2 where we find the angle between them and marked it as black colored as shown in the output.
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # slope and interceptsa1, b1 = (1/4), 1.0a2, b2 = (3/4), 0.0 # The numpy.linspace() function returns# number spaces evenly w.r.t intervall = np.linspace(-6, 6, 100) # use to create new figureplt.figure(figsize=(8, 8)) # plottingplt.xlim(0, 6)plt.ylim(0, 6)plt.title('Plot an angle using Python')plt.plot(l, l*a1+b1)plt.plot(l, l*a2+b2) # intersection pointx0 = (b2-b1)/(a1-a2)y0 = a1*x0 + b1plt.scatter(x0, y0, color='midnightblue') # circle for angletheta = np.linspace(0, 2*np.pi, 100)r = 1.0x1 = r * np.cos(theta) + x0x2 = r * np.sin(theta) + y0plt.plot(x1, x2, color='green', linestyle='dotted') # intersection pointsx_points = []y_points = [] # Code for Intersecting points of circle with Straight Linesdef intersection_points(slope, intercept, x0, y0, radius): a = 1 + slope**2 b = -2.0*x0 + 2*slope*(intercept - y0) c = x0**2 + (intercept-y0)**2 - radius**2 # solving the quadratic equation: delta = b**2 - 4.0*a*c # b^2 - 4ac x1 = (-b + np.sqrt(delta)) / (2.0 * a) x2 = (-b - np.sqrt(delta)) / (2.0 * a) x_points.append(x1) x_points.append(x2) y1 = slope*x1 + intercept y2 = slope*x2 + intercept y_points.append(y1) y_points.append(y2) return None # Finding the intersection points for line1 with circleintersection_points(a1, b1, x0, y0, r) # Finding the intersection points for line1 with circleintersection_points(a2, b2, x0, y0, r) # Here we plot Two points in order to find angle between themplt.scatter(x_points[0], y_points[0], color='crimson')plt.scatter(x_points[2], y_points[2], color='crimson') # Naming the points.plt.text(x_points[0], y_points[0], ' Point_P1', color='black')plt.text(x_points[2], y_points[2], ' Point_P2', color='black')
Output:
5. Calculate the angle and Plot Angle
In the below code the angle between to points Point_P1 and Point_P2 is calculated and finally, it is plotted as shown in the output.
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np # slope and interceptsa1, b1 = (1/4), 1.0a2, b2 = (3/4), 0.0 # The numpy.linspace() function returns# number spaces evenly w.r.t intervall = np.linspace(-6, 6, 100) # use to create new figureplt.figure(figsize=(8, 8)) # plottingplt.xlim(0, 6)plt.ylim(0, 6)plt.title('Plot an angle using Python')plt.plot(l, l*a1+b1)plt.plot(l, l*a2+b2) # intersection pointx0 = (b2-b1)/(a1-a2)y0 = a1*x0 + b1plt.scatter(x0, y0, color='midnightblue') # circle for angletheta = np.linspace(0, 2*np.pi, 100)r = 1.0x1 = r * np.cos(theta) + x0x2 = r * np.sin(theta) + y0plt.plot(x1, x2, color='green', linestyle='dotted') # intersection pointsx_points = []y_points = [] # Code for Intersecting points of circle with Straight Linesdef intersection_points(slope, intercept, x0, y0, radius): a = 1 + slope**2 b = -2.0*x0 + 2*slope*(intercept - y0) c = x0**2 + (intercept-y0)**2 - radius**2 # solving the quadratic equation: delta = b**2 - 4.0*a*c # b^2 - 4ac x1 = (-b + np.sqrt(delta)) / (2.0 * a) x2 = (-b - np.sqrt(delta)) / (2.0 * a) x_points.append(x1) x_points.append(x2) y1 = slope*x1 + intercept y2 = slope*x2 + intercept y_points.append(y1) y_points.append(y2) return None # Finding the intersection points for line1 with circleintersection_points(a1, b1, x0, y0, r) # Finding the intersection points for line1 with circleintersection_points(a2, b2, x0, y0, r) # Here we plot Two ponts in order to find angle between themplt.scatter(x_points[0], y_points[0], color='crimson')plt.scatter(x_points[2], y_points[2], color='crimson') # Naming the points.plt.text(x_points[0], y_points[0], ' Point_P1', color='black')plt.text(x_points[2], y_points[2], ' Point_P2', color='black') # plot angle value def get_angle(x, y, x0, y0, radius): base = x - x0 hypotenuse = radius # calculating the angle for a intersection point # which is equal to the cosine inverse of (base / hypotenuse) theta = np.arccos(base / hypotenuse) if y-y0 < 0: theta = 2*np.pi - theta print('theta=', theta, ',theta in degree=', np.rad2deg(theta), '\n') return theta theta_list = [] for i in range(len(x_points)): x = x_points[i] y = y_points[i] print('intersection point p{}'.format(i)) theta_list.append(get_angle(x, y, x0, y0, r)) # angle for intersection point1 ( here point p1 is taken)p1 = theta_list[0] # angle for intersection point2 ( here point p4 is taken)p2 = theta_list[2] # all the angles between the two intersection pointstheta = np.linspace(p1, p2, 100) # calculate the x and y points for# each angle between the two intersection pointsx1 = r * np.cos(theta) + x0x2 = r * np.sin(theta) + y0 # plot the angleplt.plot(x1, x2, color='black') # Code to print the angle at the midpoint of the arc.mid_angle = (p1 + p2) / 2.0 x_mid_angle = (r-0.5) * np.cos(mid_angle) + x0y_mid_angle = (r-0.5) * np.sin(mid_angle) + y0 angle_in_degree = round(np.rad2deg(abs(p1-p2)), 1) plt.text(x_mid_angle, y_mid_angle, angle_in_degree, fontsize=12) # plotting the intersection pointsplt.scatter(x_points[0], y_points[0], color='red')plt.scatter(x_points[2], y_points[2], color='red')plt.show()
Output:
arorakashish0911
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "In this article, we will learn how to plot an angle in Python. As we know that to draw an angle, there must be two intersecting lines so that angle can be made between those t... |
Rotate axis tick labels in Seaborn and Matplotlib | 25 Feb, 2021
Seaborn and Matplotlib both are commonly used libraries for data visualization in Python. We can draw various types of plots using Matplotlib like scatter, line, bar, histogram, and many more. On the other hand, Seaborn provides a variety of visualization patterns. It uses easy syntax and has easily interesting default themes. It specializes in statistics visualization.
Creating a basic plot in Matplotlib
Python3
import numpy as npimport matplotlib.pyplot as plt data = {'Cristopher': 20, 'Agara': 15, 'Jayson': 30, 'Peter': 35}names = list(data.keys())age = list(data.values()) fig = plt.figure(figsize=(10, 5)) # creating the bar plotplt.bar(names, age, color='blue', width=0.4) plt.xlabel("Names")plt.ylabel("Age of the person")plt.show()
Output:
Creating basic plot in Seaborn
Python3
import seaborn as snsimport matplotlib.pyplot as plt sns.barplot(x=["Asia", "Africa", "Antartica", "Europe"], y=[90, 60, 30, 10]) plt.show()
Output:
While plotting these plots one problem arises -the overlapping of x labels or y labels which causes difficulty to read what is on x-label and what is on y-label. So we solve this problem by Rotating x-axis labels or y-axis labels.
Rotating X-axis Labels in Matplotlib
We use plt.xticks(rotation=#) where # can be any angle by which we want to rotate the x labels
Python3
import numpy as npimport matplotlib.pyplot as plt data = {'Cristopher': 20, 'Agara': 15, 'Jayson': 30, 'Peter': 35}names = list(data.keys())age = list(data.values()) fig = plt.figure(figsize=(10, 5)) # creating the bar plotplt.bar(names, age, color='blue', width=0.4) plt.xlabel("Names")plt.xticks(rotation=45)plt.ylabel("Age of the person")plt.show()
Output:
Rotating X-axis Labels in Seaborn
By using FacetGrid we assign barplot to variable ‘g’ and then we call the function set_xticklabels(labels=#list of labels on x-axis, rotation=*) where * can be any angle by which we want to rotate the x labels
Python3
import seaborn as snsimport matplotlib.pyplot as plt g = sns.barplot(x=["Asia", "Africa", "Antartica", "Europe"], y=[90, 30, 60, 10])g.set_xticklabels( labels=["Asia", "Africa", "Antartica", "Europe"], rotation=30)# Show the plotplt.show()
Output:
Rotating Y-axis Labels in Matplotlib
We use plt.xticks(rotation=#) where # can be any angle by which we want to rotate the y labels
Python3
import numpy as npimport matplotlib.pyplot as plt data = {'Cristopher': 20, 'Agara': 15, 'Jayson': 30, 'Peter': 35}courses = list(data.keys())values = list(data.values()) fig = plt.figure(figsize=(8, 5)) # creating the bar plotplt.bar(courses, values, color='blue', width=0.4)plt.yticks(rotation=45)plt.xlabel("Names")plt.ylabel("Age of the person")plt.show()
Output:
Rotating Y-axis Labels in Seaborn
By using FacetGrid we assign barplot to variable ‘g’ and then we call the function set_yticklabels(labels=#the scale we want for y label, rotation=*) where * can be any angle by which we want to rotate the y labels
Python3
import seaborn as snsimport matplotlib.pyplot as plt g = sns.barplot(x=["Asia", "Africa", "Antartica", "Europe"], y=[90, 30, 60, 10]) g.set_yticklabels(labels=[0, 20, 40, 60, 80], rotation=30) # Show the plotplt.show()
Output:
Picked
Python-matplotlib
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 402,
"s": 28,
"text": "Seaborn and Matplotlib both are commonly used libraries for data visualization in Python. We can draw various types of plots using Matplotlib like scatter, line, bar, histogr... |
Naming a thread and fetching name of current thread in C# | 24 Jan, 2019
A thread is a light-weight process within a process. In C#, a user is allowed to assign a name to the thread and also find the name of the current working thread by using the Thread.Name property of the Thread class.
Syntax :
public string Name { get; set; }
Here, the string contains the name of the thread or null if no name was assigned or set.
Important Points:
The by default value of the Name property is null.
The string given to the name property can include any Unicode Character.
The name property of Thread class is write-once.
If a set operation was requested, but the Name property has already set, then it will give InvalidOperationException.
Example 1:
// C# program to illustrate the // concept of assigning names // to the thread and fetching// name of the current working threadusing System;using System.Threading; class Geek { // Method of Geek class public void value() { // Fetching the name of // the current thread // Using Name property Thread thr = Thread.CurrentThread; Console.WriteLine("The name of the current "+ "thread is: " + thr.Name); }} // Driver classpublic class GFG { // Main Method static public void Main() { // Creating object of Geek class Geek obj = new Geek(); // Creating and initializing threads Thread thr1 = new Thread(obj.value); Thread thr2 = new Thread(obj.value); Thread thr3 = new Thread(obj.value); Thread thr4 = new Thread(obj.value); // Assigning the names of the threads // Using Name property thr1.Name = "Geeks1"; thr2.Name = "Geeks2"; thr3.Name = "Geeks3"; thr4.Name = "Geeks4"; thr1.Start(); thr2.Start(); thr3.Start(); thr4.Start(); }}
Output:
The name of the current thread is: Geeks2
The name of the current thread is: Geeks3
The name of the current thread is: Geeks4
The name of the current thread is: Geeks1
Example 2:
// C# program to illustrate the // concept of giving a name to threadusing System;using System.Threading; class Name { static void Main() { // Check whether the thread // has already been named // to avoid InvalidOperationException if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "MyThread"; Console.WriteLine("The name of the thread is MyThread"); } else { Console.WriteLine("Unable to name the given thread"); } }}
Output:
The name of the thread is MyThread
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.name?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
C# Dictionary with examples
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2019"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "A thread is a light-weight process within a process. In C#, a user is allowed to assign a name to the thread and also find the name of the current working thread by using the ... |
Pandas read_table() function | 19 Jun, 2020
Pandas is one of the most used packages for analyzing data, data exploration, and manipulation. While analyzing the real-world data, we often use the URLs to perform different operations and pandas provide multiple methods to do so. One of those methods is read_table().
Parameters:read_table(filepath_or_buffer, sep=False, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar='”‘, quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)
Returns: A comma(‘,’) separated values file(csv) is returned as two dimensional data with labelled axes.
To get the link to csv file used in the article, click here. Code #1: Display the whole content of the file with columns separated by ‘,’
# importing pandasimport pandas as pd pd.read_table('nba.csv',delimiter=',')
Output:
Code #2: Skipping rows without indexing
# importing pandasimport pandas as pd pd.read_table('nba.csv',delimiter=',',skiprows=4,index_col=0)
Output:
In the above code, four rows are skipped and the last skipped row is displayed.
Code #3: Skipping rows with indexing
# importing pandasimport pandas as pd pd.read_table('nba.csv',delimiter=',',skiprows=4)
Output:
Code #4: In case of large file, if you want to read only few lines then give required number of lines to nrows.
# importing pandasimport pandas as pd pd.read_table('nba.csv',delimiter=',',index_col=0,nrows=4)
Output:
Code #5: If you want to skip lines from bottom of file then give required number of lines to skipfooter.
# importing pandasimport pandas as pd pd.read_table('nba.csv',delimiter=',',index_col=0, engine='python',skipfooter=5)
Output:
Code #6: Row number(s) to use as the column names, and the start of the data occurs after the last row number given in header.
# importing pandasimport pandas as pd pd.read_table('nba.csv',delimiter=',',index_col=0,header=[1,3,5])
Output:
nidhi_biet
Pandas Panel-functions
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "Pandas is one of the most used packages for analyzing data, data exploration, and manipulation. While analyzing the real-world data, we often use the URLs to perform different... |
How to combine two lists in R? - GeeksforGeeks | 30 May, 2021
In this article, we are going to combine two lists in R Language using inbuilt functions. R provided two inbuilt functions named c() and append() to combine two or more lists.
Method 1: Using c() function
c() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.
Syntax:
c(list1, list2)
Example 1:
R
# R Program to combine two lists # Creating Lists using the list() functionList1 <- list(1:5)List2 <- list(6:10) print(List1)print(List2) # Combining lists using c() functionList3 = c(List1, List2)print(List3)
Output:
Here, you can see that the second list has 2 elements, which shows that there are two lists combined as one.
Example 2:
R
# R Program to combine two lists # Creating Lists using the list() functionList1 <- list(1, 2, 3)List2 <- list('a', 'b', 'c') # Combining lists using c() functionList3 = c(List1, List2)print(List3)
Output:
Method 2: Using append() function
append() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.
Syntax:
append(list1, list2)
Example 1:
R
# R Program to combine two lists # Creating Lists using the list() functionList1 <- list(1:5)List2 <- list(6:10) print(List1)print(List2) # Combining lists using append() functionList3 = append(List1, List2)print(List3)
Output:
Example 2:
R
# R Program to combine two lists # Creating Lists using the list() functionList1 <- list(1, 2, 3)List2 <- list('a', 'b', 'c') # Combining lists using append() functionList3 = append(List1, List2)print(List3)
Output:
Picked
R List-Programs
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 26315,
"s": 26139,
"text": "In this article, we are going to combine two lists in R Language using inbuilt functions. R provided two inbuilt functions named c() and append() to combine two or... |
Scrollable Frames in Tkinter - GeeksforGeeks | 04 Mar, 2021
A scrollbar is a widget that is useful to scroll the text in another widget. For example, the text in Text, Canvas Frame or Listbox can be scrolled from top to bottom or left to right using scrollbars. There are two types of scrollbars. They are horizontal and vertical. The horizontal scrollbar is useful to view the text from left to right. The vertical scrollbar is useful to scroll the text from top to bottom.Now let us see how we can create a scrollbar. To create a scrollbar we have to create a scrollbar class object as:
h = Scrollbar(root, orient='horizontal')
Here h represents the scrollbar object which is created as a child to root window. Here orient indicates horizontal for horizontal scrollbar and vertical indicates vertical scroll bars. Similarly to create a vertical scrollbar we can write:
v = Scrollbar(root, orient='vertical')
On attaching the scrollbar to a widget like text box, list box, etc we then have to add a command xview for horizontal scrollbar and yview for the vertical scrollbar.
h.config(command=t.xview) #for horizontal scrollbar
v.config(command=t.yview) #for vertical scrollbar
Now let us look at the code for attaching a vertical and horizontal scrollbar to a Text Widget.
Python3
# Python Program to make a scrollable frame# using Tkinter from tkinter import * class ScrollBar: # constructor def __init__(self): # create root window root = Tk() # create a horizontal scrollbar by # setting orient to horizontal h = Scrollbar(root, orient = 'horizontal') # attach Scrollbar to root window at # the bootom h.pack(side = BOTTOM, fill = X) # create a vertical scrollbar-no need # to write orient as it is by # default vertical v = Scrollbar(root) # attach Scrollbar to root window on # the side v.pack(side = RIGHT, fill = Y) # create a Text widget with 15 chars # width and 15 lines height # here xscrollcomannd is used to attach Text # widget to the horizontal scrollbar # here yscrollcomannd is used to attach Text # widget to the vertical scrollbar t = Text(root, width = 15, height = 15, wrap = NONE, xscrollcommand = h.set, yscrollcommand = v.set) # insert some text into the text widget for i in range(20): t.insert(END,"this is some text\n") # attach Text widget to root window at top t.pack(side=TOP, fill=X) # here command represents the method to # be executed xview is executed on # object 't' Here t may represent any # widget h.config(command=t.xview) # here command represents the method to # be executed yview is executed on # object 't' Here t may represent any # widget v.config(command=t.yview) # the root window handles the mouse # click event root.mainloop() # create an object to Scrollbar classs = ScrollBar()
Output:
mckinneyrryan
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python | [
{
"code": null,
"e": 25529,
"s": 25501,
"text": "\n04 Mar, 2021"
},
{
"code": null,
"e": 26059,
"s": 25529,
"text": "A scrollbar is a widget that is useful to scroll the text in another widget. For example, the text in Text, Canvas Frame or Listbox can be scrolled from top to bot... |
Java | Collectors maxBy(Comparator comparator) with Examples - GeeksforGeeks | 06 Dec, 2018
Collectors maxBy(Comparator<? super T> comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.
Syntax:
public static
<T> Collector<T, ?, Optional<T>>
maxBy(Comparator<? super T> comparator)
where the terms used are as follows:
Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation.
T: The type of input elements to the reduction operation.
A: The mutable accumulation type of the reduction operation.
R: The result type of the reduction operation.
Optional: A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Comparator: A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.
Parameters: This method takes a parameter comparator of type Comparator, which is a comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.
Return Value: This method returns a Collector that produces the maximal value in accordance with the comparator passed.
Below are some examples to illustrate the implementation of maxBy():
Program 1:
// Java code to show the implementation of// Collectors maxBy(Comparator comparator) function import java.util.Comparator;import java.util.Optional;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a Stream of strings Stream<String> s = Stream.of("2", "3", "4", "5"); // using Collectors maxBy(Comparator comparator) // and finding the maximum element // in reverse order Optional<String> obj = s .collect(Collectors .maxBy(Comparator .reverseOrder())); // if present, print the element // else print the message if (obj.isPresent()) { System.out.println(obj.get()); } else { System.out.println("no value"); } }}
2
Example 2:
// Java code to show the implementation of// Collectors maxBy(Comparator comparator) function import java.util.Comparator;import java.util.Optional;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a Stream of strings Stream<String> s = Stream.of(); // using Collectors maxBy(Comparator comparator) // and finding the maximum element // in reverse order Optional<String> obj = s .collect(Collectors .maxBy(Comparator .reverseOrder())); // if present, print the element // else print the message if (obj.isPresent()) { System.out.println(obj.get()); } else { System.out.println("no value"); } }}
no value
Java - util package
Java-Collectors
Java-Functions
java-stream
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25777,
"s": 25749,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 26027,
"s": 25777,
"text": "Collectors maxBy(Comparator<? super T> comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that prod... |
Orbit counting theorem or Burnside's Lemma - GeeksforGeeks | 03 Mar, 2022
Burnside’s Lemma is also sometimes known as orbit counting theorem. It is one of the results of group theory. It is used to count distinct objects with respect to symmetry. It basically gives us the formula to count the total number of combinations, where two objects that are symmetrical to each other with respect to rotation or reflection are counted as a single representative.
Therefore, Burnside Lemma’s states that total number of distinct object is: where:
c(k) is the number of combination that remains unchanged when Kth rotation is applied, and
N is the total number of ways to change the position of N elements.
For Example:Let us consider we have a necklace of N stones and we can color it with M colors. If two necklaces are similar after rotation then the two necklaces are considered to be similar and counted as one different combination. Now Let’s suppose we have N = 4 stones with M = 3 colors, then
Since we have N stones, therefore, we have N possible variations of each necklace by rotation:
Observations: There are N ways to change the position of the necklace as we can rotate it by 0 to N – 1 time.
There are ways to color a necklace. If the number of rotations is 0, then all ways remain different.If the number of rotation is 1, then there are only M necklaces which will be different out of all ways.Generally, if the number of rotations is K, necklaces will remain the same out of all ways.
There are ways to color a necklace. If the number of rotations is 0, then all ways remain different.
If the number of rotation is 1, then there are only M necklaces which will be different out of all ways.
Generally, if the number of rotations is K, necklaces will remain the same out of all ways.
Therefore, for a total number of distinct necklaces of N stones after coloring with M colors is the summation of all the distinct necklaces at each rotation. It is given by:
Below is the implementation of the above approach:
C++
Java
C#
Javascript
// C++ program for implementing the// Orbit counting theorem// or Burnside's Lemma #include <bits/stdc++.h>using namespace std; // Function to find result using// Orbit counting theorem// or Burnside's Lemmavoid countDistinctWays(int N, int M){ int ans = 0; // According to Burnside's Lemma // calculate distinct ways for each // rotation for (int i = 0; i < N; i++) { // Find GCD int K = __gcd(i, N); ans += pow(M, K); } // Divide By N ans /= N; // Print the distinct ways cout << ans << endl;} // Driver Codeint main(){ // N stones and M colors int N = 4, M = 3; // Function call countDistinctWays(N, M); return 0;}
// Java program for implementing the// Orbit counting theorem// or Burnside's Lemmaclass GFG{ static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to find result using// Orbit counting theorem// or Burnside's Lemmastatic void countDistinctWays(int N, int M){ int ans = 0; // According to Burnside's Lemma // calculate distinct ways for each // rotation for(int i = 0; i < N; i++) { // Find GCD int K = gcd(i, N); ans += Math.pow(M, K); } // Divide By N ans /= N; // Print the distinct ways System.out.print(ans);} // Driver Codepublic static void main(String []args){ // N stones and M colors int N = 4, M = 3; // Function call countDistinctWays(N, M);}} // This code is contributed by rutvik_56
// C# program for implementing the// Orbit counting theorem// or Burnside's Lemmausing System;class GFG{static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to find result using// Orbit counting theorem// or Burnside's Lemmastatic void countDistinctWays(int N, int M){ int ans = 0; // According to Burnside's Lemma // calculate distinct ways for each // rotation for(int i = 0; i < N; i++) { // Find GCD int K = gcd(i, N); ans += (int)Math.Pow(M, K); } // Divide By N ans /= N; // Print the distinct ways Console.Write(ans);} // Driver Codepublic static void Main(string []args){ // N stones and M colors int N = 4, M = 3; // Function call countDistinctWays(N, M);}} // This code is contributed by pratham76
<script> // Javascript <script> // Javascript program for implementing the// Orbit counting theorem// or Burnside's Lemma function gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // Function to find result using// Orbit counting theorem// or Burnside's Lemmafunction countDistinctWays(N, M){ let ans = 0; // According to Burnside's Lemma // calculate distinct ways for each // rotation for(let i = 0; i < N; i++) { // Find GCD let K = gcd(i, N); ans += Math.pow(M, K); } // Divide By N ans /= N; // Print the distinct ways document.write(ans);} // Driver Code // N stones and M colors let N = 4, M = 3; // Function call countDistinctWays(N, M); </script>
24
rutvik_56
pratham76
susmitakundugoaldanga
sweetyty
Combinatorial
Mathematical
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Coin Change | DP-7
Merge two sorted arrays | [
{
"code": null,
"e": 26723,
"s": 26695,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 27105,
"s": 26723,
"text": "Burnside’s Lemma is also sometimes known as orbit counting theorem. It is one of the results of group theory. It is used to count distinct objects with respect to ... |
How to Check if Time Series Data is Stationary with Python? - GeeksforGeeks | 19 Jan, 2022
Time series data are generally characterized by their temporal nature. This temporal nature adds a trend or seasonality to the data that makes it compatible for time series analysis and forecasting. Time-series data is said to be stationary if it doesn’t change with time or if they don’t have a temporal structure. So, it is highly necessary to check if the data is stationary. In time series forecasting, we cannot derive valuable insights from data if it is stationary.
Example plot of stationary data:
When it comes to identifying if the data is stationary, it means identifying the fine-grained notions of stationarity in the data. The types of stationarity observed in time series data include
Trend Stationary – A time series that does not show a trend.Seasonal Stationary – A time series that does not show seasonal changes.Strictly Stationary – The joint distribution of observations is invariant to time shift.
Trend Stationary – A time series that does not show a trend.
Seasonal Stationary – A time series that does not show seasonal changes.
Strictly Stationary – The joint distribution of observations is invariant to time shift.
The following steps will let the user easily understand the method to check the given time series data is stationary.
Click here to download the practice dataset daily-female-births-IN.csv.
Python3
# import python pandas libraryimport pandas as pd # import python matplotlib library for plottingimport matplotlib.pyplot as plt # read the dataset using pandas read_csv()# functiondata = pd.read_csv("daily-total-female-births-IN.csv", header=0, index_col=0) # use simple line plot to see the distribution# of the dataplt.plot(data)
Output:
This is usually done by splitting the data into two or more partitions and calculating the mean and variance for each group. If these first-order moments are consistent among these partitions, then we can assume that the data is stationary. Let’s use airlines passenger count data set between 1949 – 1960.
Click here to download the practice dataset AirPassengers.csv.
Python3
# import python pandas libraryimport pandas as pd # import python matplotlib library for# plottingimport matplotlib.pyplot as plt # read the dataset using pandas read_csv()# functiondata = pd.read_csv("AirPassengers.csv", header=0, index_col=0) # print the first 6 rows of dataprint(data.head(10)) # use simple line plot to understand the# data distributionplt.plot(data)
Output:
Now, let’s partition this data into different groups and calculate the mean and variance of different groups and check for consistency.
Python3
# import the python pandas libraryimport pandas as pd # use pandas read_csv() function to read the dataset.data = pd.read_csv("AirPassengers.csv", header=0, index_col=0) # extracting only the air passengers count from# the dataset using values functionvalues = data.values # getting the count to split the dataset into 3parts = int(len(values)/3) # splitting the data into three partspart_1, part_2, part_3 = values[0:parts], values[parts:( parts*2)], values[(parts*2):(parts*3)] # calculating the mean of the separated three# parts of data individually.mean_1, mean_2, mean_3 = part_1.mean(), part_2.mean(), part_3.mean() # calculating the variance of the separated# three parts of data individually.var_1, var_2, var_3 = part_1.var(), part_2.var(), part_3.var() # printing the mean of three groupsprint('mean1=%f, mean2=%f, mean2=%f' % (mean_1, mean_2, mean_3)) # printing the variance of three groupsprint('variance1=%f, variance2=%f, variance2=%f' % (var_1, var_2, var_3))
Output:
The output clearly implies that the mean and variance of the three groups are considerably different from each other describing the data is non-stationary. Say for example if the means where mean_1 = 150, mean_2 = 160, mean_3 = 155 and variance_1 = 33, variance_2 = 35, variance_3 = 37, then we can conclude that the data is stationary. Sometimes this method can fail for some distributions, like log-norm distributions.
Let’s try the same example as above but take the log of the passengers’ count using NumPy’s log() function and check the results.
Python3
# import python pandas libraryimport pandas as pd # import python matplotlib library for plottingimport matplotlib.pyplot as plt # import python numpy libraryimport numpy as np # read the dataset using pandas read_csv()# functiondata = pd.read_csv("AirPassengers.csv", header=0, index_col=0) # extracting only the air passengers count# from the dataset using values functionvalues = log(data.values) # printing the first 15 passenger count valuesprint(values[0:15]) # using simple line plot to understand the# data distributionplt.plot(values)
Output:
The output signifies there is some trend but not very steep as the previous case, now let’s compute the partition mean and variance.
Python3
# getting the count to split the dataset# into 3 partsparts = int(len(values)/3) # splitting the data into three parts.part_1, part_2, part_3 = values[0:parts], values[parts:(parts*2)], values[(parts*2):(parts*3)] # calculating the mean of the separated three# parts of data individually.mean_1, mean_2, mean_3 = part_1.mean(), part_2.mean(), part_3.mean() # calculating the variance of the separated three# parts of data individually.var_1, var_2, var_3 = part_1.var(), part_2.var(), part_3.var() # printing the mean of three groupsprint('mean1=%f, mean2=%f, mean2=%f' % (mean_1, mean_2, mean_3)) # printing the variance of three groupsprint('variance1=%f, variance2=%f, variance2=%f' % (var_1, var_2, var_3))
Output:
Ideally, we would have expected the mean and variance to be very different but they are the same, in such cases, this method can terribly fail. In order to avoid this, we have another statistical test which is discussed below.
This is a statistical test that is dedicatedly built to test whether univariate time series data is stationary or not. This test is based on a hypothesis and can tell us the degree of probability to which it can be accepted. It is often classified under one of the unit root tests, It determines how strongly, a univariate time series data follows a trend. Let’s define the null and alternate hypotheses,
Ho (Null Hypothesis): The time series data is non-stationary
H1 (alternate Hypothesis): The time series data is stationary
Assume alpha = 0.05, meaning (95% confidence). The test results are interpreted with a p-value if p > 0.05 fails to reject the null hypothesis, else if p <= 0.05 reject the null hypothesis. Now, let’s use the same air passengers dataset and test it using adfuller() statistical function provided by the stats model package, to check whether the data is stationary or not.
Python3
# import python pandas packageimport pandas as pd # import the adfuller function from statsmodel# package to perform ADF testfrom statsmodels.tsa.stattools import adfuller # read the dataset using pandas read_csv() functiondata = pd.read_csv("AirPassengers.csv", header=0, index_col=0) # extracting only the passengers count using values functionvalues = data.values # passing the extracted passengers count to adfuller function.# result of adfuller function is stored in a res variableres = adfuller(values) # Printing the statistical result of the adfuller testprint('Augmneted Dickey_fuller Statistic: %f' % res[0])print('p-value: %f' % res[1]) # printing the critical values at different alpha levels.print('critical values at different levels:')for k, v in res[4].items(): print('\t%s: %.3f' % (k, v))
Output:
As per our hypothesis, the ADF statistic is much greater than the critical values at different levels, and also the p-value is also greater than 0.05 which signifies, we can fail to reject the null hypothesis at 90%, 95%, and 99% confidence, meaning the time series data is strongly non-stationary.
Now, let’s try running the ADF test to the log normed values and cross-check our results.
Python3
# import python pandas packageimport pandas as pd # import the adfuller function from statsmodel# package to perform ADF testfrom statsmodels.tsa.stattools import adfuller # import python numpy packageimport numpy as np # read the dataset using pandas read_csv() functiondata = pd.read_csv("AirPassengers.csv", header=0, index_col=0) # extracting only the passengers count using# values function and applying log transform on it.values = log(data.values) # passing the extracted passengers count to adfuller function.# result of adfuller function is stored in a res variableres = adfuller(values) # Printing the statistical result of the adfuller testprint('Augmneted Dickey_fuller Statistic: %f' % res[0])print('p-value: %f' % res[1]) # printing the critical values at different alpha levels.print('critical values at different levels:')for k, v in res[4].items(): print('\t%s: %.3f' % (k, v))
Output:
As you can see, the ADF test one more times shows that the ADF statistic is much greater than the critical values at different levels, and also the p-value is much greater than 0.05 which signifies, we can fail to reject the null hypothesis at 90%, 95%, and 99% confidence, meaning the time series data is strongly non-stationary.
Hence, the ADF unit root test stands out to be a robust test to check whether a time series data is stationary or not.
sagartomar9927
surinderdawra388
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26010,
"s": 25537,
"text": "Time series data are generally characterized by their temporal nature. This temporal nature adds a trend or seasonality to the data that makes it compatible for ti... |
Length of longest connected 1’s in a Binary Grid - GeeksforGeeks | 12 Feb, 2022
Given a grid of size N*M consists of 0 and 1 only, the task is to find the length of longest connected 1s in the given grid. We can only move to left, right, up or down from any current cell of the grid.
Examples:
Input: N = 3, M = 3, grid[][] = { {0, 0, 0}, {0, 1, 0}, {0, 0, 0} } Output: 1 Explanation: The longest possible route is 1 as there cant be any movement from (1, 1) position of the matrix.
Input: N = 6, M = 7, grid[][] = { {0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0}, {0, 1, 0, 1, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0}} Output: 9 Explanation: The longest possible route is 9 starting from (1, 1) -> (2, 1) -> (3, 1) -> (4, 1) -> (4, 2) -> (4, 3) -> (4, 4) -> (4, 5) -> (3, 5).
Approach: The idea is to do DFS Traversal on grid where the value of current cell is 1 and recursively call for all the four direction of the current cell where value is 1 and updated the maximum length of connected 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>#define row 6#define col 7using namespace std; int vis[row + 1][col + 1], id;int diameter = 0, length = 0; // Keeps a track of directions// that is up, down, left, rightint dx[] = { -1, 1, 0, 0 };int dy[] = { 0, 0, -1, 1 }; // Function to perform the dfs traversalvoid dfs(int a, int b, int lis[][col], int& x, int& y){ // Mark the current node as visited vis[a][b] = id; // Increment length from this node length++; // Update the diameter length if (length > diameter) { x = a; y = b; diameter = length; } for (int j = 0; j < 4; j++) { // Move to next cell in x-direction int cx = a + dx[j]; // Move to next cell in y-direction int cy = b + dy[j]; // Check if cell is invalid // then continue if (cx < 0 || cy < 0 || cx >= row || cy >= col || lis[cx][cy] == 0 || vis[cx][cy]) { continue; } // Perform DFS on new cell dfs(cx, cy, lis, x, y); } vis[a][b] = 0; // Decrement the length length--;} // Function to find the maximum length of// connected 1s in the given gridvoid findMaximumLength(int lis[][col]){ int x, y; // Increment the id id++; length = 0; diameter = 0; // Traverse the grid[] for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (lis[i][j] != 0) { // Find start point of // start dfs call dfs(i, j, lis, x, y); i = row; break; } } } id++; length = 0; diameter = 0; // DFS Traversal from cell (x, y) dfs(x, y, lis, x, y); // Print the maximum length cout << diameter;} // Driver Codeint main(){ // Given grid[][] int grid[][col] = { { 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 1, 0 }, { 0, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 1, 0, 0, 0 } }; // Function Call findMaximumLength(grid); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ static final int row = 6;static final int col = 7;static int [][]vis = new int[row + 1][col + 1];static int id;static int diameter = 0, length = 0;static int x = 0, y = 0; // Keeps a track of directions// that is up, down, left, rightstatic int dx[] = { -1, 1, 0, 0 };static int dy[] = { 0, 0, -1, 1 }; // Function to perform the dfs traversalstatic void dfs(int a, int b, int lis[][]){ // Mark the current node as visited vis[a][b] = id; // Increment length from this node length++; // Update the diameter length if (length > diameter) { x = a; y = b; diameter = length; } for(int j = 0; j < 4; j++) { // Move to next cell in x-direction int cx = a + dx[j]; // Move to next cell in y-direction int cy = b + dy[j]; // Check if cell is invalid // then continue if (cx < 0 || cy < 0 || cx >= row || cy >= col || lis[cx][cy] == 0 || vis[cx][cy] > 0) { continue; } // Perform DFS on new cell dfs(cx, cy, lis); } vis[a][b] = 0; // Decrement the length length--;} // Function to find the maximum length of// connected 1s in the given gridstatic void findMaximumLength(int lis[][]){ // Increment the id id++; length = 0; diameter = 0; // Traverse the grid[] for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if (lis[i][j] != 0) { // Find start point of // start dfs call dfs(i, j, lis); i = row; break; } } } id++; length = 0; diameter = 0; // DFS Traversal from cell (x, y) dfs(x, y, lis); // Print the maximum length System.out.print(diameter);} // Driver Codepublic static void main(String[] args){ // Given grid[][] int grid[][] = { { 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 1, 0 }, { 0, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 1, 0, 0, 0 } }; // Function Call findMaximumLength(grid);}} // This code is contributed by amal kumar choubey
# Python3 program for the above approachrow = 6col = 7 vis = [[0 for i in range(col + 1)] for j in range(row + 1)]id = 0diameter = 0length = 0 # Keeps a track of directions# that is up, down, left, rightdx = [ -1, 1, 0, 0 ]dy = [ 0, 0, -1, 1 ] # Function to perform the dfs traversaldef dfs(a, b, lis, x, y): global id, length, diameter # Mark the current node as visited vis[a][b] = id # Increment length from this node length += 1 # Update the diameter length if (length > diameter): x = a y = b diameter = length for j in range(4): # Move to next cell in x-direction cx = a + dx[j] # Move to next cell in y-direction cy = b + dy[j] # Check if cell is invalid # then continue if (cx < 0 or cy < 0 or cx >= row or cy >= col or lis[cx][cy] == 0 or vis[cx][cy]): continue # Perform DFS on new cell dfs(cx, cy, lis, x, y) vis[a][b] = 0 # Decrement the length length -= 1 return x, y # Function to find the maximum length of# connected 1s in the given griddef findMaximumLength(lis): global id, length, diameter x = 0 y = 0 # Increment the id id += 1 length = 0 diameter = 0 # Traverse the grid[] for i in range(row): for j in range(col): if (lis[i][j] != 0): # Find start point of # start dfs call x, y = dfs(i, j, lis, x, y) i = row break id += 1 length = 0 diameter = 0 # DFS Traversal from cell (x, y) x, y = dfs(x, y, lis, x, y) # Print the maximum length print(diameter) # Driver Codeif __name__=="__main__": # Given grid[][] grid = [ [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 1, 0, 0, 0 ], [ 0, 1, 0, 1, 0, 0, 0 ], [ 0, 1, 0, 1, 0, 1, 0 ], [ 0, 1, 1, 1, 1, 1, 0 ], [ 0, 0, 0, 1, 0, 0, 0 ] ] # Function Call findMaximumLength(grid) # This code is contributed by rutvik_56
// C# program for the above approachusing System; class GFG{ static readonly int row = 6;static readonly int col = 7;static int [,]vis = new int[row + 1, col + 1];static int id;static int diameter = 0, length = 0;static int x = 0, y = 0; // Keeps a track of directions// that is up, down, left, rightstatic int []dx = { -1, 1, 0, 0 };static int []dy = { 0, 0, -1, 1 }; // Function to perform the dfs traversalstatic void dfs(int a, int b, int [,]lis){ // Mark the current node as visited vis[a, b] = id; // Increment length from this node length++; // Update the diameter length if (length > diameter) { x = a; y = b; diameter = length; } for(int j = 0; j < 4; j++) { // Move to next cell in x-direction int cx = a + dx[j]; // Move to next cell in y-direction int cy = b + dy[j]; // Check if cell is invalid // then continue if (cx < 0 || cy < 0 || cx >= row || cy >= col || lis[cx, cy] == 0 || vis[cx, cy] > 0) { continue; } // Perform DFS on new cell dfs(cx, cy, lis); } vis[a, b] = 0; // Decrement the length length--;} // Function to find the maximum length of// connected 1s in the given gridstatic void findMaximumLength(int [,]lis){ // Increment the id id++; length = 0; diameter = 0; // Traverse the grid[] for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if (lis[i, j] != 0) { // Find start point of // start dfs call dfs(i, j, lis); i = row; break; } } } id++; length = 0; diameter = 0; // DFS Traversal from cell (x, y) dfs(x, y, lis); // Print the maximum length Console.Write(diameter);} // Driver Codepublic static void Main(String[] args){ // Given grid[,] int [,]grid = { { 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 1, 0 }, { 0, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 1, 0, 0, 0 } }; // Function Call findMaximumLength(grid);}} // This code is contributed by amal kumar choubey
<script> // JavaScript program to implement// the above approach let row = 6; let col = 7;let vis = new Array(row + 1);// Loop to create 2D array using 1D arrayfor (var i = 0; i < vis.length; i++) { vis[i] = new Array(2);} let id = 0;let diameter = 0, length = 0;let x = 0, y = 0; // Keeps a track of directions// that is up, down, left, rightlet dx = [ -1, 1, 0, 0 ];let dy = [ 0, 0, -1, 1 ]; // Function to perform the dfs traversalfunction dfs(a, b, lis){ // Mark the current node as visited vis[a][b] = id; // Increment length from this node length++; // Update the diameter length if (length > diameter) { x = a; y = b; diameter = length; } for(let j = 0; j < 4; j++) { // Move to next cell in x-direction let cx = a + dx[j]; // Move to next cell in y-direction let cy = b + dy[j]; // Check if cell is invalid // then continue if (cx < 0 || cy < 0 || cx >= row || cy >= col || lis[cx][cy] == 0 || vis[cx][cy] > 0) { continue; } // Perform DFS on new cell dfs(cx, cy, lis); } vis[a][b] = 0; // Decrement the length length--;} // Function to find the maximum length of// connected 1s in the given gridfunction findMaximumLength(lis){ // Increment the id id++; length = 0; diameter = 0; // Traverse the grid[] for(let i = 0; i < row; i++) { for(let j = 0; j < col; j++) { if (lis[i][j] != 0) { // Find start point of // start dfs call dfs(i, j, lis); i = row; break; } } } id++; length = 0; diameter = 0; // DFS Traversal from cell (x, y) dfs(x, y, lis); // Print the maximum length document.write(diameter);} // Driver code // Given grid[][] let grid = [[ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 1, 0, 1, 0, 0, 0 ], [ 0, 1, 0, 1, 0, 0, 0 ], [ 0, 1, 0, 1, 0, 1, 0 ], [ 0, 1, 1, 1, 1, 1, 0 ], [ 0, 0, 0, 1, 0, 0, 0 ]]; // Function Call findMaximumLength(grid); // This code is contributed by sanjoy_62.</script>
9
Time Complexity: O(N*M)
where ‘N’ is the number of rows and ‘M’ is number of columns.
Amal Kumar Choubey
rutvik_56
sanjoy_62
Kirti_Mangal
arorakashish0911
karandeep1234
BFS
binary-representation
DFS
Competitive Programming
Graph
Greedy
Matrix
Recursion
Greedy
Recursion
DFS
Matrix
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
5 Best Books for Competitive Programming
5 Best Languages for Competitive Programming
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 | [
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n12 Feb, 2022"
},
{
"code": null,
"e": 26561,
"s": 26357,
"text": "Given a grid of size N*M consists of 0 and 1 only, the task is to find the length of longest connected 1s in the given grid. We can only move to left, right, up or... |
Level order traversal in spiral form | Using Deque - GeeksforGeeks | 22 Jun, 2021
Given a Binary Tree, the task is to print spiral order traversal of the given tree. For below tree, the function should print 1, 2, 3, 4, 5, 6, 7.
Examples:
Input:
1
/ \
3 2
Output :
1
3 2
Input :
10
/ \
20 30
/ \
40 60
Output :
10
20 30
60 40
We have seen recursive and iterative solutions using two stacks and an approach using one stack and one queue. In this post, a solution with one deque is discussed. The idea is to use a direction variable and decide whether to pop elements from the front or from the rear based on the value of this direction variable.Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program to print level order traversal// in spiral form using one deque.#include <bits/stdc++.h>using namespace std; class Node {public: int data; Node *left, *right; Node(int val) { data = val; left = NULL; right = NULL; }}; void spiralOrder(Node* root){ deque<Node*> d; // Push root d.push_back(root); // Direction 0 shows print right to left // and for Direction 1 left to right int dir = 0; while (!d.empty()) { int size = d.size(); while (size--) { // One whole level // will be print in this loop if (dir == 0) { Node* temp = d.back(); d.pop_back(); if (temp->right) d.push_front(temp->right); if (temp->left) d.push_front(temp->left); cout << temp->data << " "; } else { Node* temp = d.front(); d.pop_front(); if (temp->left) d.push_back(temp->left); if (temp->right) d.push_back(temp->right); cout << temp->data << " "; } } cout << endl; // Direction change dir = 1 - dir; }} int main(){ // Build the Tree Node* root = new Node(10); root->left = new Node(20); root->right = new Node(30); root->left->left = new Node(40); root->left->right = new Node(60); // Call the Function spiralOrder(root); return 0;}
// Java program to print level order traversal// in spiral form using one deque.import java.util.*; class GFG{ static class Node{ int data; Node left, right; Node(int val) { data = val; left = null; right = null; }}; static void spiralOrder(Node root){ Deque<Node> d = new LinkedList<Node>(); // Push root d.addLast(root); // Direction 0 shows print right to left // and for Direction 1 left to right int dir = 0; while (d.size() > 0) { int size = d.size(); while (size-->0) { // One whole level // will be print in this loop if (dir == 0) { Node temp = d.peekLast(); d.pollLast(); if (temp.right != null) d.addFirst(temp.right); if (temp.left != null) d.addFirst(temp.left); System.out.print(temp.data + " "); } else { Node temp = d.peekFirst(); d.pollFirst(); if (temp.left != null) d.addLast(temp.left); if (temp.right != null) d.addLast(temp.right); System.out.print(temp.data + " "); } } System.out.println(); // Direction change dir = 1 - dir; }} // Driver codepublic static void main(String args[]){ // Build the Tree Node root = new Node(10); root.left = new Node(20); root.right = new Node(30); root.left.left = new Node(40); root.left.right = new Node(60); // Call the Function spiralOrder(root);}} // This code is contributed by Arnab Kundu
# Python program to print level order traversal# in spiral form using one deque.class Node : def __init__(self,val) : self.data = val; self.left = None; self.right = None; def spiralOrder(root) : d = []; # Push root d.append(root); # Direction 0 shows print right to left # and for Direction 1 left to right direct = 0; while (len(d) != 0) : size = len(d); while (size) : size -= 1; # One whole level # will be print in this loop if (direct == 0) : temp = d.pop(); if (temp.right) : d.insert(0, temp.right); if (temp.left) : d.insert(0, temp.left); print(temp.data, end= " "); else : temp = d[0]; d.pop(0); if (temp.left) : d.append(temp.left); if (temp.right) : d.append(temp.right); print(temp.data ,end= " "); print() # Direction change direct = 1 - direct; if __name__ == "__main__" : # Build the Tree root = Node(10); root.left = Node(20); root.right = Node(30); root.left.left = Node(40); root.left.right = Node(60); # Call the Function spiralOrder(root); # This code is contributed by AnkitRai01
<script> // JavaScript program to print level order traversal// in spiral form using one deque. class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }}; function spiralOrder(root){ var d = []; // Push root d.push(root); // Direction 0 shows print right to left // and for Direction 1 left to right var dir = 0; while (d.length!=0) { var size = d.length; while (size-- >0) { // One whole level // will be print in this loop if (dir == 0) { var temp = d[d.length-1]; d.pop(); if (temp.right!= null) d.unshift(temp.right); if (temp.left!= null) d.unshift(temp.left); document.write( temp.data + " "); } else { var temp = d[0]; d.shift(); if (temp.left != null) d.push(temp.left); if (temp.right!= null) d.push(temp.right); document.write( temp.data + " "); } } document.write("<br>"); // Direction change dir = 1 - dir; }} // Build the Treevar root = new Node(10);root.left = new Node(20);root.right = new Node(30);root.left.left = new Node(40);root.left.right = new Node(60);// Call the FunctionspiralOrder(root); </script>
10
20 30
60 40
Time Complexity: O(N) Space Complexity: O(N) where N is the number of Nodes
ankthon
andrew1234
noob2000
Binary Tree
deque
Queue
Technical Scripter
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Implement Stack using Queues
Sliding Window Maximum (Maximum of all subarrays of size k)
Array implementation of queue (Simple)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 26419,
"s": 26391,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 26567,
"s": 26419,
"text": "Given a Binary Tree, the task is to print spiral order traversal of the given tree. For below tree, the function should print 1, 2, 3, 4, 5, 6, 7. "
},
{
"... |
Python String isdigit() Method - GeeksforGeeks | 12 Aug, 2021
Python String isdigit() method is a built-in method used for string handling. The isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”. This function is used to check if the argument contains digits such as 0123456789
Syntax:
string.isdigit()
Parameters:
isdigit() does not take any parameters
Returns:
True – If all characters in the string are digits.
False – If the string contains 1 or more non-digits.
Errors And Exceptions:
It does not take any arguments, therefore it returns an error if a parameter is passedSuperscript and subscripts are considered digit characters along with decimal characters, therefore, isdigit() returns “True”.The Roman numerals, currency numerators, and fractions are not considered to be digits. Therefore, the isdigit() returns “False”
It does not take any arguments, therefore it returns an error if a parameter is passed
Superscript and subscripts are considered digit characters along with decimal characters, therefore, isdigit() returns “True”.
The Roman numerals, currency numerators, and fractions are not considered to be digits. Therefore, the isdigit() returns “False”
Input : string = '15460'
Output : True
Input : string = '154ayush60'
Output : False
Python3
# Python code for implementation of isdigit() # checking for digitstring = '15460'print(string.isdigit()) string = '154ayush60'print(string.isdigit())
Output:
True
False
Application: Using ASCII values of characters, count and print all the digits using isdigit() function.
Algorithm:
Initialize a new string and a variable count=0.Traverse every character using ASCII value, check if the character is a digit. If it is a digit, increment the count by 1 and add it to the new string, else traverse to the next character. Print the value of the counter and the new string.
Initialize a new string and a variable count=0.
Traverse every character using ASCII value, check if the character is a digit.
If it is a digit, increment the count by 1 and add it to the new string, else traverse to the next character.
Print the value of the counter and the new string.
Python3
# Python program to illustrate # application of isdigit()# initialising Empty stringnewstring ='' # Initialising the counters to 0count = 0 # Incrementing the counter if a digit is found # and adding the digit to a new string# Finally printing the count and the new string for a in range(53): b = chr(a) if b.isdigit() == True: count+= 1 newstring+= b print("Total digits in range :", count)print("Digits :", newstring)
Output:
Total digits in range : 5
Digits : 01234
In Python, superscript and subscripts (usually written using Unicode) are also considered digit characters. Hence, if the string contains these characters along with decimal characters, isdigit() returns True. The Roman numerals, currency numerators, and fractions (usually written using Unicode) are considered numeric characters but not digits. The isdigit() returns False if the string contains these characters. To check whether a character is a numeric character or not, you can use isnumeric() method.
String Containing digits and Numeric Characters
Python3
s = '23455'print(s.isdigit()) # s = '23455'# subscript is a digits = '\u00B23455' print(s.isdigit()) # s = '1⁄2'# fraction is not a digits = '\u00BD' print(s.isdigit())
Output:
True
True
False
mohammadnaved1351
AmiyaRanjanRout
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 25089,
"s": 25061,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 25360,
"s": 25089,
"text": "Python String isdigit() method is a built-in method used for string handling. The isdigit() method returns “True” if all characters in the string are digits, Other... |
Python - Concatenate string rows in Matrix - GeeksforGeeks | 30 Dec, 2020
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the concatenation of rows of matrix in uneven sized matrix. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using join() + list comprehensionThe combination of above functions can help to get the solution to this particular problem in just a one line and hence quite useful. The join function computes the concatenation of sublists and all this bound together using list comprehension.
# Python3 code to demonstrate# Row String Concatenation Matrix# using join() + list comprehension # initializing listtest_list = [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']] # printing original listprint("The original list : " + str(test_list)) # using join() + list comprehension# Row String Concatenation Matrixres = [''.join(idx for idx in sub) for sub in test_list ] # print resultprint("The row concatenation in matrix : " + str(res))
The original list : [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
The row concatenation in matrix : ['gfg is best', 'Computer Science', 'GeeksforGeeks']
Method #2 : Using loopThis task can also be performed in brute force manner in which we just iterate the sublists and perform join in brute manner creating new string for each sublist and appending in list.
# Python3 code to demonstrate# Row String Concatenation Matrix# using loop # initializing listtest_list = [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']] # printing original listprint("The original list : " + str(test_list)) # using loop# Row String Concatenation Matrixres = []for sub in test_list: res_sub = "" for idx in sub: res_sub = res_sub + idx res.append(res_sub) # print resultprint("The row concatenation in matrix : " + str(res))
The original list : [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
The row concatenation in matrix : ['gfg is best', 'Computer Science', 'GeeksforGeeks']
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 26263,
"s": 26235,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 26542,
"s": 26263,
"text": "The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the conc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.