code-rag-bench/online-tutorials huggingface dataset:
Python | time.gmtime() method

03 Jan, 2022
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules.
time.gmtime() method of Time module is used to convert a time expressed in seconds since the epoch to a time.struct_time object in UTC in which tm_isdst attribute is always 0.To convert the given time in seconds since the epoch to a time.struct_time object in local time, time.localtime() method is used.
This method returns a time.struct_time object with a named tuple interface. Following are the values present in time.struct_time object:
Syntax: time.gmtime([secs])
Parameter:secs (optional): An integer or float value representing time in seconds. Fractions of specified seconds will be ignored. If the secs parameter is not provided or None then the current time as returned by time.time() method is used.
Return type: This method returns an object of class ‘time.struct_time’.
Code #1: Use of time.gmtime() method
Python3
# Python program to explain time.gmtime() method  # importing time moduleimport time    # If secs parameter# is not given then# the current time  # as returned by time.time() method# is used  # Convert the current time in seconds# since the epoch to a# time.struct_time object in UTCobj = time.gmtime()  # Print the time.struct.time objectprint(obj)
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=22, tm_hour=3, tm_min=53,
tm_sec=32, tm_wday=3, tm_yday=234, tm_isdst=0)

Code #2: Use of time.gmtime() method
Python3
# Python program to explain time.gmtime() method  # importing time moduleimport time    # Time in seconds# since the epochsecs = 40000  # Convert the given time in seconds# since the epoch to a# time.struct_time object in UTC# using time.gmtime() methodobj = time.gmtime(secs)  # Print the time.struct_time objectprint("time.struct_time object for seconds =", secs)print(obj)    # Time in seconds# since the epochsecs = 40000.7856  # Convert the given time in seconds# since the epoch to a# time.struct_time object in UTC# using time.gmtime() methodobj = time.gmtime(secs)  # Print the time.struct_time objectprint("\ntime.struct_time object for seconds =", secs)print(obj)    # Output for sec = 40000 # and secs = 40000.7856# will be same because# fractions in 40000.7856# i.e .7856 will be ignored
time.struct_time object for seconds = 40000
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=6,
tm_sec=40, tm_wday=3, tm_yday=1, tm_isdst=0)

time.struct_time object for seconds = 40000.7856
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=6,
tm_sec=40, tm_wday=3, tm_yday=1, tm_isdst=0)

Reference: https://docs.python.org/3/library/time.html#time.gmtime
adnanirshad158
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Generating a Requirements.txt File from a Jupyter Notebook | by Adam Shafi | Towards Data Science

Want to jump straight to the best option? Click here.
Creating a requirements.txt file is a necessary process, particularly when sharing your code, developing MLOps or just pushing something up into a Docker container.
It is surprisingly tricky to get a clean requirements.txt file from a Jupyter Notebook, so I’ve investigated the different ways to do it...
This is the most common way I’ve seen on Stack Overflow is to use pip freeze. This will list every package and version in your current virtual environment.
Simply open a terminal and navigate to the folder you want your requirements file to be in.
You can then activate a virtual environment using venv or conda.
conda activate myenvpip freeze > requirements.txt
The problem with this method
It will take every package you have installed on that environment. If you want to create something lightweight, using only your imports then you’ll need to manually prune this file.
If you want to only use packages in your currently jupyter notebook, you can use the python package session-info.
Install using:
pip install session-info
In your jupyter notebook, after you have imported packages, you can then write:
import session_infosession_info.show()
You’ll get something that looks like this:
You can then copy and paste and replace the spaces with == using find and replace.
The problem with this method
It doesn’t take into account the dependencies from our .py file, custom_functions. However, these will appear lower down with all the other dependencies.
The big problem is that it takes the name of the imports and not the packages. For example, the command for sklearn is actuallypip install scikit-learn which means that this won’t work as a requirements.txt file.
If you only want the requirements.txt file to relate to a single notebook and not your whole environment, this is the best way to do it.
Start by opening a terminal and installing pipreqs and nbconvert.
pip install pipreqspip install nbconvert
Then, navigate to the folder where your Jupyter notebook is located.
If we assume the notebook is called “my nb”. You’ll need to escape the space with a backslash (\).
jupyter nbconvert --output-dir="./reqs" --to script my\ nb.ipynbcd reqspipreqs
If this worked, you should receive a success message.
So what we’ve done here is converted our notebook into a .py file in a new directory called reqs, then run pipreqs in the new directory. The reason for this is that pipreqs only works on .py files and I can’t seem to get it to work when there are other files in the folder. The requirements.txt will be generated in the same folder.
You’ll end up with a perfect requirements file which you can use for anything else!
Ruby Basic Syntax - GeeksforGeeks

06 Sep, 2019
Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990’s in Japan. To program in Ruby is easy to learn because of its similar syntax to already widely used languages. Here, we will learn the basic syntax of Ruby language.Let us write a simple program to print “Hello World!”.
# this line will print "Hello World!" as output.puts "Hello World!";
Output:
Hello World!
Ruby interprets newline characters(\n) and semicolons(;) as the end of a statement.Note: If a line has +, – or backslash at the end of a line, then it indicates the continuation of a statement.
Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in a string, i.e. it ignores all spaces in a statement But sometimes, whitespaces are used to interpret ambiguous statements.Example :
a / b interprets as a/b (Here a is a variable)a b interprets as a(b)(Here a is a method)
# declaring a function named 'a' which accepts an# integer and return 1def a(u) return 1 end   # driver codea = 3 b = 2   # this a + b interprets as a + b, so prints 5 as outputputs(a + b)  # this a b interprets as a(b) thus the returned# value is printedputs(a b)
Output:
5
1

BEGIN statement is used to declare a part of code which must be called before the program runs.
Syntax:
BEGIN
{
    # code written here
}

Similarly, END is used to declare a part of code which must be called at the end of program.Syntax:
END
{
    # code written here
}

Example of BEGIN and END
# Ruby program of BEGIN and ENDputs "This is main body of program"   END {   puts "END of the program"}BEGIN {   puts "BEGINNING of the Program"}
Output:
BEGINNING of the Program
This is main body of program

A comment hides some part of code, from the Ruby Interpreter. Comments can be written in different ways, using hash character(#) at the beginning of a line.Syntax :
#This is a single line comment
#This is multiple
#lines of comment
=begin
This is another
way of writing 
comments in a 
block fashion
=end
Identifiers are names of variables, constants and functions/methods.
Ruby identifiers are case sensitive.
Ruby identifiers may consists of alphanumeric characters and also underscore ( _ ).
For example: Man_1, item_01 are examples of identifiers.
The reserved words in Ruby which cannot be used as constant or variable names are called keywords of Ruby.
Akanksha_Rai
Picked
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Ruby | Numeric round() function
C++ Program to Implement Variable Length Array

Variable length arrays can have a size as required by the user i.e they can have a variable size.
A program to implement variable length arrays in C++ is given as follows −
 Live Demo
#include <iostream>
#include <string>

using namespace std;
int main() {
   int *array, size;
   cout<<"Enter size of array: "<<endl;
   cin>>size;
   array = new int [size];
   cout<<"Enter array elements: "<<endl;

   for (int i = 0; i < size; i++)
   cin>>array[i];
   cout<<"The array elements are: ";

   for(int i = 0; i < size; i++)
   cout<<array[i]<<" ";
   cout<<endl;
   delete []array;
   return 0;
}
The output of the above program is as follows −
Enter size of array: 10
Enter array elements: 11 54 7 87 90 2 56 12 36 80
The array elements are: 11 54 7 87 90 2 56 12 36 80
In the above program, first the array is initialized. Then the array size and array elements are requested from the user. This is given below −
cout<<"Enter size of array: "<<endl;
cin>>size;

array = new int [size];

cout<<"Enter array elements: "<<endl;

for (int i = 0; i < size; i++)
cin>>array[i];
Finally, the array elements are displayed and the array is deleted. This is given below −
cout<<"The array elements are: ";
for(int i = 0; i < size; i++)
cout<<array[i]<<" ";
cout<<endl;
delete []array;
Docker - Networking

Docker takes care of the networking aspects so that the containers can communicate with other containers and also with the Docker Host. If you do an ifconfig on the Docker Host, you will see the Docker Ethernet adapter. This adapter is created when Docker is installed on the Docker Host.
This is a bridge between the Docker Host and the Linux Host. Now let’s look at some commands associated with networking in Docker.
This command can be used to list all the networks associated with Docker on the host.
docker network ls 

None
The command will output all the networks on the Docker Host.
sudo docker network ls
The output of the above command is shown below
If you want to see more details on the network associated with Docker, you can use the Docker network inspect command.
docker network inspect networkname 

networkname − This is the name of the network you need to inspect.
networkname − This is the name of the network you need to inspect.
The command will output all the details about the network.
sudo docker network inspect bridge 
The output of the above command is shown below −
Now let’s run a container and see what happens when we inspect the network again. Let’s spin up an Ubuntu container with the following command −
sudo docker run –it ubuntu:latest /bin/bash 

Now if we inspect our network name via the following command, you will now see that the container is attached to the bridge.
sudo docker network inspect bridge

One can create a network in Docker before launching containers. This can be done with the following command −
docker network create –-driver drivername name 

drivername − This is the name used for the network driver.
drivername − This is the name used for the network driver.
name − This is the name given to the network.
name − This is the name given to the network.
The command will output the long ID for the new network.
sudo docker network create –-driver bridge new_nw 
The output of the above command is shown below −
You can now attach the new network when launching the container. So let’s spin up an Ubuntu container with the following command −
sudo docker run –it –network=new_nw ubuntu:latest /bin/bash

And now when you inspect the network via the following command, you will see the container attached to the network.
sudo docker network inspect new_nw 


    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
How to get a number of vowels in a string in JavaScript? - GeeksforGeeks

18 Jan, 2021
The Approach of this article is to return the number of vowels in a string using Javascript. A vowel is also a letter that represents a sound produced in this way: The vowels in English are a, e, i, o, u.  
Example:
Input:GeeksForGeeks
Output:  5  

Input: Hello Geeks
Output:    4
Explanation: Here we create a user-defined function called “getvowels()” which reads a string and compare with list of vowels. It compares each character of a string with vowels. When the vowels is matches it will increment the value of the vowelsCount.
Example: Below code will illustrate the approach.
HTML
<html>    <head>        <title>            How to get a number of vowels            in a string in JavaScript?        </title>    </head>   <body>       <h1>           GeeksforGeeks       </h1>       <h2>           How to get a number of vowels in            a string in JavaScript?       </h2><script>   function getVowels(string) {      var Vowels = 'aAeEiIoOuU';      var vowelsCount = 0;      for(var i = 0; i < string.length ; i++) {         if (Vowels.indexOf(string[i]) !== -1) {            vowelsCount += 1;        }      }   return vowelsCount;   }   document.write("The Number of vowels in -"+   " A Computer Science Portal for Geeks:"    + getVowels("A Computer Science Portal for Geeks"));</script></body></html>
Output:
javascript-basics
javascript-string
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Python 3 - os.mkdir() Method

The method mkdir() create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
Following is the syntax for mkdir() method −
os.mkdir(path[, mode])

path − This is the path, which needs to be created.
path − This is the path, which needs to be created.
mode − This is the mode of the directories to be given.
mode − This is the mode of the directories to be given.
This method does not return any value.
The following example shows the usage of mkdir() method.
#!/usr/bin/python3
import os, sys

# Path to be created
path = "/tmp/home/monthly/daily/hourly"
os.mkdir( path, 0755 )

print ("Path is created")
When we run the above program, it produces the following result −
Path is created


    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
Jackson Annotations - @JsonTypeInfo

@JsonTypeInfo is used to indicate details of type information which is to be included in serialization and de-serialization.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException {
      Shape shape = new JacksonTester.Circle("CustomCircle", 1);
      String result = new ObjectMapper()
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(shape);
      System.out.println(result);   
      String json = "{\"name\":\"CustomCircle\",\"radius\":1.0, \"type\":\"circle\"}";
      Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json);
      System.out.println(circle.name);
   }
   @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type") @JsonSubTypes({
      
      @JsonSubTypes.Type(value = Square.class, name = "square"),
      @JsonSubTypes.Type(value = Circle.class, name = "circle")
   })
   static class Shape {
      public String name;    
      Shape(String name){
         this.name = name;
      }
   }
   @JsonTypeName("square")
   static class Square extends Shape {
      public double length;
      Square(){
         this(null,0.0);
      }
      Square(String name, double length){
         super(name);
         this.length = length;
      }
   }
   @JsonTypeName("circle")
   static class Circle extends Shape {
      public double radius;  
      Circle(){
         this(null,0.0);
      }
      Circle(String name, double radius) {
         super(name);
         this.radius = radius;
      }
   }
}
{
   "type" : "circle",
   "name" : "CustomCircle",
   "radius" : 1.0
}
CustomCircle

 Print
 Add Notes
 Bookmark this page
remainder() in C++

20 Aug, 2021
This function is also used to return the remainder(modulus) of 2 floating point numbers mentioned in its arguments.The quotient computed is rounded.remainder = number – rquot * denom Where rquot is the result of: number/denom, rounded toward the nearest integral value (with halfway cases rounded toward the even number). 
Syntax :  
double remainder(double a, double b)
float remainder(float a, float b)
long double remainder(long double a, long double b)
Parameter:
a and b are the values 
of numerator and denominator.


Return:
The remainder() function returns the floating 
point remainder of numerator/denominator 
rounded to nearest.
Error or Exception : It is mandatory to give both the arguments otherwise it will give error – no matching function for call to ‘remainder()’ like this.# CODE 1
CPP
// CPP program to demonstrate// remainder() function#include <cmath>#include <iostream> using namespace std; int main(){    double a, b;    double answer;     a = 50.35;    b = -4.1;     // here quotient is -12.2805 and rounded to nearest value then    // rquot = -12.    // remainder = 50.35 – (-12 * -4.1)    answer = remainder(a, b);     cout << "Remainder of " << a << "/" << b << " is " << answer << endl;     a = 16.80;    b = 3.5;     // here quotient is 4.8 and rounded to nearest value then    // rquot = -5.    // remainder = 16.80 – (5 * 3.5)    answer = remainder(a, b);     cout << "Remainder of " << a << "/" << b << " is " << answer << endl;     a = 16.80;    b = 0;    answer = remainder(a, b);    cout << "Remainder of " << a << "/" << b << " is " << answer << endl;     return 0;}
OUTPUT : 
Remainder of 50.35/-4.1 is 1.15
Remainder of 16.8/3.5 is -0.7
Remainder of 16.8/0 is -nan
# CODE 2  
CPP
// CPP program to demonstrate// remainder() function#include <cmath>#include <iostream> using namespace std; int main(){    int a = 50;    double b = 41.35, answer;     answer = remainder(a, b);    cout << "Remainder of " << a << "/" << b << " = " << answer << endl;     return 0;}
OUTPUT : 
Remainder of 50/41.35 = 8.65 
abhishek0719kadiyan
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extended Integral Types (Choosing the correct integer size in C/C++)

28 Dec, 2021
C/C++ has very loose definitions on its basic integer data types (char, short, int, long, and long long). The language guarantees that they can represent at least some range of values, but any particular platform (compiler, operating system, hardware) might be larger than that.A good example is long. On one machine, it might be 32 bits (the minimum required by C). On another, it’s 64 bits. What do you do if you want an integer type that’s precisely 32 bits long? That’s where int32_t comes in: it’s an alias for whatever integer type your particular system has that is exactly 32 bits.Template:  
intN_t or uintN_t
Where N is width of integer which can be 8, 16, 32, 64
or any other type width supported by the library.
 
CPP
// C++ program to show use of extended integral types#include <iostream>using namespace std; int main(){    uint8_t i;      // i with width of exact 8 bits     // Minimum value represented by unsigned 8 bit is 0    i = 0;    cout << "Minimum value of  i\t: "<< (int)i << endl;     // Maximum value represented by unsigned 8 bit is 255    i = 255;    cout << "Maximum value of i\t: "<< (int)i << endl;     // Warning: large integer implicitly truncated to    // unsigned type. It will print any garbage value    i = 2436;    cout << "Beyond range value of i\t: " << (int)i << endl;     return 0;}
Output:  
 In function 'int main()':
19:7: warning: large integer implicitly truncated to unsigned type [-overflow]
     i = 2436;
       ^

Minimum value of  i    : 0
Maximum value of i    : 255
Beyond range value of i    : 132
Different Variations 1. Fixed width unsigned 8 bit integer: uint8_t It means give me an unsigned int of exactly 8 bits.2. Minimum width unsigned 8 bit integer: uint_least8_t It means give me the smallest type of unsigned int which has at least 8 bits. Optimized for memory consumption.3. Fastest minimum width unsigned 8 bit integer: uint_fast8_t It means give me an unsigned int of at least 8 bits which will make my program faster. It may pick larger data type because of alignment considerations. Optimized for speed.Thus a uint8_t is guaranteed to be exactly 8 bits wide. A uint_least8_t is the smallest integer guaranteed to be at least 8 bits wide. An uint_fast8_t is the fastest integer guaranteed to be at least 8 bits wide. So the extended integral types help us in writing portable and efficient code.This article is contributed by Rohit Kasle. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
rkbhola5
cpp-data-types
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2015 | Question 12

03 Apr, 2018
A machine needs a minimum of 100 sec to sort 1000 names by quick sort. The minimum time needed to sort 100 names will be approximately(A) 50.2 sec(B) 6.7 sec(C) 72.7 sec(D) 11.2 secAnswer: (B)Explanation: Best case time complexity of quick sort to take the minimum time to sort names = O(n log n)
let t1 = time taken to sort 1000 names = 100 sec;
n1=1000 names
let t2 = time taken to sort 100 names;
n2= 100 names

t1/t2 = n1*log(n1) / n2*log(n2) 
100/t2 = 1000*log(1000) / 100*log(100)
100/t2 = 10*log(1000) / log(100)
100/t2 = 10*3 / 2
t2 = 20/3 = 6.66 
Option (B) is correctQuiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Find Mixed Combinations of string and list

26 Nov, 2019
Sometimes, while working with Python, we can have a problem in which we need to make combinations of string and character list. This type of problem can come in domains in which we need to interleave the data. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + enumerate() + replace()This task can be performed using combination of above functions. In this, we just iterate each element of character list and insert each combination using brute force way.
# Python3 code to demonstrate working of# Mixed Combinations of string and list# using loop + enumerate() + replace()  # initialize list and string test_list = ["a", "b", "c"]test_str = "gfg"  # printing original list and stringprint("The original list : " + str(test_list))print("The original string : " + test_str)  # Mixed Combinations of string and list# using loop + enumerate() + replace()res = []for idx, ele in enumerate(test_str):    res += [test_str[ : idx] + test_str[idx : ].replace(ele, k, 1)            for k in test_list]  # printing resultprint("The list after mixed Combinations : " + str(res))
The original list : [‘a’, ‘b’, ‘c’]The original string : gfgThe list after mixed Combinations : [‘afg’, ‘bfg’, ‘cfg’, ‘gag’, ‘gbg’, ‘gcg’, ‘gfa’, ‘gfb’, ‘gfc’]
 
Method #2 : Using list comprehensionThe above functionality can be used to perform this task. In this, we provide a one-line alternative using comprehension.
# Python3 code to demonstrate working of# Mixed Combinations of string and list# using list comprehension  # initialize list and string test_list = ["a", "b", "c"]test_str = "gfg"  # printing original list and stringprint("The original list : " + str(test_list))print("The original string : " + test_str)  # Mixed Combinations of string and list# using list comprehensionres = [test_str[ : idx] + ele + test_str[idx + 1 : ]\      for idx in range(len(test_str)) for ele in test_list]  # printing resultprint("The list after mixed Combinations : " + str(res))
The original list : [‘a’, ‘b’, ‘c’]The original string : gfgThe list after mixed Combinations : [‘afg’, ‘bfg’, ‘cfg’, ‘gag’, ‘gbg’, ‘gcg’, ‘gfa’, ‘gfb’, ‘gfc’]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.cla() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The cla() function in pyplot module of matplotlib library is used to clear the current axes.Syntax:
matplotlib.pyplot.cla()

Below examples illustrate the matplotlib.pyplot.cla() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib function   import matplotlib.pyplot as plt      plt.plot([1, 2, 3, 4], [16, 4, 1, 8])  plt.cla()plt.title('matplotlib.pyplot.cla Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt      t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t)   fig, [ax, ax1] = plt.subplots(2, 1)   ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)  ax1.set_ylabel('y-axis')ax1.set_xlabel('x-axis')ax1.plot(t, s)ax1.grid(True)ax1.cla()  fig.suptitle('matplotlib.pyplot.cla Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Find out the Area and Perimeter of Rectangle using Class Concept

17 Dec, 2020
The perimeter is the length of the outline of a shape. To find the perimeter of a rectangle or square you have to add the lengths of all four sides. x is in this case the length of the rectangle while y is the width of the rectangle. The area is the measurement of the surface of a shape.
The main task here is to create a class that can be used to find the Area and Perimeter of a rectangle. 
By using the formula for Area of Rectangle and Perimeter of Rectangle:
Area of Rectangle = Length * Breadth
Perimeter of Rectangle = 2 * (Length + Breadth)
Example:
Length = 10
Breadth = 20
Area of rectangle is = 200
Perimeter of rectangle is = 60
Approach :
First, we will create a class called Rectangle in which we will define the variable length and breadth. And the method Area and Perimeter to calculate the Area and Perimeter of Rectangle.
Then we will create another class in which we will create a main method.
Inside the main method, the object of the rectangle is created using which we can call assign the values to the variable of Rectangle class, and after assigning the values the methods of the Rectangle class will be called to calculate the Area and Perimeter of Rectangle.
Both the methods of the Rectangle class will use the values of length and breadth that we had passed from the main method using the object of that class. And the result will get printed.
Example:
Java
// Java program to create a class to// print the area and perimeter of a// rectangle  import java.util.*;  // Rectangle Class Filepublic class Rectangle {      // Variable of data type double    double length;    double width;      // Area Method to calculate the area of Rectangle    void Area()    {        double area;        area = this.length * this.width;        System.out.println("Area of rectangle is : "                           + area);    }      // Perimeter Method to calculate the Perimeter of    // Rectangle    void Perimeter()    {        double perimeter;        perimeter = 2 * (this.length + this.width);        System.out.println("Perimeter of rectangle is : "                           + perimeter);    }}   class Use_Rectangle {         public static void main(String args[])    {        // Object of Rectangle class is created        Rectangle rect = new Rectangle();          // Assigning the value in the length variable of        // Rectangle Class        rect.length = 15.854;          // Assigning the value in the width variable of        // Rectangle Class        rect.width = 22.65;          System.out.println("Length = " + rect.length);        System.out.println("Width = " + rect.width);          // Calling of Area method of Rectangle Class        rect.Area();          // Calling of Perimeter method of Rectangle Class        rect.Perimeter();    }}
Length = 15.854
Width = 22.65
Area of rectangle is : 359.09309999999994
Perimeter of rectangle is : 77.008
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | String translate() - GeeksforGeeks

24 Jul, 2020
translate() returns a string that is modified string of givens string according to given translation mappings.
There are two ways to translate :
Parameters :
string.translate(mapping)
mapping – a dictionary having mapping between two characters.Returns : Returns modified string where each character is mapped to its corresponding character according to the provided mapping table.
# Python3 code to demonstrate # translations without # maketrans()   # specifying the mapping # using ASCII table = { 119 : 103, 121 : 102, 117 : None }   # target string trg = "weeksyourweeks"  # Printing original string print ("The string before translating is : ", end ="") print (trg)   # using translate() to make translations. print ("The string after translating is : ", end ="") print (trg.translate(table)) 
The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks

One more example:
# Python 3 Program to show working# of translate() method  # specifying the mapping  # using ASCII  translation = {103: None, 101: None, 101: None}  string = "geeks"print("Original string:", string)  # translate stringprint("Translated string:",        string.translate(translation))
Original string: geeks
Translated string: ks

Syntax : maketrans(str1, str2, str3)Parameters :str1 : Specifies the list of characters that need to be replaced.str2 : Specifies the list of characters with which the characters need to be replaced.str3 : Specifies the list of characters that needs to be deleted.
Returns : Returns the translation table which specifies the conversions that can be used by translate()
# Python 3 Program to show working# of translate() method  # First StringfirstString = "gef"  # Second StringsecondString = "eks"  # Third StringthirdString = "ge"  # Original Stringstring = "geeks"print("Original string:", string)  translation = string.maketrans(firstString,                                secondString,                                thirdString)  # Translated Stringprint("Translated string:",        string.translate(translation))
Original string: geeks
Translated string: ks

Output :
Original string: geeks
Translated string: ks
nidhi_biet
python-string
Python-string-functions
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
How to convert an image to base64 encoding in PHP? - GeeksforGeeks

31 Jul, 2021
The base64_encode() function is an inbuilt function in PHP which is used to convert any data to base64 encoding. In order to convert an image into base64 encoding firstly need to get the contents of file. This can be done with the help of file_get_contents() function of PHP. Then pass this raw data to base64_encode() function to encode.
Required Function:
base64_encode() Function The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data.
file_get_contents() Function The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.
Input Image:
Program:
<?php   // Get the image and convert into string$img = file_get_contents('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-22.png');  // Encode the image string data into base64$data = base64_encode($img);  // Display the outputecho $data;?>
Output:
iVBORw0KGgoAAAANSUhEUgAAApsAAAC4CAYAAACsNSfVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAAZdEVYdFNvZnR3YXJdhfdsglgklAEFkb2JlIEltYWdlUmVhZHlxyWqwrwtwefd...TeUsalQKBQKhUKhsBvK2FQoFAqFQqFQ2A1lbCoUCoVCoVAo7IYyNhUKhUKhUCgUdkMZmwqFQKBQKO0H0fxpZ1bfc

Reference:
http://php.net/manual/en/function.base64-encode.php
http://php.net/manual/en/function.file-get-contents.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.
Picked
Technical Scripter 2018
PHP
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Construct a linked list from 2D matrix in C++

Suppose we have one matrix, we have to convert it to 2d linked list using recursive approach.
The list will have the right and down pointer.
So, if the input is like
then the output will be
To solve this, we will follow these steps −
Define a function make_2d_list(), this will take matrix mat, i, j, m, n,
Define a function make_2d_list(), this will take matrix mat, i, j, m, n,
if i and j are not in the matrix boundary, then −return null
if i and j are not in the matrix boundary, then −
return null
return null
temp := create a new node with value mat[i, j]
temp := create a new node with value mat[i, j]
right of temp := make_2d_list(mat, i, j + 1, m, n)
right of temp := make_2d_list(mat, i, j + 1, m, n)
down of temp := make_2d_list(mat, i + 1, j, m, n)
down of temp := make_2d_list(mat, i + 1, j, m, n)
return temp
return temp
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode {
   public:
   int data;
   TreeNode *right, *down;
   TreeNode(int d){
      data = d;
      right = down = NULL;
   }
};
void show_2d_list(TreeNode* head) {
   TreeNode *right_ptr, *down_ptr = head;
   while (down_ptr) {
      right_ptr = down_ptr;
      while (right_ptr) {
         cout << right_ptr->data << " ";
         right_ptr = right_ptr->right;
      }
      cout << endl;
      down_ptr = down_ptr->down;
   }
}
TreeNode* make_2d_list(int mat[][3], int i, int j, int m, int n) {
   if (i > n - 1 || j > m - 1)
      return NULL;
   TreeNode* temp = new TreeNode(mat[i][j]);
   temp->right = make_2d_list(mat, i, j + 1, m, n);
   temp->down = make_2d_list(mat, i + 1, j, m, n);
   return temp;
}
int main() {
   int m = 3, n = 3;
   int mat[][3] = {
      { 10, 20, 30 },
      { 40, 50, 60 },
      { 70, 80, 90 } };
   TreeNode* head = make_2d_list(mat, 0, 0, m, n);
   show_2d_list(head);
}
{ { 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 } }
10 20 30
40 50 60
70 80 90
Accessing an array returned by a function in JavaScript

Following is the code for accessing an array returned by a function in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Accessing an array returned by a function in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to return an array from retTable() function and access it</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function retTable(num) {
      let tempNum = [];
      for (i = 1; i <= 10; i++) {
         tempNum.push(i * num);
      }
      return tempNum;
   }
   BtnEle.addEventListener("click", () => {
      let tableArr = retTable(5);
      resEle.innerHTML = "tableArr = " + tableArr;
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
Electron - Inter Process Communication

Electron provides us with 2 IPC (Inter Process Communication) modules called ipcMain and ipcRenderer.
The ipcMain module is used to communicate asynchronously from the main process to renderer processes. When used in the main process, the module handles asynchronous and synchronous messages sent from a renderer process (web page). The messages sent from a renderer will be emitted to this module.
The ipcRenderer module is used to communicate asynchronously from a renderer process to the main process. It provides a few methods so you can send synchronous and asynchronous messages from the renderer process (web page) to the main process. You can also receive replies from the main process.
We will create a main process and a renderer process that will send each other messages using the above modules.
Create a new file called main_process.js with the following contents −
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
const {ipcMain} = require('electron')

let win

function createWindow() {
   win = new BrowserWindow({width: 800, height: 600})
   win.loadURL(url.format ({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true
   }))
}

// Event handler for asynchronous incoming messages
ipcMain.on('asynchronous-message', (event, arg) => {
   console.log(arg)

   // Event emitter for sending asynchronous messages
   event.sender.send('asynchronous-reply', 'async pong')
})

// Event handler for synchronous incoming messages
ipcMain.on('synchronous-message', (event, arg) => {
   console.log(arg) 

   // Synchronous event emmision
   event.returnValue = 'sync pong'
})

app.on('ready', createWindow)
Now create a new index.html file and add the following code in it.
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8">
      <title>Hello World!</title>
   </head>
   
   <body>
      <script>
         const {ipcRenderer} = require('electron')

         // Synchronous message emmiter and handler
         console.log(ipcRenderer.sendSync('synchronous-message', 'sync ping')) 

         // Async message handler
         ipcRenderer.on('asynchronous-reply', (event, arg) => {
            console.log(arg)
         })

         // Async message sender
         ipcRenderer.send('asynchronous-message', 'async ping')
      </script>
   </body>
</html>
Run the app using the following command −
$ electron ./main_process.js

The above command will generate the following output −
// On your app console
Sync Pong
Async Pong

// On your terminal where you ran the app
Sync Ping
Async Ping

It is recommended not to perform computation of heavy/ blocking tasks on the renderer process. Always use IPC to delegate these tasks to the main process. This helps in maintaining the pace of your application.

    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    9 Lectures 
     41 mins

 Ashraf Said

    8 Lectures 
     32 mins

 Ashraf Said

    25 Lectures 
     1 hours 

 Ashraf Said

    17 Lectures 
     1 hours 

 Ashraf Said

    8 Lectures 
     25 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Check whether the given string is a valid identifier in Python

Suppose we have a string representing an identifier. We have to check whether it is valid or not. There are few criteria based on which we can determine whether it is valid or not.
It must start with underscore '_' or any uppercase or lowercase letters
It does not contain any whitespace
All the subsequent characters after the first one must not consist of any special characters like $, #, % etc.
If all of these three are valid then only the string is valid identifier.
So, if the input is like id = "_hello_56", then the output will be True.
To solve this, we will follow these steps −
if first character in s is not alphabetic and not underscore, thenreturn False
return False
for each character ch in s[from index 1 to end], doif ch is not alphanumeric and ch is not underscore, thenreturn False
if ch is not alphanumeric and ch is not underscore, thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
Live Demo
def solve(s):
   if not s[0].isalpha() and s[0] != '_':
      return False

   for ch in s[1:]:
      if not ch.isalnum() and ch != '_':
         return False

   return True

id = "_hello_56"
print(solve(id))
"_hello_56"
True
Python program to find the smallest number in a list

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given al list, we need to display the smallest number available in the list
Here we can either sort the list and get the smallest element or use the built-in min() function to get the smallest element.
Now let’s observe the concept in the implementation below −
 Live Demo
list1 = [101, 120, 104, 145, 99]
# sorting using built-in function
list1.sort()
print("Smallest element is:", list1[0])
Smallest element is: 99
All the variables are declared in the local scope and their references are seen in the figure above.
 Live Demo
list1 = [101, 120, 104, 145, 99]
#using built-in min fucntion
print("Smallest element is:", min(list1))
Smallest element is: 99
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can find the smallest number in a list.
Docker - Configuring

In this chapter, we will look at the different options to configure Docker.
This command is used to stop the Docker daemon process.
service docker stop 

None
A message showing that the Docker process has stopped.
sudo service docker stop 
When we run the above command, it will produce the following result −
This command is used to start the Docker daemon process.
service docker start 

None
A message showing that the Docker process has started.
sudo service docker start
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
Division Operators in Python?

Generally, the data type of an expression depends on the types of the arguments. This rule is applied to most of the operators: like when we add two integers ,the result should be an integer. However, in case of division this doesn’t work out well because there are two different expectations. Sometimes we expect division to generate create precise floating point number and other times we want a rounded-down integer result.
In general, the python definition of division(/) depended solely on the arguments. For example in python 2.7, dividing 20/7 was 2 because both arguments where integers. However, 20./7 will generate 2.857142857142857 as output because the arguments were floating point numbers.
Above definition of ‘/’ often caused problems for applications where data types were used that the author hadn’t expected.
Consider a simple program of converting temperature from Celsius to Fahrenheit conversion will produce two different results depending on the input. If one user provide integer argument(18) and another floating point argument(18.0), then answers were totally different, even though all of the inputs had the equal numeric values.
#Conversion of celcius to Fahrendheit in python 2.6
>>> print 18*9/5 + 32
64
>>> print 18.0*9/5 + 32
64.4
>>> 18 == 18.0
True
From above we can see, when we pass the 18.0, we get the correct output and when we pass 18, we are getting incorrect output. This behaviour is because in python 2.x, the “/” operator works as a floor division in case all the arguments are integers. However, if one of the argument is float value the “/” operator returns a float value.
An explicit conversion function(like float(x)) can help prevent this. The idea however, is for python be simple and sparse language, without a dense clutter of conversions to cover the rare case of an unexpected data type. Starting with Python 2.2 version, a new division operator was added to clarify what was expectred. The ordinary / operator will, in the future, return floating-point results. A special division operator, //, will return rounded-down results.
>>> # Python 2.7 program to demonstrate the use of "//" for both integers and floating point number
>>> print 9//2
4
>>> print -9//2
-5
>>> print 9.0//2
4.0
>>> print -9.0//2
-5.0
In python 3.x, above mentioned flaws were removed and the ‘/’ operator does floating point division for both integer and floating point arguments.
>>> #Conversion of celcius to Fahrendheit in python 3.x
>>> #Passing 18 (integer)
>>> print (18*9/5 + 32)
64.4
>>> #Passing 18.0(float)
>>> print(18.0*9/5 + 32)
64.4
Also there is no difference when we pass +ve or –ve arguments.
>>> print(9/2)
4.5
>>> print(-9/2)
-4.5
>>> print(9.0/2)
4.5
>>> print(-9.0/2)
-4.5