code-rag-bench/online-tutorials huggingface dataset:
Architecture of an Embedded System | Set-3 - GeeksforGeeks

09 Jun, 2020
Typical embedded system mainly has two parts i.e., embedded hardware and embedded software.
Embedded hardwares are based around microprocessors and microcontrollers, also include memory, bus, Input/Output, Controller, where as embedded software includes embedded operating systems, different applications and device drivers. Basically these two types of architecture i.e., Havard architecture and Von Neumann architecture are used in embedded systems.
Architecture of the Embedded System includes Sensor, Analog to Digital Converter, Memory, Processor, Digital to Analog Converter, and Actuators etc.
The below figure illustrates the overview of basic architecture of embedded systems :
Embedded Product Development Life Cycle (EDLC) :Developing an embedded system or product mainly goes through this three phases which are –
1. Analysis
2. Design
3. Implementation 
If we will go a little bit deeper to the development steps it includes these 7 steps :
Requirement analysisExamineDesignDevelopTestDeployMaintenance
Requirement analysis
Examine
Design
Develop
Test
Deploy
Maintenance
Now Let’s discuss some of the advantages and disadvantages of Embedded systems.
Advantages of Embedded System :
Embedded systems are fast in performance.
These systems consumes less power
Small in shape and size.
These systems are so scalable and reliable.
Works on wide variety of sectors and environments.
Improve product quality and enhance performance.
Performs specific tasks without error.
Disadvantages of Embedded System :
Difficult to backup of embedded files.
Sometimes complex to develop.
Integration may be a problem.
Offer very limited resources for processing.
Troubleshooting may be difficult.
Maintenance may be a problem.
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Architecture of 8086
Logical and Physical Address in Operating System
Addressing modes in 8085 microprocessor
8085 program to add two 8 bit numbers
Architecture of 8085 microprocessor
Computer Organization | RISC and CISC
Interrupts
Memory Hierarchy Design and its Characteristics
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Programmable peripheral interface 8255
How to create a directory hierarchy using Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
The mkdir() method of this class creates a directory with the path represented by the current object.
To create a hierarchy of new directories you can using the method mkdirs() of the same class. This method creates the directory with the path represented by the current object, including non-existing parent directories.
 Live Demo
import java.io.File;
import java.util.Scanner;
public class CreateDirectory {
   public static void main(String args[]) {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String path = sc.next();
      System.out.println("Enter the name of the desired a directory: ");
      path = path+sc.next();
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdirs();
      if(bool) {
         System.out.println("Directory created successfully");
      }else {
         System.out.println("Sorry couldnt create specified directory");
      }
   }
}
Enter the path to create a directory:
D:\test\myDirectories\
Enter the name of the desired a directory:
sample_directory
Directory created successfully
If you verify you can observe see the created directory as −
How to get current time zone in android using clock API class?

This example demonstrate about How to get current time zone in android using clock API class.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
   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/date"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Local Date"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show current time zone.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.time.Clock;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView = findViewById(R.id.date);
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
         Clock clock = Clock.systemDefaultZone();
         textView.setText(String.valueOf(clock.getZone()));
      }
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it is showing the current time zone.
Click here to download the project code
How to add a mathematical expression in axis label in a plot created by using plot function in R?

When we create a plot using plot function in R, the axes titles are either chosen by R automatically based on the vectors passed through the function or we can use ylab or xlab for particular axes. To add a mathematical expression in an axis label, we can use title function with expression function to define the mathematical expression.
Consider the below vectors and create scatterplot between the two −
set.seed(111)
x<-rpois(1000,20)
y<-rpois(1000,15)
plot(x,y)
Now suppose, we want to remove y from the Y-axis and put alpha square then it can be done as shown below −
plot(x,y,ylab="")
title(ylab=expression(alpha^2))
Select iframe using Python and Selenium

We can select iframe with Selenium webdriver. An iframe is identified with a <iframe> tag in an html document. An iframe is an html document containing elements which resides inside another html document.
Let us see a html document of a frame.
The following methods help to switch between iframes−
switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of iframe is 0.Syntax−driver.switch_to.frame(0), switching to the first iframe.
switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of iframe is 0.
Syntax−
driver.switch_to.frame(0), switching to the first iframe.
switch_to.frame(args) - The frame name or id is put as an argument to the method.Syntax−driver.switch_to.frame("nm"), switching to the iframe with name nm.
switch_to.frame(args) - The frame name or id is put as an argument to the method.
Syntax−
driver.switch_to.frame("nm"), switching to the iframe with name nm.
switch_to.frame(args) - The frame webelement is put as an argument to the method.Syntax−driver.switch_to.frame(f),switching to the iframe with webelement f.
switch_to.frame(args) - The frame webelement is put as an argument to the method.
Syntax−
driver.switch_to.frame(f),switching to the iframe with webelement f.
switch_to.default_content() – To shift to the parent page from the iframe.Syntax−driver.switch_to.default_content()
switch_to.default_content() – To shift to the parent page from the iframe.
Syntax−
driver.switch_to.default_content()
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://the-internet.herokuapp.com")
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# switch to frame with name
driver.switch_to.frame("frame-bottom")
# identify element and get text method
s = driver.find_element_by_xpath("//body").text
print ("Test inside frame: " + s)
# move out of frame to parent page
driver.switch_to.default_content()
driver.quit()
card-title class in Bootstrap 4

Use the card-title class in Bootstrap 4 to set title for the card like the following example −
The card title set above used the card-title class inside the card-body class. In addition, I have used the card-text class to set text inside the Bootstrap card as shown in the below give code snippet −
<div class="card-body">
  <h4 class="card-title">Company Locations</h4>
  <p class="card-text">Singapore</p>
  <p class="card-text">Malaysia</p>
  <p class="card-text">Australia</p>
</div>
You can try to run the following code to implement the card-title class −
Live Demo
<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>
<body>

<div class="container">
  <h2>Location</h2>
  <div class="card">
    <div class="card-body">
      <h4 class="card-title">Company Locations</h4>
      <p class="card-text">Singapore</p>
      <p class="card-text">Malaysia</p>
      <p class="card-text">Australia</p>
    </div>
  </div>
</div>

</body>
</html>
Express.js res.attachment() Function - GeeksforGeeks

19 Oct, 2021
The res.attachment() function is used to set the HTTP response Content-Disposition header field to ‘attachment’. If the name of the file is given as filename, then it sets the Content-Type based on the extension name through res.type() function and finally sets the Content-Disposition ‘filename = ‘ parameter.Syntax:  
res.attachment( [filename] )
Parameter: The filename parameter describes the the name of the file.Return Value: It returns an Object.Installation of express module:  
You can visit the link to Install express module. You can install this package by using this command.  
npm install express
After installing the express module, you can check your express version in command prompt using the command.  
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.  
node index.js
Example 1: Filename: index.js  
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){    res.attachment('Hello.txt');    console.log(res.get('Content-Disposition'));}); app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Place any file in root directory of the project which can be attached, like here we have used Hello.txt.Steps to run the program:  
The project structure will look like this:  
The project structure will look like this:  
Make sure you have installed express module using the following command: 
npm install express
Run index.js file using below command: 
node index.js
Output: 
Server listening on PORT 3000
Open your browser and go to http://localhost:3000/, now you can see the following output on your console: 
Server listening on PORT 3000
attachment; filename="Hello.txt"
sweetyty
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
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?
Convert a list into a tuple in Python.

Sometimes during data analysis using Python, we may need to convert a given list into a tuple. Because some downstream code may be expecting to handle tuple and the current list has the values for that tuple. In this article we will see various ways to do that.
This is a straight way of applying the tuple function directly on the list. The list elements get converted to a tuple.
 Live Demo
listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = tuple(listA)
# Result
print("The tuple is : ",res)
Running the above code gives us the following result −
Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : ('Mon', 2, 'Tue', 3)
We can apply the * operator we can expand the given list and put the result in a parentheses.
listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = (* listA,)
# Result
print("The tuple is : ",res)
Running the above code gives us the following result −
Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : ('Mon', 2, 'Tue', 3)
Combine multiple images using one dockerfile

When you are working on a large project on docker, you need to go through certain phases of the development cycle. Maintaining a different dockerfile for each cycle such as build, release, testing etc. eats up a lot of resources and is highly inefficient when it comes to productivity.
In the later versions of docker, it allows us to use what is called multi-stage Dockerfile with the help of two particular commands - FROM and AS.
We can use multiple FROM commands combined with AS commands in our Dockerfile where the last FROM command will actually build the image. All the FROM commands before that, will lead to the creation of intermediate images which are cached regularly.
The AS command when used with the FROM command allows us to provide a virtual name for our intermediate images.
Let us consider an example below for better understanding.
#We create a base image.
FROM ubuntu AS base

#Install packages
RUN apt-get -y update
RUN apt-get -y vim

#Create intermediate image layer Dependencies
FROM base AS dependencies

#Install dependencies using a requirements file
RUN pip3 install -r requirements.txt

#Create intermediate image layer for Testing
FROM dependencies AS test

#Set your work directory
WORKDIR /usr/src/app

COPY . .

#Build the final image by running the test file
CMD [“python3”, “./test.py”]
As we can see in the above dockerfile, we have created two intermediate images called base and dependencies. The base intermediate image is an ubuntu image and we update it and install vim editor inside it. Using that base image, to create an intermediate image called dependencies, we install certain dependencies for our project which we can define in a separate file called requirements.txt. The final image is created by the test image layer where we define the working directory, copy the files and run the test.py file.
The order of building the images is base, then dependencies and at last test. We also have to note that in case, any of the intermediate images fails to build, the final image cannot be created.
Thus, creating a multi-stage dockerfile helps when you are working on a large scale project development with various phases of development surely helps us track the changes and progress efficiently.
Python | Stemming words with NLTK

08 Jun, 2022
Stemming is the process of producing morphological variants of a root/base word. Stemming programs are commonly referred to as stemming algorithms or stemmers. A stemming algorithm reduces the words “chocolates”, “chocolatey”, and “choco” to the root word, “chocolate” and “retrieval”, “retrieved”, “retrieves” reduce to the stem “retrieve”.
Prerequisite: Introduction to Stemming
Some more example of stemming for root word "like" include:

-> "likes"
-> "liked"
-> "likely"
-> "liking"
Errors in Stemming: There are mainly two errors in stemming – Overstemming and Understemming. Overstemming occurs when two words are stemmed from the same root that are of different stems. Under-stemming occurs when two words are stemmed from the same root that is not of different stems.
Applications of stemming are:  
Stemming is used in information retrieval systems like search engines.
It is used to determine domain vocabularies in domain analysis.
Stemming is desirable as it may reduce redundancy as most of the time the word stem and their inflected/derived words mean the same.
Below is the implementation of stemming words using NLTK:
Code #1:  
Python3
# import these modulesfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize ps = PorterStemmer() # choose some words to be stemmedwords = ["program", "programs", "programmer", "programming", "programmers"] for w in words:    print(w, " : ", ps.stem(w))
Output: 
program  :  program
programs  :  program
programmer  :  program
programming  :  program
programmers  :  program
Code #2: Stemming words from sentences
Python3
# importing modulesfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize ps = PorterStemmer() sentence = "Programmers program with programming languages"words = word_tokenize(sentence) for w in words:    print(w, " : ", ps.stem(w))
Output : 
Programmers  :  program
program  :  program
with  :  with
programming  :  program
languages  :  language
sumitgumber28
sooda367
Code_r
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Getting started with Machine Learning
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Support Vector Machine Algorithm
Random Forest Regression in Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to multiply a matrix by its transpose while ignoring missing values in R ?

21 Apr, 2021
In this article, we will discuss how to multiply a matrix by its transpose while ignoring the missing values in R Programming Language. It can be done by replacing all the NAs by 0 in the matrix
The replacement of values, can be performed in O(n*m), where n is the number of rows and m is the number of columns. Replacing by 0s doesn’t affect the multiplicative product, and therefore, this is an effective solution. The transpose can then be calculated by using t(matrix). The product can be calculated by the following syntax in R : 
m1 %*% m2 , where m1 and m2 are the matrices involved. 
If m1 is the matrix of n*m dimensions and m2 of m*n (since it’s the transpose), the product matrix obtained is a square matrix is n * n .
Example 1:
R
# declaring matrix mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2)  # replacing matrix NA with 0smat[is.na(mat)] = 0  # printing original matrixprint ("Original Matrix")print (mat)  # calculating transpose of the# matrixtransmat = t(mat)print ("Transpose Matrix")print (transmat)  # calculating product of matricesprod = mat%*%transmatprint ("Product Matrix")print (prod)
Output:
[1] "Original Matrix"
    [,1] [,2]
[1,]    1    3
[2,]    0    0
[3,]    2    4
[1] "Transpose Matrix"
    [,1] [,2] [,3]
[1,]    1    0    2
[2,]    3    0    4
[1] "Product Matrix"
    [,1] [,2] [,3]
[1,]   10    0   14
[2,]    0    0    0
[3,]   14    0   20
The original matrix is of the dimensions 3 x 2 and the transpose is of the dimension 2×3. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 3×3 square matrix. 
Example 2: The original matrix is of the dimensions 1 x 3 and the transpose is of the dimension 3×1. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 1×1 square matrix, which is basically a singular cell matrix. 
R
# declaring matrix mat = matrix(c(10, NA, 7), ncol = 3)  # replacing matrix NA with 0smat[is.na(mat)] = 0  # printing original matrixprint ("Original Matrix")print (mat)  # calculating transpose of the# matrixtransmat = t(mat)print ("Transpose Matrix")print (transmat)  # calculating product of matricesprod = mat%*%transmatprint ("Product Matrix")print (prod)
Output
[1] "Original Matrix"
    [,1] [,2] [,3]
[1,]   10   0    7
[1] "Transpose Matrix"
    [,1]
[1,]   10
[2,]    0
[3,]    7
[1] "Product Matrix"
    [,1]
[1,]   149
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to Install and Configure Fish Shell in Ubuntu?

05 Oct, 2021
Fish Shell is a unique user-friendly command-line shell for the different operating systems. fish includes some smart features like syntax highlighting, fancy tab completions and autosuggest-as-we-type that just works by default with no configuration required. fish is mostly written in shell script and in C++.
Step 1: Install fish repository in ubuntu
$ sudo apt-add-repository ppa:fish-shell/release-3 
Step 2: Update and upgrade repository
$ sudo apt-get update && sudo apt-get upgrade
Step 3: Install fish shell
$ sudo apt-get install fish
Step 4: Make fish shell as default shell
$ sudo chsh -s /usr/local/bin/fish
To get back to bash, use
$ sudo chsh -s 'which bash'
how-to-install
GBlog
How To
Installation Guide
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes?
Morgan Stanley Interview Preparation - GeeksforGeeks

Beat the competition and land yourself a top job. Register for Job-a-thon now!
TCS Recruitment Process
Infosys Recruitment Process
Wipro Recruitment Process
IBM Recruitment Process
Cognizant Recruitment Process
SAP Labs Interview Preparation
Morgan Stanley Interview Preparation
Accenture Recruitment Process
Swiggy Recruitment Process
Flipkart Interview Preparation
Paytm Interview Preparation
Samsung Interview Preparation
Walmart Labs Recruitment Process
Directi Interview Preparation
Qualcomm Recruitment Process
MakeMyTrip Recruitment Process
Company Preparation
Amazon Interview Preparation
Microsoft Interview Preparation
Google Interview Preparation
D E Shaw Interview Preparation
Goldman Sachs Interview Preparation
Morgan-Stanley Interview Preparation
Popular Articles
Sort an array of 0s, 1s and 2s
Swap Kth node from beginning with Kth node from end in a Linked List
Dynamic Programming | Set 14 (Maximum Sum Increasing Subsequence)
Dynamic Programming | Set 7 (Coin Change)
Largest Sum Contiguous Subarray
Print a given matrix in spiral form
Maximum Product Subarray
Count numbers from 1 to n that have 4 as a a digit
Write your own atoi()
Remove duplicates from sorted array
Largest subarray with equal number of 0s and 1s
Show All Articles
Popular Coding Problems
Kadane's Algorithm
Sort an array of 0s, 1s and 2s
0 - 1 Knapsack Problem
Minimum element in a sorted and rotated array
Maximum sum increasing subsequence
Level order traversal Line by Line
Implement Atoi
Largest subarray of 0's and 1's
Remove duplicate elements from sorted Array
Clone a linked list with next and random pointer
Show All Coding Problems
Popular Video Tutorials
Recent Interview Experiences
Morgan Stanley Interview Experience | Set 32 (On-Campus)
Morgan Stanley Interview Experience | Set 31 (On-Campus)
Morgan Stanley Interview Experience | Set 30 (On-Campus)
Morgan Stanley Interview Experience | Set 29 (On-Campus)
Morgan Stanley Interview Experience | Set 28 (On-Campus)
Largest even number possible by using one swap operation in given number
Morgan Stanley Interview | Set 27 (For 2.5 Years Experienced)
Morgan Stanley Interview | Set 26 (Off-Campus)
Morgan Stanley Interview | Set 25 (Off-Campus)
Morgan Stanley Interview | Set 24 (On-Campus for Internship)
Show All Interview Experiences
Binary Tree Iterator for Inorder Traversal
How to get JSON response in Ajax ?
Different ways to access characters in a given String in C++
How to Install iPython on Linux?
Pure CSS Form Read-Only Inputs
Failure Classification in DBMS
Difference Between VB.NET and C#
How to add emoji in HTML document ?
Git - Difference Between Git Fetch and Git Pull
Bulma Centering Columns Option
HTML | DOM Local Storage clear() Method

26 Jul, 2019
The clear() method removes all the Storage Object items for the current domain.Syntax:
localStorage.clear()
Property Values:No Property Values
Example: Set item, clear and display for the current domain.
<!DOCTYPE html><html>  <head>    <style>        body {            text-align: center;        }                  h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML DOM Storage clear() Method</h2>      <p>      Example to demonstrate the use of storage      clear() method to delete all the local       storage items for this domain.    </p>      <p>      Script to create some local storage items.      Click the button to create the items:    </p>      <button onclick="createItems()">        Create local storage items    </button>      <h2>Display Items</h2>      <p>      Click the button to display all the items:    </p>      <button onclick="displayItems()">      Display items    </button>    <p id="demo"></p>      <h2>Remove Items</h2>      <p>      Click the button to clear the storage:    </p>      <button onclick="deleteItems()">      Clear    </button>      <h2>Display Items Again</h2>      <p>      Click the button to display all the items:    </p>      <button onclick="displayItems()">      Display again    </button>    <p id="demo"></p>      <script>        function createItems() {              // Set item in local storage.            localStorage.setItem("GeeksForGeeks", "");            localStorage.setItem("HTML DOM", "");            localStorage.setItem("Storage Clear() Method", "");        }          function deleteItems() {            // Clear local storage items.            localStorage.clear();        }          function displayItems() {            var l, i;            // Display items.            document.getElementById("demo").innerHTML = "";            for (i = 0; i < localStorage.length; i++) {                x = localStorage.key(i);                document.getElementById("demo").innerHTML += x;            }        }    </script>  </body>  </html>
Output:
Supported Browsers: The browser supported by DOM Local Storage clear() are listed below:
Google Chrome 4.0
Internet Explorer 8.0
Mizilla Firefox 3.5
Opera 10.5
Safari 4.0
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axes.Axes.set_yticklabels() in Python

30 Jun, 2022
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.set_yticklabels() function in axes module of matplotlib library is used to Set the y-tick labels with list of string labels.
Syntax: Axes.set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs) 
Parameters: This method accepts the following parameters.
labels : This parameter is the list of string labels.
fontdict : This parameter is the dictionary controlling the appearance of the ticklabels.
minor : This parameter is used whether set major ticks or to set minor ticks
Return value: This method returns a list of Text instances.
Below examples illustrate the matplotlib.axes.Axes.set_yticklabels() function in matplotlib.axes: 
Example 1: 
Python3
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10))ax.set_yticklabels(("Label-1", "Label-2",                    "Label-3", "Label-4"))   fig.suptitle('matplotlib.axes.Axes.set_yticklabels()\ function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
  
Example 2: 
Python3
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  # Fixing random state for reproducibilitynp.random.seed(19680801)  x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape)  fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2)  ax.set_yticks([-1, 0, 1])  ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) ax.set_yticklabels(("Val-1", "Val-2", "Val-3"))   fig.suptitle('matplotlib.axes.Axes.set_yticklabels()\ function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
 
simmytarika5
Python-matplotlib
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
Program to find the number of days between two dates in PHP

03 Dec, 2021
In this article, we will see how to get the date difference in the number of days in PHP, along with will also understand the various ways to get the total count of difference in 2 dates & see their implementation through the examples. We have given two dates & our task is to find the number of days between these given dates. For this, we will be following the below 2 methods:
Using strtotime() Function
Using date_diff() Function
Consider the following example:
Input : date1 = "2-05-2017"
        date2 = "25-12-2017"
Output: Difference between two dates: 237 Days
Explanation: Calculating the total number of days between the start & end date.
Note: The dates can be taken in any format. In the above example, the date is taken in dd-mm-yyyy format.
Method 1: Using strtotime() Function
This is a built-in function in PHP that is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in the English date-time description. The function returns the time in seconds since the Unix Epoch
Example 1: In this example, we have taken two dates and calculated their differences.
PHP
<?php    // Function to find the difference   // between two dates.  function dateDiffInDays($date1, $date2)   {      // Calculating the difference in timestamps      $diff = strtotime($date2) - strtotime($date1);        // 1 day = 24 hours      // 24 * 60 * 60 = 86400 seconds      return abs(round($diff / 86400));  }    // Start date  $date1 = "17-09-2018";    // End date  $date2 = "31-09-2018";    // Function call to find date difference  $dateDiff = dateDiffInDays($date1, $date2);    // Display the result  printf("Difference between two dates: "     . $dateDiff . " Days ");?>
Difference between two dates: 14 Days
 
Method 2: Using date_diff() Function
The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.
Example: This example describes calculating the number of days between the 2 dates in PHP.
PHP
<?php    // Creates DateTime objects  $datetime1 = date_create('17-09-2018');  $datetime2 = date_create('25-09-2018');    // Calculates the difference between DateTime objects  $interval = date_diff($datetime1, $datetime2);    // Display the result  echo $interval->format('Difference between two dates: %R%a days');?>
Difference between two dates: +8 days
 
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.
nidhi_biet
bhaskargeeksforgeeks
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pretty-Printing in BeautifulSoup

25 Feb, 2021
Prerequisite:
requests
BeautifulSoup
In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response.
pip install requests
Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping.
pip install beautifulsoup4
In simple words we can say, It prettifies the HTML with proper indents and everything.
Let’s Understand Step by step implementation:-
Import Required Module
Python3
# Import Required Moduleimport requestsfrom bs4 import BeautifulSoup
Parse HTML Content
Python3
# Web URLWeb_url = "Enter WEB URL"  # Get URL Contentr = requests.get(Web_url)  # Parse HTML Codesoup = BeautifulSoup(r.content, 'html.parser')
Pretty the HTML Code. BeautifulSoup has a prettify() method.
The prettify() method will turn a Beautiful Soup parse tree into a nicely formatted Unicode string, with a separate line for each tag and each string:
Python3
print(soup.prettify())
Below is the implementation:
Python3
# Import Required Moduleimport requestsfrom bs4 import BeautifulSoup  # Web URLWeb_url = "https://www.geeksforgeeks.org/transparent-window-in-tkinter/"  # Get URL Contentr = requests.get(Web_url)  # Parse HTML Codesoup = BeautifulSoup(r.content, 'html.parser')print(soup.prettify())
Output:
Picked
Python BeautifulSoup
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 | datetime.timedelta() function
Python | Get unique values from a list
Python PIL | tobytes() Method

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.tobytes() Return image as a bytes object
Syntax: Image.tobytes(encoder_name=’raw’, *args)
Parameters:
encoder_name – What encoder to use. The default is to use the standard “raw” encoder.args – Extra arguments to the encoder.
Returns: A bytes object.
Image Used:
     # Importing Image module from PIL packagefrom PIL import Image  # creating a image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")  # using tobytesimg.tobytes("xbm", "rgb")print(img)
Output:
PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x2D39DED2BE0

Another Example: Here using same image with change in encoder name to hex.
Image Used:
     # Importing Image module from PIL packagefrom PIL import Image  # creating a image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")  # using tobytesimg.tobytes("hex", "rgb")print(img)
Output:
PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x27845B91BE0

Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
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 - Pandas dataframe.append()
Python | datetime.timedelta() function
Get the Minimum and Maximum element of a Vector in R Programming - range() Function - GeeksforGeeks

16 Dec, 2021
range() function in R Programming Language is used to get the minimum and maximum values of the vector passed to it as an argument.
Syntax: range(x, na.rm, finite)
Parameters: 
x: Numeric Vector
na.rm: Boolean value to remove NA
finite: Boolean value to exclude non-finite elements
R
# R program to find the# minimum and maximum element of a vector # Creating a vectorx <- c(8, 2, 5, 4, 9, 6, 54, 18) # Calling range() functionrange(x)
Output: 
[1]  2 54
R
# R program to find the# minimum and maximum element of a vector # Creating a vectorx <- c(8, 2, Inf, 5, 4, NA, 9, 54, 18) # Calling range() functionrange(x) # Calling range() function# excluding NA valuesrange(x, na.rm = TRUE) # Calling range() function# excluding finite valuesrange(x, na.rm = TRUE, finite = TRUE)
Output: 
[1] NA NA
[1]   2 Inf
[1]  2 54
kumar_satyam
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
Linear Discriminant Analysis in R Programming
How to filter R DataFrame by values in a column?
How to change Colors in ggplot2 Line Plot in R ?
How to import an Excel File into R ?
C# Program for Count set bits in an integer - GeeksforGeeks

02 Jan, 2019
Write an efficient program to count number of 1s in binary representation of an integer.
Examples :
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits

1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program.
C#
// C# program to Count set// bits in an integerusing System;  class GFG {    // Function to get no of set    // bits in binary representation    // of positive integer n    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            count += n & 1;            n >>= 1;        }        return count;    }      // Driver Code    public static void Main()    {        int i = 9;        Console.Write(countSetBits(i));    }}  // This code is contributed by Sam007
2

Recursive Approach :
C#
// C# implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer nusing System;  class GFG {      // recursive function    // to count set bits    public static int countSetBits(int n)    {          // base case        if (n == 0)            return 0;          else              // if last bit set            // add 1 else add 0            return (n & 1) + countSetBits(n >> 1);    }      // Driver code    static public void Main()    {          // get value        // from user        int n = 9;          // function calling        Console.WriteLine(countSetBits(n));    }}  // This code is contributed by aj_36
2

Please refer complete article on Count set bits in an integer for more details!
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Program to Check a Specified Type is an Enum or Not
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
C# Program to Read and Write a Byte Array to File using FileStream Class
How to Sort Object Array By Specific Property in C#?
C# Program to Delete an Empty and a Non-Empty Directory
C# Program to Print the Current Assembly Name Using GetExecutingAssembly() Method
C# Program to Implement IComparable Interface
C# Program to Check a Specified Type is a Primitive Data Type or Not
C# - Reading Lines From a File Until the End of File is Reached
C# - Copying the Contents From One File to Another File
Convert Python Script to .exe File - GeeksforGeeks

01 Feb, 2021
We create lots of Python programs per day and want to share them with the world. It is not that you share that Python program with everyone, and they will run this script in some IDLE shell. But you want everyone to run your Python script without the installation of Python. So for this work, you can convert the .py file to .exe file. In this article, you will learn how you can convert .py file to .exe file. Follow the below steps for the same. 
Step 1: Install the library pyinstaller. Type below command in the command prompt.  
pip install pyinstaller
Step 2: Go into the directory where your ‘.py’ file is located. 
 
Step 3: Press the shift⇧ button and simultaneously right-click at the same location. You will get the below box.  
Step 4: Click on ‘Open PowerShell window here’. 
 
You will get a window shown below. 
 
Step 5: Type the command given below in that PowerShell window.  
pyinstaller --onefile -w 'filename.py'
Here the ‘.py’ file name is ‘1’. See below: 
 
In case you get an error at this point in the PowerShell window like this: 
 
The correction while typing the above command:  
.\pyinstaller --onefile -w 'filename.py'

For any missing package:
pyinstaller --hidden-import 'package_name' --onefile 'filename.py'
 
Step 6: After typing the command ‘Hit the Enter’. It will take some time to finish the process depending on the size of the file and how big is your project. After the processing has been finished, the window will look as below: 
 
Step 7: See the directory it should look like this: 
 
‘build’ folder and ‘1.spec’ is of no use. You can delete these if you want, it will not affect your ‘.exe’ file. 
 
Step 8: Open ‘dist’ folder above. Here you will get your ‘.exe’ file. 
 
Right-click on the file and check the properties. 
 
 
shanmalan
python-utility
Technical Scripter 2019
Python
Technical Scripter
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
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Tryit Editor v3.6 - Show Python

f = open("demofile.txt", "r")
What is the difference between Getters and Setters in JavaScript?

Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object. Let's discuss them through examples.
In the following example, an object named "business" is created and using "Getter" a property called "company" is displayed in the output.
 Live Demo
<html>
<body>
<script>
   var business= {
      Name: "Musk",
      Country : "America",
      Company : "PayPal",
      get comp() {
         return this.company;
      }
   };
   document.write(business.company);
</script>
</body>
</html>
paypal
In the following example, an object named "business" is created and using "Setter" the value of property called "company" is changed from PayPal to SolarCity as shown in the output.
 Live Demo
<html>
<body>
<script>
   var business = {
      Name: "Musk",
      Country : "America",
      company : "PayPal",
      set comp(val) {
         this.company = val;
      }
   };
   business.comp = "SolarCity";
   document.write(business.company);
</script>
</body>
</html>
SolarCity
Python - Window size Adjustment in Kivy

Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
Kivy is that platform where the size does not matter a lot as it is self-adjusting accordingly but What if we want to fix the size to some extent whether its hight wise or width wise or free from boundation depends on the user requirement.
# When there is no fix window size i.e fully resizable according to user:
from kivy.config import Config
# 0 being off 1 being on as in true / false you can use 0 or 1 && True or False
Config.set('graphics', 'resizable', True)
# import kivy module
import kivy
# this restrict the kivy version i.e below this kivy version you cannot use the app
kivy.require("1.9.1")
# base Class of your App inherits from the App class. app:always refers to the instance of your #application
from kivy.app import App
# if you not import label and use it through error
from kivy.uix.label import Label
# defining the App class
class MyLabelApp(App):
   def build(self):
      # label display the text on screen
      # markup text with different colour
         l2 = Label(text ="[color = ff3333][b]Hello !!!!!!!!!!![/b]
            [/color]\n [color = 3333ff]World!!! !!:):):):)[/color]",
               font_size ='20sp', markup = True)
         return l2
# creating the object
label = MyLabelApp()
# run the window
label.run()
# No resizing, fixed size with the width:
from kivy.config import Config
# 0 being off 1 being on as in true / false
# you can use 0 or 1 && True or False
Config.set('graphics', 'resizable', '0')
# fix the width of the window
Config.set('graphics', 'width', '500')
#fixing the height of the window
from kivy.config import Config
# 0 being off 1 being on as in true / false
# you can use 0 or 1 && True or False
Config.set('graphics', 'resizable', '0')
# fix the height of the window
Config.set('graphics', 'height', '400')