code-rag-bench/online-tutorials huggingface dataset:
JavaScript | Focus() - GeeksforGeeks

01 Apr, 2022
JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers.Syntax:
HTMLElementObject.focus()
Parameters: It does not accept any parameters.Return Value: This method does not return any value.
<html>  <head>    <script type="text/javascript">        function myFunction() {            document.getElementById("focus").focus();        }    </script></head>  <body>    <form action="#">        <br>        <br>        <label>            Hover me: </label>        <input type="text" onmousemove=myFunction() id="focus">                <!-- onmousemove is an event which occurs when somenone         hovers the mouse on that particular element and calls         the function of javascript -->        <br>        <br>        <label>Without Focus: </label>        <input type="text">        <br>        <br>        <input type="button" value="submit">    </form></body></html>
Output:Focus field can be removed with the help of blur() method in javascript.Syntax:
HTMLElementObject.blur()
Parameters: This method does not accept any parameter.Illustration of blur method on clicking a field:Code:
<html>  <head>    <script type="text/javascript">        function setFocus() {            document.getElementById("focus").focus();        }          function removeFocus() {            document.getElementById("focus").blur();        }    </script></head>  <body>    <input type="button" onclick="setFocus()" value="set focus">    <input type="button" onclick="removeFocus()" value="remove focus">    <br>    <br>    <input type="text" id="focus"></body>  </html>
Output:After clicking on set focus-After clicking on remove focus-
javascript-functions
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
How do you run JavaScript script through the Terminal?
Python | Append at front and remove from rear - GeeksforGeeks

31 Dec, 2020
Being familiar with the concept of queue, which follows FIFO rule, i.e first in first out, that suggests a front removal and rear insertion. This has been discussed many times. But sometimes we need to perform the exact opposite of this and we need to perform the append at front and remove element from the rear. Let’s discuss certain ways in which this can be done.
Method #1 : Using + operator and list slicingThese operators can be used to perform this particular task. The append operation can be done with the help of + operator and the removal of rear can be done using the conventional list slicing.
# Python3 code to demonstrate# append from front and remove from rear# using + operator and list slicing  # initializing listtest_list = [4, 5, 7, 3, 10]  # printing original list print("The original list : " + str(test_list))  # using + operator and list slicing# append from front and remove from rearres = [13] + test_list[:-1]  # printing resultprint("The list after append and removal : " + str(res))
The original list : [4, 5, 7, 3, 10]
The list after append and removal : [13, 4, 5, 7, 3]

 
Method #2 : Using collections.deque()The doubly ended queue can be used to perform this particular task in which is supported by python using the collection library, the appendleft and pop methods of queue function can be used to perform this job.
# Python3 code to demonstrate# append from front and remove from rear# using collections.dequefrom collections import deque  # initializing listtest_list = [4, 5, 7, 3, 10]  # printing original list print("The original list : " + str(test_list))  # using collections.deque# append from front and remove from rearres = deque(test_list)res.appendleft(13)res.pop()res = list(res)  # printing resultprint("The list after append and removal : " + str(res))
The original list : [4, 5, 7, 3, 10]
The list after append and removal : [13, 4, 5, 7, 3]

Python DSA-exercises
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python - First K consecutive digits in String - GeeksforGeeks

01 Aug, 2020
Given a String and number K, extract first K consecutive digits making number.
Input : test_str = “geeks5geeks43best”, K = 2Output : 43Explanation : 43 is first 2 consecutive digits.
Input : test_str = “geeks5gee2ks439best”, K = 3Output : 439Explanation : 439 is first 3 consecutive digits.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we run a loop through the list and check if valid N consecutive elements are present for current digit, if yes, we return those N elements.
Python3
# Python3 code to demonstrate working of # First K consecutive digits in String# Using loop  # initializing stringtest_str = "geeks5geeks43isbest"  # printing original stringprint("The original string is : " + str(test_str))  # initializing K K = 2  # using loop to run through characters res = ""for idx in range(len(test_str) - K + 1):        is_num = True                  # check for valid number of consecutives        for j in range(K):            is_num = is_num & test_str[idx + j].isdigit()                      # extracting numbers         if is_num :            res = ""            for j in range(K):                res += test_str[idx + j]  # printing result print("Required character digits : " + str(res)) 
The original string is : geeks5geeks43isbest
Required character digits : 43

Method #2 : Using regex()
This is yet another way in which this task can be performed. In this, we apply valid regex expression and after processing, the result is returned as occurrences, the first one is returned.
Python3
# Python3 code to demonstrate working of # First K consecutive digits in String# Using regex()import re  # initializing stringtest_str = "geeks5geeks43isbest"  # printing original stringprint("The original string is : " + str(test_str))  # initializing K K = 2  # using regex() to solve problemtemp = re.search('\d{% s}'% K, test_str)res = (temp.group(0) if temp else '')  # printing result print("Required character digits : " + str(res)) 
The original string is : geeks5geeks43isbest
Required character digits : 43

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to align text to the left in Tkinter Label?

Tkinter Label widget can be aligned using the anchor attributes. In order to calculate the accommodate spacing and alignment of the widget, anchor would help in a better way. Anchor provides several options such as N, W, S, E, NW, NE. SW, SE which can be defined in the pack manager itself.
In the following example, we will align the Label text of an application to the left by adding the anchor attribute towards “w” direction.
#Import the required library
from tkinter import*
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x250")
#Create a Label Widget
Label(win, text= "New Line Text", font= ('Helvetica 15 underline'),
background="gray74").pack(pady=20, side= TOP, anchor="w")
win.mainloop()
Running the above code will align the text label widget towards Left direction.
Program to count number of islands in a given matrix in Python

Suppose we have a binary matrix, we have to find number of islands in the matrix. Here 1 is for land and 0 is for water, so an island is a group of 1s that are neighboring and whose perimeter is surrounded by water. Here we are considering neighbors can only be horizontal or vertical, not diagonal.
So, if the input is like
then the output will be 4.
To solve this, we will follow these steps −
Define a function explore() . This will take row, col, matrix
if row and col are not in range of matrix or matrix[row, col] is 0, thenreturn
return
matrix[row, col] := 0
explore(row + 1, col, matrix)
explore(row - 1, col, matrix)
explore(row, col + 1, matrix)
explore(row, col - 1, matrix)
From the main method, do the following −
if matrix is null, thenreturn 0
return 0
islands := 0
for row in range 0 to row count of matrix, dofor col in range 0 to column count of matrix, doif matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix)
for col in range 0 to column count of matrix, doif matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix)
if matrix[row, col] is same as 1, thenislands := islands + 1explore(row, col, matrix)
islands := islands + 1
explore(row, col, matrix)
return islands
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def explore(self, row, col, matrix):
   if (
         row < 0 or col < 0 or row > len(matrix) - 1 or col > len (matrix[0]) - 1 or          matrix[row][col] == 0):
         return
      matrix[row][col] = 0
      self.explore(row + 1, col, matrix)
      self.explore(row - 1, col, matrix)
      self.explore(row, col + 1, matrix)
      self.explore(row, col - 1, matrix)
      def solve(self, matrix):
         if not matrix:
            return 0
         islands = 0
         for row in range(len(matrix)):
            for col in range(len(matrix[0])):
               if matrix[row][col] == 1:
                  islands += 1
                  self.explore(row, col, matrix)
         return islands
ob = Solution() matrix = [
   [1, 0, 1, 0, 0],
   [0, 0, 1, 0, 0],
   [0, 1, 1, 0, 0],
   [0, 0, 0, 0, 0],
   [1, 1, 0, 1, 1],
   [1, 1, 1, 0, 1]
]
print(ob.solve(matrix))
[
   [1, 0, 1, 0, 0],
   [0, 0, 1, 0, 0],
   [0, 1, 1, 0, 0],
   [0, 0, 0, 0, 0],
   [1, 1, 0, 1, 1],
   [1, 1, 1, 0, 1]
]
4
Matching Pair | Practice | GeeksforGeeks

Given a set of numbers from 1 to N, each number is exactly present twice so there are N pairs. In the worst-case scenario, how many numbers X should be picked and removed from the set until we find a matching pair?
Example 1:
Input:
N = 1
Output:
2
Explanation:
When N=1 Then there is 
one pair and a matching 
pair can be extracted in 
2 Draws.

Example 2:
Input:
N = 2
Output:
3
Explanation:
When N=2 then there are 
2 pairs, let them be {1,2,1,2}
and a matching pair will 
be made in 3 draws.


Your Task:
You don't need to read input or print anything. Your task is to complete the function find() which takes an integer N as input parameter and returns an integer, the number of x must be picked and removed from set to find a matching pair.
 
Expected Time Complexity: O(1)
Expected Space Complexity: O(1)
 
Constraints:
0 <= N <= 105
0
hashimshafeequem2 months ago
class Solution:   def find (self, N):       return N+1
0
prateekkasaudhan1232 months ago
class Solution{   static long find(int N){       // code here       return (N+1);   }}
0
jatinbitthal13193 months ago
Java solution 0.1 sec
class Solution{   static long find(int N){       // code here       return N + 1;   }}
0
thatsiddharth3 months ago
class Solution{   static long find(int N){       // code here                 return N+1;          }}
0
shambhavijha9913 months ago
def find (self, N):       return(N+1)
+1
ayushnautiyal11104 months ago
int find(int N){        return N+1;   }
-6
gyanaranjansahoo5094 months ago
its's like pigeon hole principle in mathematics
+9
rohithk4224 months ago
How N+1?
Lets say there are numbers [ 1, 2, 3, 4, 1, 2, 3, 4 ] with 1 - 4 in pairs... lets pick up 4 numbers(worst case - all diff nums) from the list 1,2,3,4(we have) now the remaining item in list is [1, 2, 3, 4]
Now - which ever number(1 or 2 or 3 or 4) I choose I will make a pair because, I already have 1, 2, 3, 4
The point 1 is N and point 2 is the +1 so the result is N+1
-4
mayank20214 months ago
#python3    def find (self, N):       return N+1
-10
naraindragokul4 months ago
Print("Hello world") 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to filter some fields in objects and fetch a specific subject name value in MongoDB?

To filter and fetch, use projection along with MongoDB $filter and $match. Let us create a collection with documents −
> db.demo507.insertOne(
... {
...
...    "Information":
...    [
...       {"Name":"John","SubjectName":"MySQL"},
...       {"Name":"Bob","SubjectName":"MongoDB"},
...       {"Name":"Chris","SubjectName":"MySQL"},
...       {"Name":"David","SubjectName":"C++"}
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8836d3987b6e0e9d18f577")
}
Display all documents from a collection with the help of find() method −
> db.demo507.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e8836d3987b6e0e9d18f577"),
   "Information" : [
      {
         "Name" : "John",
         "SubjectName" : "MySQL"
      },
      {
         "Name" : "Bob",
         "SubjectName" : "MongoDB"
      },
      {
         "Name" : "Chris",
         "SubjectName" : "MySQL"
      },
      {
         "Name" : "David",
         "SubjectName" : "C++"
      }
   ]
}
Following is the query to filter some fields in objects −
> db.demo507.aggregate([
...    {$match: {"Information.SubjectName" : "MySQL" } },
...    {$project: {
...       _id:0,
...       Information: {
...          $filter: {
...             input: '$Information',
...             as: 'result',
...             cond: {$eq: ['$$result.SubjectName', 'MySQL']}
...          }
...       }
...    }
... },{$project: {Information: { SubjectName:1}}}
... ]);
This will produce the following output −
{ "Information" : [ { "SubjectName" : "MySQL" }, { "SubjectName" : "MySQL" } ] }
Generating Test Cases (generate() and generate_n() in C++

In this section we will see how we can use C++ STL function to generate test cases. Sometimes generating test cases for array programs can be very complicated and inefficient process. C++ provides two methods to generate test cases. These methods are as follows −
The C++ function std::algorithm::generate() assigns the value returned by successive calls to gen to the elements in the range of first to last. It takes three parameters first, last and gen, these are forward iterator to the initial position, backward iterator to the final position and generator function that is called with no argument, and return values.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int create_random() {
   return (rand() % 1000);
}
int main () {
   srand(time(NULL));
   vector<int> data(15);
   generate(data.begin(), data.end(), create_random);
   for (int i=0; i<data.size(); i++)
      cout << data[i] << " " ;
}
449 180 785 629 547 912 581 520 534 778 670 302 345 965 107
The C++ function std::algorithm::generate_n() assigns the value returned by successive calls to gen for first n elements. It takes three parameters first, n and gen, these are forward iterator to the initial position, number of calls will be there and generator function that is called with no argument, and return values.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int create_random() {
   return (rand() % 1000);
}
int main () {
   srand(time(NULL));
   vector<int> data(15);
   generate_n(data.begin(), 6, create_random);
   for (int i=0; i<data.size(); i++)
      cout << data[i] << " " ;
}
540 744 814 771 254 913 0 0 0 0 0 0 0 0 0
TypeScript - String split()

This method splits a String object into an array of strings by separating the string into substrings.
string.split([separator][, limit]);

separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string.
separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string.
limit − Integer specifying a limit on the number of splits to be found.
limit − Integer specifying a limit on the number of splits to be found.
The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array.
var str = "Apples are round, and apples are juicy."; 
var splitted = str.split(" ", 3); 
console.log(splitted)

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
[ 'Apples', 'are', 'round,' ]


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Importance of the accumulate() method of JSONObject in Java?

A JSONObject is an unordered collection of a name and value pairs. A few important methods of JSONArray are accumulate(), put(), opt(), append(), write() and etc. The accumulate() method accumulates the values under a key and this method similar to the put() method except if there is an existing object stored under a key then a JSONArray can be stored under a key to hold all of the accumulated values. If there is an existing JSONArray then a new value can be added.
public JSONObject accumulate(java.lang.String key, java.lang.Object value) throws JSONException
import org.json.*;
public class JSONAccumulateMethodTest {
   public static void main(String[] args) throws JSONException {
      JSONObject jsonObj = new JSONObject();
      jsonObj.accumulate("Technology", "Java");
      jsonObj.accumulate("Technology", "Python");
      jsonObj.accumulate("Technology", "Spark");
      jsonObj.accumulate("Technology", "Selenium");
      jsonObj.accumulate("Technology", ".Net");
      System.out.println(jsonObj.toString(3));
   }
}
{"Technology": [
   "Java",
   "Python",
   "Spark",
   "Selenium",
   ".Net"
]}
Apache IVY - Cachepath Task

cachepath task is used to create an ANT classpath with resolved artifacts present in the cache. As ANT needs jars to be classpath to compile java files, Ivy cachepath builds the classpath.
Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter.
Update the build.xml to use the ivy retrieve task.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
   <target name="resolve" description="resolve dependencies">
      <ivy:resolve />
      <ivy:cachepath pathid="new.classpath" />
   </target>
   <target name="compile" depends="resolve" description="Compile">
      <mkdir dir="build/classes" />
      <javac srcdir="src" destdir="build/classes">
         <classpath refid="new.classpath" />
      </javac>
   </target>
</project>
Following are the important terms.
pathid − id of the classpath where cached jars are present.
pathid − id of the classpath where cached jars are present.
retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute.
As we've all the files ready. Just go the console. Navigate to E: > ivy  folder and run the ant command.
E:\ivy > ant compile

Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy\build.xml

resolve:
[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-
PC
[ivy:resolve]   confs: [default]
[ivy:resolve]   found commons-lang#commons-lang;2.6 in public
[ivy:resolve]   found junit#junit;3.8.1 in public
[ivy:resolve] :: resolution report :: resolve 2314ms :: artifacts dl 15ms
      ---------------------------------------------------------------------
      |                  |            modules            ||   artifacts   |
      |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
      ---------------------------------------------------------------------
      |      default     |   2   |   2   |   0   |   0   ||   4   |   0   |
      ---------------------------------------------------------------------

compile:
   [javac] E:\ivy\build.xml:13: warning: 'includeantruntime' was not set, defau
lting to build.sysclasspath=last; set to false for repeatable builds
   [javac] Compiling 1 source file to E:\ivy\build\classes

BUILD SUCCESSFUL
Total time: 3 seconds

You can verify the compiled class file in project build directory.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
How to make a Tkinter canvas rectangle transparent?

The canvas widget is one of the most versatile widgets in Tkinter Library. Generally, it is used to draw shapes, animate objects, and create complex graphics in any application. To create shapes like Rectangle, we use the create_rectangle(x,y, x+ width, y+ height, **options) method. We can configure the item on the canvas by adding properties such as width, height, fill and bg, border width, etc.
The alpha property in canvas defines the transparency of the canvas item. However, the property is not available in the Tkinter library; thus, we must define a function to provide the transparency attribute in shape. The steps to create the function for transparency attribute are,
Define an inbuilt function create_rectangle(x,y,a,b, **options).
Calculate the alpha for each color (RGB) that must be provided to the shape.
Remove the predefined alpha (if applicable) from the shape using pop().
Calculate the shape color in the region using winfo_rgb() and add the alpha to the shape.
Since a newly created shape will have different color and background, thus it must be needed to use this as an image.
The Image can be displayed in the canvas easily.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win= Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Store newly created image
images=[]

# Define a function to make the transparent rectangle
def create_rectangle(x,y,a,b,**options):
   if 'alpha' in options:
      # Calculate the alpha transparency for every color(RGB)
      alpha = int(options.pop('alpha') * 255)
      # Use the fill variable to fill the shape with transparent color
      fill = options.pop('fill')
      fill = win.winfo_rgb(fill) + (alpha,)
      image = Image.new('RGBA', (a-x, b-y), fill)
      images.append(ImageTk.PhotoImage(image))
      canvas.create_image(x, y, image=images[-1], anchor='nw')
      canvas.create_rectangle(x, y,a,b, **options)
# Add a Canvas widget
canvas= Canvas(win)

# Create a rectangle in canvas
create_rectangle(50, 110,300,280, fill= "blue", alpha=.3)
create_rectangle(40, 90, 420, 250, fill= "red", alpha= .1)
canvas.pack()

win.mainloop()
Running the above code will display multiple transparent rectangles in the canvas.
C++ program to Solve Tower of Hanoi Problem using Binary Value

This C++ program displays the solution to the Tower of Hanoi problem using binary value.
There is one binary digit for each disk.
The most significant bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it’s on the final peg.
The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk.
The corresponding disk is stacked on top the previous disk on the same peg if a bit has the same value as the previous one.
If it is different that means that the corresponding disk is one position to the left or right of the previous one.
Begin
   Take the number of disk n as input.
   Declare n and a.
   Make a for loop a = 1 to (1<<n) – 1
   //
   Here, (a & a – 1) = bitwise AND with a and a – 1.
      (a | a – 1) = bitwise OR with a and a – 1.
         Here % means modulus operator.
   //
   Print the result indicating that moving disks from peg number (a & a – 1) % 3 to peg number ((a | a – 1) + 1) % 3
End
#include<iostream>
using namespace std;
int main() {
   int n, a;
   cout<<"\nEnter the no of Disks: ";
   cin>>n;
   for (a = 1; a < (1 << n); a++) {
      cout<<"\nDisk Move from Peg "<<(a&a-1)%3 <<" to Peg "<<((a|a-1)+1)%3;
   }
   cout<<"\n";
}
Enter the no of Disks: 3
Disk Move from Peg 0 to Peg 2
Disk Move from Peg 0 to Peg 1
Disk Move from Peg 2 to Peg 1
Disk Move from Peg 0 to Peg 2
Disk Move from Peg 1 to Peg 0
Disk Move from Peg 1 to Peg 2
Disk Move from Peg 0 to Peg 2
Rod Cutting

A rod is given of length n. Another table is also provided, which contains different size and price for each size. Determine the maximum price by cutting the rod and selling them in the market.
To get the best price by making a cut at different positions and comparing the prices after cutting the rod.
Let the f(n) will return the max possible price after cutting a row with length n. We can simply write the function f(n) like this.
f(n) := maximum value from price[i]+f(n – i – 1), where i is in range 0 to (n – 1).
Input:
The price of different lengths, and the length of rod. Here the length is 8.
Output:
Maximum profit after selling is 22.
Cut the rod in length 2 and 6. The profit is 5 + 17 = 22
rodCutting(price, n)
Input: Price list, number of different prices on the list.
Output: Maximum profit by cutting rods.
Begin
   define profit array of size n + 1
   profit[0] := 0
   for i := 1 to n, do
      maxProfit := - ∞
      for j := 0 to i-1, do
         maxProfit := maximum of maxProfit and (price[j] + profit[i-j-1])
      done

      profit[i] := maxProfit
   done
   return maxProfit
End
#include <iostream>
using namespace std;

int max(int a, int b) {
   return (a > b)? a : b;
}

int rodCutting(int price[], int n) {    //from price and length of n, find max profit
   int profit[n+1];
   profit[0] = 0;
   int maxProfit;

   for (int i = 1; i<=n; i++) {
      maxProfit = INT_MIN;    //initially set as -ve infinity
      for (int j = 0; j < i; j++)
         maxProfit = max(maxProfit, price[j] + profit[i-j-1]);
      profit[i] = maxProfit;
   }
   return maxProfit;
}

int main() {
   int priceList[] = {1, 5, 8, 9, 10, 17, 17, 20};
   int rodLength = 8;
   cout << "Maximum Price: "<< rodCutting(priceList, rodLength);
}
Maximum Price: 22
Differences between Interface and class in Java

A class is a blueprint from which individual objects are created. A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.
Following are the important differences between Class and an Interface.
public class JavaTester {
   public static void main(String args[]) {
      Animal tiger = new Tiger();
      tiger.eat();
      Tiger tiger1 = new Tiger();
      tiger1.eat();
   }
}
interface Animal {
   public void eat();
}
class Tiger implements Animal {
   public void eat(){
      System.out.println("Tiger eats");
   }
}
Tiger eats
Tiger eats
Tryit Editor v3.7

CSS Grid Container
Tryit: Using justify-content: end
Python program to Remove and print every third from list until it becomes empty?

First we create a list, the index of the starting address is 0 and the position of the first third element is 2 and need to traverse till the list becomes empty and another important work to do every time we have to find the index of the next third element and print the value and after that reduce the length of the list.
A:[10,20,30,40]
OUTPUT:30 20 40 10

The first third element is 30, then we count from 40 for next third element 20,then again start from 40 for the next third element is 40 itself and finally 10 is printed.
Step 1: The index of the list starts from 0 and the first third element will be at position 2.
variable p=2,starting index id=0.

Step 2: find the length of the list.
listlen=len (LST)	// length of the list(LST)

Step 3: Traverse till the list becomes empty and each time find the index of the next third element.
While(listlen>0)
   Id=(p+id)%listlen
   A=LST.pop(id)// removes and prints the required element
      Listlen-=1
End while
# To remove to every third element until list becomes empty
def removenumber(no):
   # list starts with
   # 0 index
   p = 3 - 1
   id = 0
   lenoflist = (len(no))

   # breaks out once the
   # list becomes empty
   while lenoflist > 0: 
      id = (p + id) % lenoflist

      # removes and prints the required
      # element
      print(no.pop(id)) 
      lenoflist -= 1

# Driver code
A=list()        
n=int(input("Enter the size of the array ::"))
print("Enter the INTEGER number")
for i in range(int(n)):
   p=int(input("n="))
   A.append(int(p))
print("After remove third element, The List is")
removenumber(A)         # call function
Enter the size of the array ::9
Enter the number
n=10
n=20
n=30
n=40
n=50
n=60
n=70
n=80
n=90
After remove third element, The List is
30
60
90
40
80
50
20
70
10
Java - compareTo() Method

The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc.
However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type.
public int compareTo( NumberSubClass referenceName )

Here is the detail of parameters −
referenceName − This could be a Byte, Double, Integer, Float, Long, or Short.
referenceName − This could be a Byte, Double, Integer, Float, Long, or Short.
If the Integer is greater than the argument then 1 is returned.
If the Integer is equal to the argument then 0 is returned.
If the Integer is less than the argument then -1 is returned.
public class Test {
   public static void main(String args[]) {
      Integer x = 5;
      //Integer value is greater than the argument (5>3) so, output is 1
      System.out.println(x.compareTo(3));
      //Integer value is equal to the argument so, output is 0
      System.out.println(x.compareTo(5));
      //Integer value is less than the argument (5<8) so, output is −1
      System.out.println(x.compareTo(8));            
   }
}
This will produce the following result −
1
0
-1


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
What is the syntax to define enums in javascript?

Enums are not supported in JavaScript natively. We can however create Enums using Object.freeze by creating objects containing all the enumerable properties and then freezing the object so that no new enum can be added to it.
const Color = {
   RED: 1,
   BLUE: 2,
   GREEN: 3,
   YELLOW: 4
};
Object.freeze(Color);
// Example usage:
let carColor = Color.BLUE;
// Trying to add new colors fails silently:
Color.WHITE = 5;
console.log(Color)
{ RED: 1, BLUE: 2, GREEN: 3, YELLOW: 4 }
Accessing elements of a Pandas Series

Pandas series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The elements of a pandas series can be accessed using various methods.
Let's first create a pandas series and then access it's elements.
A panadas series is created by supplying data in various forms like ndarray, list, constants and the index values which must be unique and hashable. An example is given below.
import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s
Running the above code gives us the following result −
a    11
b    8
c    6
d    14
e  25
dtype: int64
We can access the data elements of a series by using various methods. We will continue to use the series created above to demonstrate the various methods of accessing.
The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value.
import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[0]
print s['a']
Running the above code gives us the following result −
11
11
In a similar manner as above we get the first three elements by using the : value in front of the index value of 3 or the appropriate custom index value.
import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[:3]
print s[:'c']
Running the above code gives us the following result −
a    11
b    8
c    6
dtype: int64
a    11
b   8
c 6
dtype: int64
In a similar manner as above, we get the first three elements by using the: value at the end of the index value of 3 with a negative sign or the appropriate custom index value.
import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[-3:]
print s['c':]
Running the above code gives us the following result −
c 6
d 14
e 25
dtype: int64
c 6
d 14
e 25
dtype: int64
In this case, we use the custom index values to access non-sequential elements of the series.
import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[['c','b','e']]
Running the above code gives us the following result −
c 6
b 8
e 25
dtype: int64
Tryit Editor v3.7

Tryit: HTML border color
Convert a given Binary Tree to Doubly Linked List (Set 1) in C++

In this tutorial, we will be discussing a program to convert a binary tree to a doubly linked list.
For this we will be provided with a binary tree. Our task is to convert it into a doubly linked list such that the left and right pointers become the previous and next pointers. Also the sequential order of the doubly linked list must be equal to the inorder traversal of the binary tree.
For this we are having a very straight forward approach. We will be traversing the binary tree in in order way making the nodes of the doubly linked list along with and finally making the left and right to be the previous and next nodes respectively.
 Live Demo
#include <iostream>
using namespace std;
//node structure of binary tree
struct node{
   int data;
   node* left;
   node* right;
};
//traversing and making nodes for
//doubly linked list
void binarytodll(node *root, node **head){
   if (root == NULL)
      return;
   static node* prev = NULL;
   //converting left subtree
   binarytodll(root->left, head);
   if (prev == NULL)
      *head = root;
   else {
      root->left = prev;
      prev->right = root;
   }
   prev = root;
   //converting right subtree
   binarytodll(root->right, head);
}
//allocating a new node
node* newNode(int data) {
   node* new_node = new node;
   new_node->data = data;
   new_node->left = new_node->right = NULL;
   return (new_node);
}
//printing nodes of doubly linked list
void print_dll(node *node){
   while (node!=NULL) {
      cout << node->data << " ";
      node = node->right;
   }
}
int main(){
   node *root = newNode(10);
   root->left = newNode(12);
   root->right = newNode(15);
   root->left->left = newNode(25);
   root->left->right = newNode(30);
   root->right->left = newNode(36);
   node *head = NULL;
   binarytodll(root, &head);
   print_dll(head);
   return 0;
}
25 12 30 10 36 15
HTML | <tr> bgcolor Attribute

26 Jun, 2019
The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5.
Syntax:
<tr bgcolor= "color_name | hex_number | rgb_number">
Attribute Values:
color_name: It sets the background color by using the color name. For example “red”.
hex_number: It sets the background color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the background color by using the RGB code. For example: “RGB(0, 153, 0)” .
Example:
<!DOCTYPE html><html>  <head>    <title>HTML tr bgcolor Attribute</title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML tr bgcolor Attribute</h2>      <table width="500" border="1">        <tr bgcolor="green">            <th>Name</th>            <th>Expenses</th>        </tr>          <tr bgcolor="yellow">            <td>BITTU</td>            <td>2500.00</td>        </tr>          <tr bgcolor="red">            <td>RAKESH</td>            <td>1400.00</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <tr> bgcolor attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
What is ObjectId in MongoDB

01 Nov, 2020
Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.
An ObjectID is a 12-byte Field Of BSON type
The first 4 bytes representing the Unix Timestamp of the document
The next 3 bytes are the machine Id on which the MongoDB server is running.
The next 2 bytes are of process id
The last Field is 3 bytes used for increment the objectid.
Format of ObjectId:
ObjectId(<hexadecimal>)

ObjectId accepts one parameter which is optional Hexadecimal ObjectId in String.
We can give our own ObjectId to the document but it must be unique.
*db.<collectionname>.insertOne({"_id":"231231"})

Example:
Database : gfg
Collection: student_gfg
Methods of ObjectId:
str: Returns the hexadecimal string format of the ObjectIdObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date.ObjectId.valueOf(): It return the hexadecimal format of a given String Literal.ObjectId.toString(): This method returns ObjectId in String format in javascript representation.
str: Returns the hexadecimal string format of the ObjectId
ObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date.
ObjectId.valueOf(): It return the hexadecimal format of a given String Literal.
ObjectId.toString(): This method returns ObjectId in String format in javascript representation.
1.Creating ObjectId: To generate new ObjectId of particular document.
newObjectId = ObjectId()
Output:
ObjectId(“5f92cbf10cf217478ba93561”)
2.Timestamp of the ObjectID: It returns the timestamp information of the object as a Date in ISO format.
var id =new ObjectId();    
 id.getTimestamp()
Output:
ISODate(“2020-10-23T12:32:42Z”)
3.Converting ObjectId to string: ObjectId can be converted into string format.
 new ObjectId().str
Output:
5f92cdce0cf217478ba93563
Technical Scripter 2020
MongoDB
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | mime_content_type() function

15 Jul, 2019
The mime_content_type() function is an inbuilt function in PHP which is used to get the MIME content-type of a file.
Syntax:
string mime_content_type( $file )
Parameters: This function accepts single parameter $file which specifies the path of the file which MIME details to be find.
Return Value: This function returns the MIME content type or False on failure.
Below programs illustrate the mime_content_type() function in PHP:
Program 1:Original Image:
<?php  // PHP program to illustrate mime_content_type function  echo mime_content_type('gfg.png') . "</br>";?>
Output:
image/png

Program 2:Original Image:
<?php  // PHP program to illustrate // mime_content_type function  // Providing and print result of different kind of files echo mime_content_type('/home/rajvir/Desktop/gfg.png') . "</br>";echo mime_content_type('/home/rajvir/Desktop/gfg_Article.html') . "</br>";echo mime_content_type('/home/rajvir/Downloads/gfg.gif') . "</br>";echo mime_content_type('/home/rajvir/Desktop/gfg_contribute.txt') . "</br>";echo mime_content_type('/home/rajvir/Downloads/geeks.ppt') . "</br>";echo mime_content_type('/home/rajvir/Downloads/geeks.pdf') . "</br>";  ?>
Output:
image/png
text/plain
image/gif
text/plain
application/vnd.ms-powerpoint
application/pdf

Reference: http://php.net/manual/en/function.mime-content-type.php
ManasChhabra2
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Download file from URL using PHP
Split a comma delimited string into an array in PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Java - String hashCode() Method

This method returns a hash code for this string. The hash code for a String object is computed as −
s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]

Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
Here is the syntax of this method −
public int hashCode()

Here is the detail of parameters −
This is a default method and this will not accept any parameters.
This method returns a hash code value for this object.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      System.out.println("Hashcode for Str :" + Str.hashCode() );
   }
}
This will produce the following result −
Hashcode for Str :1186874997
Matplotlib.pyplot.hsv() 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.
The hsv() function in pyplot module of matplotlib library is used to set the colormap to “hsv”.Syntax:
matplotlib.pyplot.hsv()

Below examples illustrate the matplotlib.pyplot.hsv() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np         ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad)      angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis],                   rad, axis = 1)angles[:, 1::2] += np.pi / ang      x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten()      triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),                         y[triang.triangles].mean(axis = 1))                < radm)      tpc = plt.tripcolor(triang, z, shading ='flat')  plt.hsv()  plt.title('matplotlib.pyplot.hsv() function Example',          fontweight ="bold")  plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm    dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y)      extent = np.min(x), np.max(x), np.min(y), np.max(y)  Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r",           interpolation ='nearest',           extent = extent,           alpha = 1)      def geeks(x, y):          return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))      Z2 = geeks(X, Y)      plt.imshow(Z2, alpha = 0.7,            interpolation ='bilinear',           extent = extent)  plt.hsv()  plt.title('matplotlib.pyplot.hsv() function\Example', fontweight ="bold")  plt.show()
Output:
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 ?
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python