HTTP Introduction.

Learning HTTP is basic and foundational learning for web development because it helps you understand how data is exchanged on the internet. In this article, we will cover the basics of HTTP, why we need to learn about it, and how it is evolving with time. 

What is HTTP?

What is HTTP?

HTTP, or Hypertext Transfer Protocol, is the foundation of data communication on the World Wide Web. It is an application layer protocol that enables the transfer of hypertext, which includes text, images, videos, and other multimedia, between clients (typically web browsers) and servers. HTTP is the protocol used for retrieving and transmitting information on the internet.

HTTP operates in a client-server model, where a client (e.g., a web browser) sends requests to a server, and the server responds with the requested data. The communication between the client and server consists of messages, where an HTTP request is sent by the client, and the server replies with an HTTP response. It is also known as a stateless protocol.

Stateless Protocol: A stateless protocol is a communication protocol that treats each request from a client to a server as an independent transaction. In other words, the protocol does not retain any information about the state or context of previous requests. Each request is processed based solely on the information provided in that specific request, without reference to prior interactions. 

What is the need for HTTP?

The primary purpose of HTTP is to establish a structured and efficient communication channel between clients, such as web browsers, and servers. This protocol ensures that requests for information are properly formatted, transmitted, and received, enabling users to navigate websites and access resources effortlessly. In essence, HTTP is the cornerstone of the web, fostering a standardized approach to data exchange that is integral to the functioning of the modern internet.

History and Evolution on HTTP.

With time there multiple new features have been added in HTTP protocols and what we use now in modern web development is the evolved version. Let's look at the history of HTTP.

Inception of HTTP:

HTTP, or Hypertext Transfer Protocol, was conceived in 1991 as the backbone of data communication on the World Wide Web. This initial version, known as HTTP/0.9, was rudimentary in nature, supporting only the GET method and responding with HTML content. The early internet landscape prompted the need for a more robust protocol, laying the groundwork for subsequent developments.

Emergence of HTTP/1.0:

Officially defined in 1996, HTTP/1.0 marked a significant advancement over its predecessor. This iteration introduced a variety of HTTP methods such as GET and POST, enabling a broader range of interactions between clients and servers. It also incorporated status codes and headers, enhancing the protocol's reliability and flexibility. However, HTTP/1.0 still faced challenges, particularly concerning connection reuse limitations.

Evolution with HTTP/1.1:

The release of HTTP/1.1 in 1997 addressed the limitations of its predecessor. Notable improvements included the introduction of persistent connections, allowing multiple requests over a single connection. Additionally, the protocol introduced pipelining, enabling the transmission of multiple requests without waiting for each response. HTTP/1.1 also expanded the range of headers, providing more control over the communication process.

Leap to HTTP/2:

HTTP/2, standardized in 2015, brought about a paradigm shift in web communication. It aimed to enhance page load times and reduce latency by introducing features like multiplexing, which allowed simultaneous processing of multiple requests and responses over a single connection. Header compression was implemented to minimize overhead, and prioritization of requests further optimized performance.

Unveiling HTTP/3:

In a continuous effort to improve performance and security, HTTP/3 is currently evolving. This iteration, still in progress as of my last knowledge update in January 2022, introduces QUIC (Quick UDP Internet Connections) as the underlying transport protocol. The objective is to address some limitations of TCP (Transmission Control Protocol) used in previous versions and further enhance the efficiency and reliability of web communication.

Looking ahead, the trajectory of HTTP's evolution involves an ongoing commitment to enhancing performance, security, and reliability. As technology advances, future iterations of the protocol will likely explore new technologies and protocols, ensuring that HTTP continues to meet the dynamic demands of the ever-evolving digital landscape.

Prerequisite to learn HTTP.

To learn HTTP, a basic understanding of fundamental web concepts is helpful. Familiarity with the structure of URLs, knowledge of how web browsers function and a grasp of client-server architecture are beneficial. Additionally, a beginner's understanding of HTML and web development concepts will provide a solid foundation for comprehending HTTP interactions between clients and servers. 

Microsoft Pledges Skill 75,000 Women Developers in India.

Highlight: Microsoft CEO Satya Nadella announces skilling and certification for 75,000 women developers in India, emphasizing the company's commitment to diversity and economic empowerment through technology.
Microsoft plan to skill 75000 Developers

In a groundbreaking commitment to fostering diversity and empowering women in technology, Microsoft CEO Satya Nadella announced that the company aims to provide skilling and certification to 75,000 women developers in India throughout the year 2024. The announcement was made during Microsoft's "Microsoft Build" event in Bengaluru on January 8, where Nadella emphasized the pivotal role of skills in creating economic opportunities for an increasingly skilled workforce.

Nadella, who arrived in Mumbai on February 7 for a two-day visit, underscored the theme for 2024 as Artificial Intelligence (AI) and the opportunities emerging from it. The initiative aligns with Microsoft's broader goal of promoting inclusivity and narrowing the gender gap in the fast-evolving realms of cloud, artificial intelligence (AI), and digital technology.

This skilling initiative represents an expansion of Microsoft's existing program named "Code; Without Barriers," which was launched in September 2021. Collaborating with 13 companies across nine Asia Pacific countries, the program was designed to address the gender gap and provide support, training, and networking opportunities for female developers, coders, and professionals in technical roles.

"The program provides support, training, and networking opportunities for female developers and coders, and those in other technical roles to contribute to inclusive economic growth, encourage innovation, and reflect the region’s social makeup," Microsoft stated in a release.

During his visit, Nadella also highlighted the noteworthy contribution of Karya.ai, an initiative incubated at Microsoft Research, which is playing a pivotal role in taking AI jobs to rural India. Karya.ai focuses on creating datasets in various Indian languages to train AI models and conduct research, simultaneously generating employment opportunities in rural areas.

Manu Chopra, CEO, and co-founder of Karya.ai, shared insights into the initiative, stating that his company pays workers 20 times above the Indian minimum wage, approximately Rs 400 per hour, for recording sentences on smartphones. Importantly, workers are entitled to royalties if the data generated by Karya.ai is resold.

Nadella's vision for India goes beyond skilling initiatives; it centers around empowering every individual and organization, starting with the developer community. The commitment to fostering an inclusive tech ecosystem aligns with Microsoft's broader mission of empowering every person and organization globally.

As technology continues to shape the future, Microsoft's initiatives in India stand as a testament to the company's dedication to leveraging AI and technology for societal progress. The pledge to skill and certify 75,000 women developers not only addresses the immediate skills gap but also sets the stage for a more diverse and inclusive tech landscape in India, reflecting the true potential of innovation when driven by a variety of perspectives.

Google Unveils Gemini Ultra: Rebranding Existing Chatbot Bard.

Gemini Google Most Capable AI Model

In a long-anticipated move, Google has officially launched Gemini Ultra, a revolutionary version that powers Gemini Advanced. This new iteration promises an enriched user experience, excelling in reasoning, instructional guidance, coding support, and collaborative creativity. Simultaneously, Google announced the rebranding of Bard to simply "Gemini," signaling a comprehensive upgrade in its AI offerings.

Gemini Advanced transcends traditional AI capabilities, positioning itself as a personalized tutor capable of generating custom step-by-step instructions, sample quizzes, and engaging in dynamic discussions tailored to individual learning preferences. For coding enthusiasts, the chatbot becomes an invaluable companion, adept at handling advanced coding scenarios, providing ideation support, and assisting in the evaluation of different coding approaches.

How to Access Google Gemini? 

To access Gemini Advanced, users can subscribe to the Google One AI Premium Plan, priced at $19.99 per month, featuring a complimentary two-month trial. This plan not only unlocks the latest AI advancements but also includes the benefits of the existing Google One Premium plan, offering 2TB of storage.

AI Premium subscribers are set to enjoy additional perks, with upcoming access to Gemini integration in Gmail, Docs, Slides, Sheets, and more, formerly known as Duet AI. Gemini Advanced is available for users in over 150 countries and territories in English, marking a global expansion of Google's advanced AI offerings.

Mobile App for Google Gemini.

Google has introduced a dedicated mobile app for Gemini on both Android and iOS platforms. The Gemini app for Android is currently available on Google Play, initially supporting English with plans to introduce Korean and Japanese language support next week. By downloading the Gemini app or opting in through Google Assistant, users can seamlessly access the new overlay experience, whether through the app or other activation methods like the power button, corner swiping on select phones, or using the "Hey Google" command.

On iOS, the introduction of Gemini access is slated for the coming weeks within the Google app. Users can effortlessly toggle the Gemini feature, engaging in conversations to boost creativity, generate custom images, seek assistance in writing social posts, and even plan activities – all directly from the Google app.

Google's Gemini Ultra marks a significant leap forward in AI capabilities, offering a multifaceted approach to learning, coding, and creative collaboration. The integration of Gemini across platforms reflects Google's commitment to providing users with a seamless and advanced AI experience, pushing the boundaries of innovation in the digital landscape.

HTML Interview Questions and Answers (2024).

In the dynamic world of web development, mastering HTML is the foundation for crafting engaging and user-friendly websites. In this article, we have covered the top 30+ HTML interview questions, providing comprehensive answers to help you not only crack interviews but also deepen your grasp of HTML essentials. 

HTML Interview Questions

1. What is HTML?

HTML stands for HyperText Markup Language. It is the standard markup language used to create the structure and layout of web pages. HTML utilizes a system of tags to define elements such as headings, paragraphs, links, images, and more. These elements form the building blocks of a webpage.

2. What does HTML stand for?

HTML stands for HyperText Markup Language.

3. What is the latest version of HTML?

HTML5 is the latest version of HTML. HTML5 represents the fifth revision of the HTML standard and includes new features, improvements, and enhanced support for multimedia and interactivity. Keep in mind that the web development landscape evolves, and it's advisable to check for the latest updates and versions as standards progress.

4. What are the new features of HTML5?

HTML5 introduces several new features and improvements over its predecessors, enhancing the capabilities of web development. Here are some key features of HTML5:

  • Semantic Elements: New semantic elements like `<header>`, `<footer>`, `<article>`, `<section>`, and `<nav`> provide clearer document structure.
  • Audio and Video Support: Native support for embedding audio and video content using the `<audio>` and `<video>` elements, eliminating the need for third-party plugins like Flash.
  • Canvas Element: The `<canvas>` element allows dynamic rendering of graphics, enabling the creation of interactive and animated content directly within the browser.
  • New Form Input Types: Additional form input types such as `<email>`, `<url>`, `<tel>`, `<number>`, `<date>`, and more enhance the user experience and provide better input validation.
  • Local Storage: Introducing the `localStorage` object enables web applications to store data locally on the user's device, improving offline capabilities and performance.
  • Web Workers: Web Workers allow the execution of scripts in the background, enabling parallel processing and improved performance without affecting the main user interface.
  • Geolocation API: The Geolocation API provides native support for obtaining the user's geographical location, enabling location-based services in web applications.
  • Offline Web Applications: HTML5 includes features like the Application Cache and the `manifest` attribute, allowing web applications to work offline and providing a better user experience.
  • New Structural Elements: Introduction of elements like `<article>`, `<aside>`, `<mark>`, `<progress>`, `<output>`, and more for better document structure and semantics.
  • Drag-and-Drop Support: Native support for drag-and-drop functionality simplifies the implementation of interactive interfaces and content manipulation.
  • WebSocket: The WebSocket API enables bidirectional communication between the browser and the server, facilitating real-time updates and data exchange.
  • Web Storage: Alongside `localStorage`, HTML5 also introduces `sessionStorage` for storing session-specific data on the client side.

These features collectively contribute to a more feature-rich and efficient web development environment. It's important to note that the specifications and support for HTML5 features may vary among different browsers, and developers should consider compatibility issues while implementing them. 

5. Explain the Basic Structure of HTML.

The basic structure of an HTML document includes the following essential elements:
  • Document Type Declaration: The <!DOCTYPE html> declaration at the beginning of the HTML document defines the document type and version. It helps browsers to render the page correctly.
  • HTML Root Element: The <html> element serves as the root element of the HTML document. It wraps the entire content and includes language attributes such as lang to specify the language of the document.
  • Head Section: The <head> element contains metadata about the document, such as the title, character set, linked stylesheets, and scripts.
  • Body Section: The <body> element encloses the main content of the HTML document, including text, images, links, forms, and other elements that make up the visible part of the webpage.
Example:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Webpage</title>
    <!-- Additional meta tags, stylesheets, and scripts can be added here -->
  </head>

  <body>
    <!--This section will be visible to the end user-->
  </body>
</html>

6. What is the purpose of <!DOCTYPE> declaration?

The <!DOCTYPE> declaration, short for Document Type Declaration, is a crucial element at the beginning of an HTML document. Its primary purpose is to specify the document type and version of HTML or XHTML that the web page is using. This declaration helps the web browser to interpret and render the document correctly.

7. Difference Between HTML and XHTML.

HTML (HyperText Markup Language):

  • Nature: HTML is more forgiving and lenient in terms of syntax rules.
  • Parsing: Browsers are forgiving and can render a page even with syntax errors.
  • Tags: Case sensitivity is not strict, and tags can be written in uppercase or lowercase.
  • Self-Closing Tags: Self-closing tags are optional (e.g., `<img>` or `<br>`).

XHTML (eXtensible HyperText Markup Language):

  • Nature: XHTML is stricter and follows XML syntax rules.
  • Parsing: Browsers are less forgiving; a small syntax error can break the rendering.
  • Tags: Case sensitivity is strict, and all tags must be written in lowercase.
  • Self-Closing Tags: Self-closing tags are mandatory (e.g., `<img />` or `<br />`).

8. What is semantic HTML? Can you give examples?

Semantic HTML refers to using HTML elements that carry meaning about the structure and content of a webpage. It provides clarity to both browsers and developers, enhancing accessibility and search engine optimization.

Examples:
  • <header>: Represents the header of a section or page.
  • <nav>: Defines a navigation menu.
  • <article>: Represents an independent, self-contained piece of content.
  • <section>: Defines a section in a document.
  • <aside>: Represents content tangentially related to the content around it.
  • <footer>: Represents the footer of a section or page.
  • <figure> and <figcaption>: Used to encapsulate media and its caption.

Using these elements makes the HTML code more meaningful and aids in creating a clearer document structure.

9. Explain the difference between Block-Level Elements and Inline Elements.

Block-Level: Block-level elements create a new block or box in the layout, starting on a new line and stretching the full width of the parent container.
Examples: <div>, <p>, <h1>-<h6>, <ul>, <li>, <section>.

Inline-Element: Simple Answer: Inline elements flow within the content and do not create new blocks. They only take up as much width as necessary.
Examples: <span>, <a>, <strong>, <em>, <img>, <br>.

10. What is the purpose of <head> element in HTML?

The `<head>` element in HTML is used to contain metadata about the document, such as the title, character set, linked stylesheets, scripts, and other essential information that is not directly displayed on the webpage.

11. What is the use of <meta> elements in HTML?

The `<meta>` element in HTML is used to provide metadata about the document. Commonly, it includes information like the character set, viewport settings for responsive design, and keywords relevant to search engines.

12. What is the meaning of initial-scale=1.0 in HTML?

`initial-scale=1.0` in the viewport meta tag of HTML sets the initial zoom level of the webpage to 1.0, meaning it doesn't zoom in or out when the page is first loaded. This is commonly used for responsive web design to ensure proper scaling on various devices.

13. What are attributes in HTML?

Attributes in HTML provide additional information about HTML elements. They are included in the opening tag and modify the element's behavior or appearance. Examples include `src` in `<img>` for the image source and `href` in `<a>` for the hyperlink destination.

14. What is the purpose of 'alt' attribute in <img> tag?

The `alt` attribute in the `<img>` tag provides alternative text for an image. It serves as a descriptive text that is displayed if the image cannot be loaded or for accessibility purposes, helping users with visual impairments understand the content of the image.

15. How to create a Hyperlink in HTML?

To create a hyperlink in HTML, use the <a> (anchor) element. Set the href attribute to the URL you want to link to, and include the text or content between the opening and closing <a> tags.
Example:
<a href="https://www.example.com">Visit Example.com</a>

16. What is the difference Between <ol> and <ul> element?

  • <ol> (Ordered List): Represents a list where items are ordered or numbered sequentially.
  • <ul> (Unordered List): Represents a list where items are not ordered and are typically displayed with bullets.
Example:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Example Code</title>
  </head>

  <body>
    <ol>
      <li>Item 1</li>
      <li>Item 2</li>
    </ol>
    <ul>
      <li>Item A</li>
      <li>Item B</li>
    </ul>
  </body>
</html>
Output:
HTML ordered and unordered list example

17. Difference Between Tags and Elements.

Tag: A tag is a specific code enclosed in angle brackets that defines an HTML element.
  • Example: <p>, <a>, <img>
Element: An element consists of the opening tag, content, and closing tag, representing a complete and functional unit in HTML.
  • Example: <p>This is a paragraph.</p>

18. Explain the purpose of <iframe> tag.

The `<iframe>` (Inline Frame) tag is used to embed another HTML document or external content within the current HTML document. It allows for the inclusion of external web pages, videos, maps, or other interactive elements while keeping them separate from the main document's structure.

19. What is the importance of the lang attribute in <HTML> tag?

The `lang` attribute in the `<html>` tag is important for indicating the language of the HTML document. It helps search engines and assistive technologies understand the language of the content, aiding in proper indexing, accessibility, and text-to-speech functionalities.

20. How do you embed audio and video in HTML?

To embed audio and video in HTML, you can use the <audio> and <video> elements, specifying the source (src) attribute with the file URL. For example:

<audio controls>
  <source src="audio.mp3" type="audio/mp3">
  Your browser does not support the audio tag.
</audio>

<video width="320" height="240" controls>
  <source src="video.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

21. What is the use of the HTML5 Canvas element?

The HTML5 `<canvas>` element is used for drawing graphics, animations, and interactive content on a webpage using JavaScript. It provides a drawing surface that allows developers to create dynamic visual elements, charts, games, and more directly within the browser.

22. What are HTML Forms?

HTML forms are a set of elements that enable users to input and submit data on a webpage. They typically include input fields, checkboxes, radio buttons, and buttons. When submitted, the form data can be processed on the server or handled with client-side scripting.

23. What is the purpose of the 'required' attribute in a Form?

The `required` attribute in a form is used to specify that a particular input field must be filled out before submitting the form. It helps ensure that users provide necessary information and prevents the submission of incomplete forms.

24. What is the role of <label> element in a form?

The `<label>` element in a form is used to associate a text label with a form control, such as an input field. This improves accessibility and user experience, as clicking on the label focuses or activates the associated form control. It also provides a clear description of the expected input for screen readers and visual users.

25. How do you create a dropdown list in HTML?

To create a dropdown list in HTML, use the <select> element along with the <option> elements for each item in the list. This creates a dropdown menu with three options. The value attribute in each <option> tag represents the data sent to the server when the form is submitted.
For example:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Example Code</title>
  </head>

  <body>
    <h3>Drop Down List</h3>
    <select>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>
  </body>
</html>
Output:
HTML Dropdown menu example

26. What is the purpose of the 'colspan' and 'rowspan' attributes in a table?

The colspan and rowspan attributes in a table are used to merge or span multiple columns or rows, respectively. They define the number of columns or rows a cell should span.
  • colspan: Specifies the number of columns a table cell should span horizontally.
  • rowspan: Specifies the number of rows a table cell should span vertically.
Example:
HTML table colspan and rowspan example

27. Explain the concept of HTML Entities.

HTML entities are special codes or sequences that represent reserved characters in HTML. They are used to display characters that have a specific meaning in HTML, such as `<` or `&`, without triggering their usual interpretation. For example, `&lt;` represents `<`, and `&amp;` represents `&`. This ensures proper rendering and prevents ambiguity in the displayed content.

28. Explain the importance of the 'rel' attribute in the <a> tag.

The `rel` attribute in the `<a>` tag (anchor) defines the relationship between the linked document and the current document. It provides additional information about the type of link, such as whether it's a stylesheet (`rel="stylesheet"`), an icon (`rel="icon"`), or part of a navigation menu (`rel="next"` or `rel="prev"`). This information is crucial for browsers, search engines, and other user agents to interpret and handle the link appropriately.

29. Explain the difference between cookies and local storage.

Cookies:
  • Small pieces of data are stored on the client side.
  • Sent with every HTTP request, impacting performance.
  • Typically limited to 4KB in size.
  • Has an expiration date and can be set for sessions or persisted.
  • Used for client-server communication and maintaining user sessions.
Local Storage:
  • Larger storage capacity (typically 5-10MB per domain).
  • Not automatically sent with HTTP requests, reducing overhead.
  • Persists even after the browser is closed.
  • Accessed via the `localStorage` object in JavaScript.
  • Used for client-side data storage, improving performance for some scenarios.

30. How To Disable Form Elelemt in HTML?

To disable a form element in HTML, you can use the disabled attribute. This renders the input field as disabled, preventing user interaction. The same attribute can be applied to other form elements such as buttons and selects.

For example:
<input type="text" name="username" disabled>

31. Explain the concept of HTML Microdata.

HTML microdata is a specification that allows developers to embed machine-readable metadata directly into HTML content. It provides a way to annotate information about the content, making it more understandable for search engines and other applications. Microdata uses specific attributes like `itemscope`, `itemtype`, and `itemprop` to define structured data, improving the semantics and context of the content for better search engine indexing and data interpretation.

32. What is a tooltip in HTML?

A tooltip is a small, pop-up box that appears when a user hovers over an element (like a link or button) on a webpage. It typically displays additional information or a description related to the hovered element, providing users with context or details without requiring a click or navigation. Tooltips are commonly used for enhancing user experience and providing quick information about elements on a page.

33. Difference between <div> and <span> tag.

  • <div>: A block-level element used for grouping and structuring content. It typically starts on a new line and takes up the full width of its container.
  • <span>: An inline element used for applying styles or scripting to a specific portion of text within a larger block. It does not create a new block and only takes up as much width as its content.

34. How to add a comment in HTML?

To add a comment in HTML, use the <!-- and --> tags. Anything between these tags is treated as a comment and is not displayed in the browser.
<!-- This is a comment in HTML -->
<p>This is a paragraph.</p>

So far we have covered 30+ HTML Interview questions and answers and we hope you will find them useful for your interview preparation. Continue to explore, practice, and refine your HTML expertise, as the language remains at the forefront of creating seamless and innovative web experiences. Happy coding!

Google New TensorFlow for Graph Neural Networks.

Tensorflow for Graph Neural Network


Highlight:TF-GNN's tfgnn.GraphTensor object and integrated gradients feature propel TensorFlow's ecosystem, enabling efficient handling of diverse graph structures and offering valuable insights into influential features for improved machine learning model training and evaluation.
In a significant stride towards advancing machine learning capabilities, the Google TensorFlow team has unveiled TensorFlow GNN 1.0 (TF-GNN), a cutting-edge update to its machine learning framework. TF-GNN is specifically engineered to empower the development and scalability of graph neural networks (GNNs), enabling intricate analyses of complex networks such as transportation and social networks.

This new library marks a pivotal moment in the evolution of machine learning, as TF-GNN seamlessly blends the structural intricacies of graphs with the features of their nodes. Bridging the gap between discrete graph data and continuous neural network models, TF-GNN enhances the TensorFlow ecosystem's capacity for more detailed predictions and analyses, particularly in scenarios involving diverse node and edge types.

At the core of TF-GNN's advancements lies the tfgnn.GraphTensor object, a groundbreaking addition that represents heterogeneous graphs characterized by diverse node and edge types. This integration proves instrumental in efficiently handling graph data, enabling the TensorFlow ecosystem to navigate and manage complex network structures seamlessly.

The Python API introduced by TF-GNN offers developers a versatile toolkit, allowing for the configuration of subgraph sampling tailored to various computational environments, from individual workstations to distributed systems. This flexibility is paramount for handling datasets of varying sizes and complexities, providing a robust solution for diverse machine-learning applications.

One of the standout features of TF-GNN is its introduction of integrated gradients for model attribution. This enhancement sheds light on the features most influential in predictions, offering valuable insights for model training and evaluation. TF-GNN's holistic approach to understanding graph structures contributes to improved predictions on entire graphs, individual nodes, or potential edges, making it a powerful tool across a spectrum of applications.

TensorFlow GNN 1.0 is seamlessly integrated into the TensorFlow ecosystem, providing developers worldwide with accessible resources, comprehensive documentation, and code samples. As the machine learning landscape evolves, TF-GNN emerges as a formidable asset, propelling the capabilities of graph neural networks to new heights and fostering innovation in the field.

Microsoft Plans to Provide AI Skills to 2M Indians.

Microsoft AI Training for 2Million Indians


Highlight: Nadella urges India to embrace AI's transformative potential, announcing Microsoft's plan to provide AI skilling opportunities to 2 million in smaller cities while highlighting Karya, an ethical data company contributing to rural empowerment.

In a resounding testament to Microsoft's prowess in the realm of artificial intelligence (AI), CEO Satya Nadella asserted the company's leading position in the field, declaring its AI model to be superior to even the much-hyped GPT-4. Speaking at a company event in Mumbai, Nadella's candid remarks underscored Microsoft's unwavering commitment to innovation and technological advancement.


Nadella's address to the leaders of India's largest companies showcased Microsoft's aggressive investments in AI and its impact on shaping the future of industries worldwide. Emphasizing the transformative potential of AI, Nadella urged businesses to embrace the technology to enhance productivity and refine their products, cautioning against falling behind in an increasingly competitive landscape.


The Microsoft executive's call to action extended to India as he urged the nation to intensify efforts in harnessing AI's capabilities, predicting its profound impact on the country's GDP. With India emerging as the second largest talent base for AI developers on GitHub, Nadella highlighted the nation's potential to lead in AI innovation and development.

Puneet Chandok, leading Microsoft's India and South Asia business, echoed Nadella's sentiments, emphasizing India's transition from incredibility to credibility in the global technology landscape. Chandok's remarks underscored India's burgeoning aspirations and commitment to realizing ambitious dreams in the AI arena.


As part of Microsoft's initiatives to empower Indian talent, the company announced plans to offer AI skilling opportunities to 2 million individuals in smaller cities and towns by the next year, signaling a concerted effort to bridge the digital divide and promote socio-economic progress.


Nadella also spotlighted Karya, an "ethical data company" leveraging AI to create datasets in multiple Indian languages while empowering rural communities through employment and education opportunities. This unique offering exemplifies India's innovative approach to AI, paving the way for localized solutions tailored to the nation's diverse needs and challenges.


In Nadella's eyes, India stands at the forefront of AI innovation, with its distinctive use cases and aspirations converging seamlessly with global trends. As India continues to chart its path in the AI landscape, Microsoft's unwavering commitment to empowering individuals and businesses alike sets the stage for a future defined by technological advancement and inclusive growth. 

Stock Span Problem Using Stack.

The stock span problem is a financial problem where we have a series of daily price quotes for a stock and we need to calculate the span of the stock's price for each day. The span of the stock's price for a particular day is defined as the maximum number of consecutive days (including the current day) for which the stock price is less than or equal to the price of the current day.

Example:

Input: [100, 80, 60, 70, 60, 75, 85]

Output: [1, 1, 1, 2, 1, 4, 6]

Explanation:

  • For day 1 (100), the span is 1, as it is the first day.
  • For day 2 (80), the span is 1, as the previous day's price (100) is greater.
  • For day 3 (60), the span is 1, as the previous day's price (80) is greater.
  • For day 4 (70), the span is 2, as the previous day's price (60) is smaller, so we include the day before that (60).
  • For day 5 (60), the span is 1, as the previous day's price (70) is greater.
  • For day 6 (75), the span is 4, as the previous day's price (60) is smaller, so we include the three days before that (60, 70, 60).
  • For day 7 (85), the span is 6, as the previous day's price (75) is smaller, so we include the five days before that (60, 70, 60, 75, 85).


There are many ways to solve this problem, popularly it is solved using stack or dynamic programming and here we are going to discuss all these approaches in detail starting with the brute force approach.

Stock Span Problem Using Brute Force Approach.

In this approach, for each day, we traverse backward and count the number of consecutive days with prices less than or equal to the current day's price. Traverse backward from i-1 to 0 and for each previous day j, compare the stock price at day i with the stock price at day j.

Below is the code implementation of the above approach:
// Cpp program for stock span problem (brute force)
#include <iostream>
#include <vector>
using namespace std;

vector<int> calculateSpan(const vector<int>& prices) {
    int n = prices.size();
    vector<int> span(n, 1);

    for (int i = 0; i < n; ++i) {
        int spanValue = 1;
         
        //traverse backwards and count the number of consecutive days 
        for (int j = i - 1; j >= 0 && prices[j] <= prices[i]; --j) {
            spanValue++;
        }

        span[i] = spanValue;
    }

    return span;
}

int main() {
    vector<int> stockPrices = {100, 80, 60, 70, 60, 75, 85};
    vector<int> span = calculateSpan(stockPrices);

    cout << "Stock Prices: ";
    for (int price : stockPrices) {
         cout << price << " ";
    }

    std::cout << "\nSpans: ";
    for (int s : span) {
        std::cout << s << " ";
    }

    return 0;
}
// Java program for stock span problem - brute force approach
import java.util.Arrays;

public class StockSpan {
    public static void main(String[] args) {
        int[] prices = {100, 80, 60, 70, 60, 75, 85};
        int[] span = calculateSpan(prices);

        System.out.println("Stock Prices: " + Arrays.toString(prices));
        System.out.println("Spans: " + Arrays.toString(span));
    }

    public static int[] calculateSpan(int[] prices) {
        int n = prices.length;
        int[] span = new int[n];
        Arrays.fill(span, 1);

        for (int i = 0; i < n; ++i) {
            int spanValue = 1;
            //traverse backwards and count the number of consecutive days
            for (int j = i - 1; j >= 0 && prices[j] <= prices[i]; --j) {
                spanValue++;
            }

            span[i] = spanValue;
        }

        return span;
    }
}
# Python program to solve stock span problem
def calculate_span(prices):
n = len(prices)
span = [1] * n

for i in range(1, n):
    span_value = 1

    for j in range(i - 1, -1, -1):
        if prices[j] > prices[i]:
            break
        span_value += 1

    span[i] = span_value

return span

stock_prices = [100, 80, 60, 70, 60, 75, 85]
span = calculate_span(stock_prices)

print("Stock Prices: " + str(stock_prices))
print("Spans: " + str(span))
// C# code to solve stock span problem - brute force
using System;

class StockSpan {
    public static void Main() {
        int[] prices = {100, 80, 60, 70, 60, 75, 85};
        int[] span = CalculateSpan(prices);

        Console.WriteLine("Stock Prices: " + string.Join(" ", prices));
        Console.WriteLine("Spans: " + string.Join(" ", span));
    }

    public static int[] CalculateSpan(int[] prices) {
        int n = prices.Length;
        int[] span = new int[n];
        Array.Fill(span, 1);

        for (int i = 0; i < n; ++i) {
            int spanValue = 1;

            for (int j = i - 1; j >= 0 && prices[j] <= prices[i]; --j) {
                spanValue++;
            }

            span[i] = spanValue;
        }

        return span;
    }
}
Output:
Stock Prices: 100 80 60 70 60 75 85 
Spans: 1 1 1 2 1 4 6 

Time Complexity: O(n^2).
Space Complexity: O(1).

Stock Span Problem Using Stack.

In this approach, we utilize a stack to efficiently calculate the span of stock prices. We traverse the array of stock prices once and maintain a stack of previous days' indices along with their corresponding span values. Below are the algorithm steps that you follow for better understanding.

Algorithm Steps:
  • Create an empty stack to store indices.
  • Initialize an array span of the same size as the number of days, initially filled with zeros. This array will store the span for each day.
  • Iterate through each day, starting from the first day.
  • -- While the stack is not empty and the price of the stock on the current day is greater than the price on the day represented by the index at the top of the stack: Pop the index from the stack.
  • -- If the stack is empty, set the span for the current day as the current day itself; otherwise, set it as the difference between the current day and the day represented by the index at the top of the stack.
  • -- Push the current day's index onto the stack.
  • After completing the iteration, the span array contains the span for each day.

Below is the code implementation for the above approach:
// Stock span problem using stack
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

vector<int> calculateSpan(const vector<int>& prices) {
    stack<int> st;
    vector<int> span(prices.size(), 0);

    for (int i = 0; i < prices.size(); ++i) {
        while (!st.empty() && prices[i] >= prices[st.top()]) {
            st.pop();
        }

        span[i] = st.empty() ? i + 1 : i - st.top();
        st.push(i);
    }

    return span;
}

int main() {
    vector<int> prices = {100, 80, 60, 70, 60, 75, 85};
    vector<int> span = calculateSpan(prices);

    cout << "Stock Prices: ";
    for (int price : prices) {
        cout << price << " ";
    }

    cout << "\nStock Spans: ";
    for (int s : span) {
        cout << s << " ";
    }

    return 0;
}
// Stock Span Problem Using Stack
import java.util.Stack;
import java.util.Arrays;

public class StockSpan {
    public static void main(String[] args) {
        int[] prices = {100, 80, 60, 70, 60, 75, 85};
        int[] span = calculateSpan(prices);

        System.out.println("Stock Prices: " + Arrays.toString(prices));
        System.out.println("Stock Spans: " + Arrays.toString(span));
    }

    public static int[] calculateSpan(int[] prices) {
        Stack<Integer> st = new Stack<>();
        int[] span = new int[prices.length];

        for (int i = 0; i < prices.length; i++) {
            while (!st.isEmpty() && prices[i] >= prices[st.peek()]) {
                st.pop();
            }

            span[i] = st.isEmpty() ? i + 1 : i - st.peek();
            st.push(i);
        }

        return span;
    }
}
# Python code for stock span problem using stack
def calculate_span(prices):
stack = []
span = [0] * len(prices)

for i in range(len(prices)):
    while stack and prices[i] >= prices[stack[-1]]:
        stack.pop()

    span[i] = len(stack) if not stack else i - stack[-1]
    stack.append(i)

return span

prices = [100, 80, 60, 70, 60, 75, 85]
span = calculate_span(prices)

print("Stock Prices: " + str(prices))
print("Stock Spans: " + str(span))
// C# code for stock span problem using stack
using System;
using System.Collections.Generic;

public class StockSpan {
    public static void Main(string[] args) {
        int[] prices = {100, 80, 60, 70, 60, 75, 85};
        int[] span = CalculateSpan(prices);

        Console.WriteLine("Stock Prices: " + string.Join(" ", prices));
        Console.WriteLine("Stock Spans: " + string.Join(" ", span));
    }

    public static int[] CalculateSpan(int[] prices) {
        Stack<int> st = new Stack<int>();
        int[] span = new int[prices.Length];

        for (int i = 0; i < prices.Length; i++) {
            while (st.Count > 0 && prices[i] >= prices[st.Peek()]) {
                st.Pop();
            }

            span[i] = st.Count == 0 ? i + 1 : i - st.Peek();
            st.Push(i);
        }

        return span;
    }
}
Output:
Stock Prices: 100 80 60 70 60 75 85 
Spans: 1 1 1 2 1 4 6 

Time Complexity: O(n).
Space Complexity: O(n).

There are many other approaches as well to solve this problem like by using Dynamic Programming and Monitonic Stack that we have covered separately in other articles.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson