code-rag-bench/online-tutorials huggingface dataset:
Program to reverse an array up to a given position in Python

In this tutorial, we will learn how to reverse an array upto a given position. Let's see the problem statement.
We have an array of integers and a number n. Our goal is to reverse the elements of the array from the 0th index to (n-1)th index. For example,
Input
array = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 5
Output
[5, 4, 3, 2, 1, 6, 7, 8, 9]
Procedure to achieve the goal.
 Initialize an array and a number
 Loop until n / 2. Swap the (i)th index and (n-i-1)th elements.
 Swap the (i)th index and (n-i-1)th elements.
Print the array you will get the result.
## initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
## checking whether the n value is less than length of the array or not
if n > len(arr):
   print(f"{n} value is not valid")
else:
   ## loop until n / 2
   for i in range(n // 2):
      arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i]
   ## printing the array
   print(arr)
If you run the above program, you will get the following results.
[5, 4, 3, 2, 1, 6, 7, 8, 9]
A simple way to do this is to use the slicing in Python.
1. Initialize an array and a number
2. Slice from (n-1) to 0 and n to length(Add both of them).
Let's see the code.
## initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
## checking whether the n value is less than length of the array or not
if n > len(arr):
   print(f"{n} value is not valid")
else:
   ## reversing the arr upto n
   ## [n-1::-1] n - 0 -1 is for decrementing the index
   ## [n:] from n - length
   arr = arr[n-1::-1] + arr[n:]
   ## printing the arr
   print(arr)
If you run the above program, you will get the following result.
[5, 4, 3, 2, 1, 6, 7, 8, 9]
If you have any doubts regarding the program, please do mention them in the comment section.
Java Examples - Copy a File

How to copy one file into another file ?
This example shows how to copy contents of one file into another file using read & write methods of BufferedWriter class.
import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
      BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
      out1.write("string to be copied\n");
      out1.close();
      InputStream in = new FileInputStream(new File("srcfile"));
      OutputStream out = new FileOutputStream(new File("destnfile"));
      byte[] buf = new byte[1024];
      int len;
      
      while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
      }
      in.close();
      out.close();
      BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
      String str;
      
      while ((str = in1.readLine()) != null) {
         System.out.println(str);
      }
      in.close();
   }
}
The above code sample will produce the following result.
string to be copied

The following is another sample example of copy one file into another file in java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class CopyExample {
   public static void main(String[] args) {
      FileInputStream ins = null;
      FileOutputStream outs = null;
      try {
         File infile = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         File outfile = new File("C:\\Users\\TutorialsPoint7\\Desktop\\bbc.txt");
         ins = new FileInputStream(infile);
         outs = new FileOutputStream(outfile);
         byte[] buffer = new byte[1024];
         int length;
         
         while ((length = ins.read(buffer)) > 0) {
            outs.write(buffer, 0, length);
         } 
         ins.close();
         outs.close();
         System.out.println("File copied successfully!!");
      } catch(IOException ioe) {
         ioe.printStackTrace();
      } 
   }
}
The above code sample will produce the following result.
File copied successfully!!

 Print
 Add Notes
 Bookmark this page
How we can iterate through a Python list of tuples?

Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=’ ‘ to print all items in a tuple in one line. Another print() introduces new line after each tuple.
L=[(1,2,3), (4,5,6), (7,8,9,10)]
for x in L:
  for y in x:
    print(y, end=' ')
  print()
1 2 3

4 5 6

7 8 9 10
SQL Query to Display Last 50% Records from Employee Table

13 Apr, 2021
Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server’s databases.
For the purpose of demonstration, we will be creating an Employee table in a database called “geeks“.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE Employee(
ID INT IDENTITY(1,1) KEY,     --IDENTITY(1,1) tells start ID from 1 and increment
                            -- it by 1 with each row inserted.
NAME VARCHAR(30) NOT NULL,
PHONE INT NOT NULL UNIQUE,
EMAIL VARCHAR(30) NOT NULL UNIQUE,
DATE_OF_JOINING DATE);
NOTE: We should use VARCHAR or BIGINT as the data type for the PHONE column to avoid integer overflow.
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS Employee;
Use the below statement to add data to the Employee table:
INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)
VALUES
('Yogesh Vaishnav', 0000000001, 'yogesh@mail.com', '2019-10-03'),
('Vishal Vishwakarma', 0000000002, 'chicha@mail.com', '2019-11-07'),
('Ajit Yadav', 0000000003, 'ppa@mail.com', '2019-12-12'),
('Ashish Yadav', 0000000004, 'baba@mail.com', '2019-12-25'),
('Tanvi Thakur', 0000000005, 'tanvi@mail.com', '2020-01-20'),
('Sam', 0000000006, 'sam@mail.com', '2020-03-03'),
('Ron', 0000000007, 'ron@mail.com', '2020-05-16'),
('Sara', 0000000008, 'sara@mail.com', '2020-07-01'),
('Zara', 0000000009, 'zara@mail.com', '2020-08-20'),
('Yoji', 0000000010, 'yoji@mail.com', '2020-03-10'),
('Rekha Vaishnav', 12, 'rekha@mail.com', '2021-03-25');
To verify the contents of the table use the below statement:
SELECT * FROM Employee;
Now let’s retrieve the last 50% of the records from the Employee Table.
In MS SQL we can directly retrieve the last 50% of the records with the help of top and percent and order by clauses. A simple syntax for the same is given below:
Syntax :
select * from 
  /*Gives the top N percent records from bottom of a database table*/
(select top N percent * from <table_name> order by <column_name> desc)<identifier>
order by <column_name>;
Example :
SELECT * FROM
(SELECT top 50 percent * FROM Employee ORDER BY ID DESC)
ORDER BY ID;
Output :
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS | matrix3d() Function

21 Aug, 2019
The matrix3d() function is an inbuilt function which is used to apply a transformation to create a 3D transformation as a 4×4 homogeneous matrix.
Syntax:
matrix3d( a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4 )
Parameters: This function accepts 16 parameters as mentioned above and described below:
a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, d4: These parameters are used to hold the value for linear transformation.
a4, b4, c4: These parameters are used to hold the value of translation.
Below example illustrates the matrix3d() function in CSS:Example:
<!DOCTYPE html> <html> <head>     <title>        CSS matrix3d() function        </title>               <style>         .GFG {             transform: matrix3d(                0.6, 0.1, 0.7, 0,                -0.5, 0.8, 0.1, 0,                -0.6, -0.5, 0.5, 0,                0, 0, 0, 1            );                          font-size:26px;            font-weight:bold;            width:250px;            padding:20px;            background: green;            color: white;            font-family: sans-serif;        }     </style>       </head>   <body>     <center>        <h1 style="color:green">GeeksforGeeks</h1>         <h2>CSS matrix3d() function</h2>         <br><br>               <div class="GFG">            Welcome to GeeksforGeeks        </div>     </center></body>   </html>                    
Output:
Supported Browsers: The browsers supported by matrix3d() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Swing Examples - Change the default icon of the window

Following example showcase how to change the default icon of the window in Swing based application.
We are using the following APIs.
ImageIcon − To create an image icon.
ImageIcon − To create an image icon.
JFrame.setIconImage() − To set the icon to the window.
JFrame.setIconImage() − To set the icon to the window.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();   
   }
   
   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");           
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ImageIcon arrowIcon = null;

      java.net.URL imgURL = SwingTester.class.getResource("arrow.jpg");
      if (imgURL != null) {
         arrowIcon = new ImageIcon(imgURL);
         frame.setIconImage(arrowIcon.getImage());
      } else {
         JOptionPane.showMessageDialog(frame, "Icon image not found.");
      }

      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(JFrame frame){      
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       
      panel.add(new JLabel("Hello World!"));

      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}
 Print
 Add Notes
 Bookmark this page
LESS - Namespaces and Accessors

Namespaces are used to group the mixins under a common name. Using namespaces, you can avoid conflict in name and encapsulate a group of mixins from outside.
The following example demonstrates the use of namespaces and accessors in the LESS file −
<html>
   <head>
      <title>Less Namespaces and Accessors</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
   </head>
   
   <body>
      <h1>Example using Namespaces and Accessors</h1>
      <p class = "myclass">LESS enables customizable, 
      manageable and reusable style sheet for web site.</p>
   </body>
</html>
Now create the style.less file.
.class1 {
   .class2 {
      .val(@param) {
         font-size: @param;
         color:green;
      }
   }
}

.myclass {
   .class1 > .class2 > .val(20px);
}
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css

Execute the above command; it will create the style.css file automatically with the following code −
.myclass {
   font-size: 20px;
   color: green;
}
Follow these steps to see how the above code works −
Save the above html code in the namespaces_accessors.html file.
Save the above html code in the namespaces_accessors.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Colored Flower by circles using Turtle in Python - GeeksforGeeks

01 Aug, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Following steps are used :
Import Turtle
Set screen
Make Turtle Object
Define colors used for drawing
Loop to draw circles oriented by angle.
Below is the implementation :
Python3
# import turtle package import turtle  # screen objectsc = turtle.Screen()     # turtle objectpen = turtle.Turtle()      # Driver Code# colorscol = ['violet', 'indigo', 'blue', 'green',        'yellow', 'orange', 'red']  # screen sizesc.setup(500,500)   # screen colorsc.bgcolor('black')  # turtle sizepen.pensize(4)   # turtle objectpen.speed(20)      # integer variable # for accessing colorsi = 0  # loop to draw 30 circles for angle in range(0, 360, 12):      # color of circle  pen.color(col[i])        if i == 6:               i = 0        else:    i += 1        # Set the orientation of  # the turtle to angle  pen.seth(angle)       # circle of radius 80  pen.circle(80)     # hide the turtlepen.ht()
Python-turtle
Python
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Converting image to Grayscale without using any methods Java OpenCV.

To convert the colored image to grayscale.
Get the red green blue values of each pixel
Get the red green blue values of each pixel
Get the average of these 3 colors.
Get the average of these 3 colors.
Replace the RGB values with the average.
Replace the RGB values with the average.
Create a new pixel value from the modified colors.
Create a new pixel value from the modified colors.
Set the new value to the pixel.
Set the new value to the pixel.
import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Color2Grey {
   public static void main(String args[])throws IOException {
      //Reading the image
      File file= new File("D:\\Images\\car.jpg");
      BufferedImage img = ImageIO.read(file);
      for (int y = 0; y < img.getHeight(); y++) {
         for (int x = 0; x < img.getWidth(); x++) {
            //Retrieving the values of a pixel
            int pixel = img.getRGB(x,y);
            //Creating a Color object from pixel value
            Color color = new Color(pixel, true);
            //Retrieving the R G B values
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();
            //Finding the average of the red green blue values
            int average = (red+green+blue)/3;
            //Creating new Color object
            color = new Color(average, average, average);
            //Setting new Color object to the image
            img.setRGB(x, y, color.getRGB());
         }
      }
      //Saving the modified image
      file = new File("D:\\Images\\grey_image.jpg");
      ImageIO.write(img, "jpg", file);
      System.out.println("Done...");
   }
}
How to loop through collections with a cursor in MongoDB?

Following is the syntax to loop through collections with cursor
var anyVariableName1;
var anyVariableName2= db.yourCollectionName.find();
while(yourVariableName2.hasNext()) {
   yourVariableName1= yourVariableName2.next(); printjson(yourVariableName1);
};
Let us create a collection with documents. Following is the query
> db.loopThroughCollectionDemo.insertOne({"StudentName":"John","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca81f2d6669774125247f")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca8272d66697741252480")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Chris","StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca8462d66697741252481")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Robert","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca8632d66697741252482")
}
Following is the query to display all documents from a collection with the help of find() method
> db.loopThroughCollectionDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9ca81f2d6669774125247f"),
   "StudentName" : "John",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5c9ca8272d66697741252480"),
   "StudentName" : "Larry",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c9ca8462d66697741252481"),
   "StudentName" : "Chris",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c9ca8632d66697741252482"),
   "StudentName" : "Robert",
   "StudentAge" : 24
}
Following is the query to loop through collections with cursor
> var allDocumentValue;
> var collectionName=db.loopThroughCollectionDemo.find();
> while(collectionName.hasNext()){allDocumentValue= collectionName.next();printjson(allDocumentValue);
... }
This will produce the following output
{
   "_id" : ObjectId("5c9ca81f2d6669774125247f"),
   "StudentName" : "John",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5c9ca8272d66697741252480"),
   "StudentName" : "Larry",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c9ca8462d66697741252481"),
   "StudentName" : "Chris",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c9ca8632d66697741252482"),
   "StudentName" : "Robert",
   "StudentAge" : 24
}
Insert() Method in C#

The Insert() method in C# is used to return a new string in which a specified string is inserted at a specified index position in this instance.
The syntax is as follows −
public string Insert (int begnIndex, string val);
Above, the parameter begnIndex is the zero-based index position of the insertion, whereas val is the string to insert.
Let us now see an example −
 Live Demo
using System;
public class Demo{
   public static void Main(){
      String str = "JohnWick";
      Console.WriteLine("Initial string = "+str);
      String res = str.Insert(5, " ");
      Console.WriteLine("Updated = "+res);
   }
}
This will produce the following output −
Initial string = JohnWick
Updated = JohnW ick
Let us now see another example
 Live Demo
using System;
public class Demo{
   public static void Main(){
      String str = "WelcomeJacob";
      Console.WriteLine("Initial string = "+str);
      String res = str.Insert(7, " here, ");
      Console.WriteLine("Updated = "+res);
   }
}
This will produce the following output −
Initial string = WelcomeJacob
Updated = Welcome here, Jacob
Python Program to Print Numbers in an Interval

In this article, we will learn about the solution and approach to solve the given problem statement.
Given the starting and ending range of an interval. We need to print all the numbers in the interval given.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
There are two for loops, first for loop is for getting the numbers in the interval and second loop for the checking whether the number is prime or not.
Now let’s see the implementation.
 Live Demo
start = 10
end = 29
for val in range(start, end + 1):
# If num is divisible by any number is not prime
   if val > 1:
      for n in range(2, val):
         if (val % n) == 0:
            break
      else:
         print(val)
11
13
17
19
23
29
All variables and functions are declared in the global scope as shown in the figure below.
In this article, we learned about the approach to print numbers in a given interval.
Check if MongoDB database exists?

There are two possibilities to check if MongoDB database exists.
Case 1: The first possibility is that the MongoDB database exists i.e. it returns particular index.
Case 2: The second possibility is that the MongoDB database does not exist i.e. it returns index -1.
NOTE: An index starts from 0 and ends with (N-1) like an array.
The syntax is as follows to check if MongoDB database exists.
db.getMongo().getDBNames().indexOf("yourDatabaseName");
Case 1: Let us implement the above syntax to check if MongoDB database exists. Following is the query
db.getMongo().getDBNames().indexOf("test");
This will produce the following output
6
Look at the above sample output, we are getting 6 that means the database “test” exists and it is present at index 6.
Let us check all the databases now. Following is the query
> show dbs;
This will produce the following output
admin             0.001GB
config            0.000GB
local             0.000GB
sample            0.001GB
sampleDemo        0.000GB
studentSearch     0.000GB
test              0.009GB
Look at the above sample output, the database “test” exists and at index 6.
Case 2: If MongoDB database does not exist
> db.getMongo().getDBNames().indexOf("education");
The following is the output displaying -1 since the database “education” does not exist
-1
What is strstr() Function in C language?

The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.
An array of characters is called a string.
The syntax for declaring an array is as follows −
char stringname [size];
For example − char string[50]; string of length 50 characters
Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
It is used to search whether a substring is present in the main string or not.
It is used to search whether a substring is present in the main string or not.
It returns pointer to first occurrence of s2 in s1.
It returns pointer to first occurrence of s2 in s1.
The syntax for strstr() function is as follows −
strstr(mainsring,substring);
The following program shows the usage of strstr() function.
 Live Demo
#include<stdio.h>
void main(){
   char a[30],b[30];
   char *found;
   printf("Enter a string:\n");
   gets(a);
   printf("Enter the string to be searched for:\n");
   gets(b);
   found=strstr(a,b);
   if(found)
      printf("%s is found in %s in %d position",a,b,found-a);
   else
      printf("-1 since the string is not found");
}
When the above program is executed, it produces the following result −
Enter a string: how are you
Enter the string to be searched for: you
you is found in 8 position
Let’s see another program on strstr() function.
Given below is a C program to find, if a string is present in another string as substring by using strstr library function −
 Live Demo
#include<stdio.h>
#include<string.h>
void main(){
   //Declaring two strings//
   char mainstring[50],substring[50];
   char *exists;
   //Reading strings//
   printf("Enter the main string : \n ");
   gets(mainstring);
   printf("Enter the sub string you would want to check if exists in main string :");
   gets(substring);
   //Searching for sub string in main string using library function//
   exists = strstr(mainstring,substring);
   //Conditions//
   if(exists){
      printf("%s exists in %s ",substring,mainstring);
   } else {
      printf("'%s' is not present in '%s'",substring,mainstring);
   }
}
When the above program is executed, it produces the following result −
Enter the main string : TutorialsPoint c Programming
Enter the sub string you would want to check if exists in main string :Programming
Programming exists in TutorialsPoint c Programming
C library function - strrchr()

The C library function char *strrchr(const char *str, int c) searches for the last occurrence of the character c (an unsigned char) in the string pointed to, by the argument str.
Following is the declaration for strrchr() function.
char *strrchr(const char *str, int c)
str − This is the C string.
str − This is the C string.
c − This is the character to be located. It is passed as its int promotion, but it is internally converted back to char.
c − This is the character to be located. It is passed as its int promotion, but it is internally converted back to char.
This function returns a pointer to the last occurrence of character in str. If the value is not found, the function returns a null pointer.
The following example shows the usage of strrchr() function.
#include <stdio.h>
#include <string.h>

int main () {
   int len;
   const char str[] = "http://www.tutorialspoint.com";
   const char ch = '.';
   char *ret;

   ret = strrchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
String after |.| is - |.com|


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
JavaScript: Check if array has an almost increasing sequence

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
The sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing.
For sequence = [1, 3, 2, 1], the output should be −
almostIncreasingSequence(sequence) = false.
There is no one element in this array that can be removed in order to get a strictly increasing sequence.
For sequence = [1, 3, 2], the output should be −
almostIncreasingSequence(sequence) = true.
We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].
Following is the code −
const arr1 = [3, 5, 67, 98, 3];
const arr2 = [4, 3, 5, 67, 98, 3];
const almostIncreasingSequence = sequence => {
   let removed = 0;
   let i = 0;
   let prev = -Infinity;
   while(removed < 2 && i < sequence.length) {
      if(sequence[i] > prev) {
         prev = sequence[i];
      }else{
         prev = Math.min(prev, sequence[i]);
         removed++;
      }
      i++;
   }
   return removed < 2;
};
console.log(almostIncreasingSequence(arr1));
console.log(almostIncreasingSequence(arr2));
This will produce the following output on console −
true
false
Using Extensions with Selenium & Python

We can use extensions with Selenium webdriver in Python. We can have multiple extensions of the Chrome browser while we manually open the browser and work on it.
However, while the Chrome browser is opened through Selenium webdriver, those extensions which are available to the local browser will not be present. To configure an extension, we have to obtain the .crx extension file of the extension.
Then we have to perform installation of the extension to the browser which is launched by Selenium. To get all the extensions available to the browser enter chrome://extensions on the browser address bar.
To get add an extension for example: Momentum, visit the link −
https://chrome.google.com/webstore/category/extensions and enter Momentum in the search box. Once the search results are displayed, click on the relevant option.
After clicking on the Momentum extension, the details of the extension gets displayed. Copy the URL of the extension as highlighted in the below image.
Now, navigate to the link: https://chrome−extension−downloader.com/ and paste the URL we have copied within the Download extension field.
The .crx file of the extension gets downloaded to our system. We should then save it in a desired location.
To add this extension to the Chrome browser, once it is launched by Selenium webdriver, we have to use the Options class. We shall create an object of this class and apply add_extension method on it.
The path of the .crx file of the extension that we want to add is passed as a parameter to that method. Finally, this information is passed to the webdriver object.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
op = Options()
#set .crx file path of extension
op.add_extension('C:\\Users\\Momentum_v0.92.2.crx')
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe",
options=op)
driver.maximize_window()
#launch browser
driver.get("https://www.tutorialspoint.com/index.htm")
Python Increment and Decrement Operators

In this article, we will learn about increment and decrement operators in Python 3.x. Or earlier. In other languages we have pre and post increment and decrement (++ --) operators.
In Python we don’t have any such operators . But we can implement these operators in the form as dicussed in example below.
x=786

x=x+1
print(x)

x+=1
print(x)

x=x-1
print(x)

x-=1
print(x)
787
788
787
786
Other languages have for loops which uses increment and decrement operators. Python offers for loop which has a range function having default increment value “1” set. We can also specify our increment count as a third argument in the range function
for i in range(0,5):
   print(i)

for i in range(0,5,2):
   print(i)
0
1
2
3
4
0
2
4
In this article, we learned how to use Increment and Decrement Operators in Python.
How to add a regression line to a plot in base R if intercept and slope are given?

To add a regression line to a plot in base R if intercept and slope are given, we can follow the below steps −
First of all, create two vectors and the scatterplot between them.
Then, use abline function to create the regression line with intercept and slope given by a and b respectively.
Use plot functions to create scatterplot between two random vectors x and y −
 Live Demo
> x<-round(rnorm(20),2)
> y<-round(rnorm(20),2)
> plot(x,y)
Using abline function to add the regression line to the scatterplot with given intercept a = 0.51 and slope = -1.05 −
 Live Demo
> x<-round(rnorm(20),2)
> y<-round(rnorm(20),2)
> plot(x,y)
> abline(a=0.51,b=-1.05)
Break statement in Scala - GeeksforGeeks

17 Jan, 2019
In Scala, we use a break statement to break the execution of the loop in the program. Scala programing language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop. Break method is used by importing scala.util.control.breaks._ package.
Flow Chart:
Syntax:
// import package
import scala.util.control._

// create a Breaks object 
val loop = new breaks;

// loop inside breakable
loop.breakable{

// Loop starts
for(..)
{
// code
loop.break
}
}

or
import scala.util.control.Breaks._
breakable 
{
 for(..)
{
 code..
 break
}
}
For example:
// Scala program to illustrate the // implementation of break  // Importing break packageimport scala.util.control.Breaks._object MainObject {      // Main methoddef main(args: Array[String]) {          // Here, breakable is used to prevent exception     breakable     {         for (a <- 1 to 10)         {            if (a == 6)                          // terminate the loop when                 // the value of a is equal to 6                break             else             println(a);        }    }}}
Output:
1
2
3
4
5
 Break in Nested loop: We can also use break method in nested loop.
For example:
// Scala program to illustrate the // implementation of break in nested loop  // Importing break packageimport scala.util.control._  object Test {      // Main methoddef main(args: Array[String]) {    var num1 = 0;    var num2 = 0;    val x = List(5, 10, 15);    val y = List(20, 25, 30);      val outloop = new Breaks;    val inloop = new Breaks;          // Here, breakable is used to     // prevent from exception    outloop.breakable     {         for (num1 <- x)         {                         // print list x            println(" " + num1);              inloop.breakable             {            for (num2 <- y)             {                          //print list y            println(" " + num2);              if (num2 == 25)             {                              // inloop is break when             // num2 is equal to 25            inloop.break;            }            }                  // Here, inloop breakable            }         }          // Here, outloop breakable    } }}
Output:
  5
 20
 25
 10
 20
 25
 15
 20
 25
Explanation: In the above example, the initial value of both num1 and num2 is 0. Now first outer for loop start and print 5 from the x list, then the inner for loop start its working and print 20, 25 from the y list, when the controls go to num2 == 25 condition, then the inner loop breaks. Similarly for 10 and 15.
Scala
Scala-Basics
Scala-Decision-Making
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
For Loop in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala | map() method
Scala | flatMap Method
Scala List filter() method with example
Scala | reduce() Function
String concatenation in Scala
Type Casting in Scala
Scala List contains() method with example
Scala String substring() method with example
How to get the size of PyGame Window? - GeeksforGeeks

02 Jun, 2021
In this article, we will learn How to get the size of a PyGame Window. 
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.
Installation:
This library can be installed using the below command:
pip install pygame 
Step-by-step Approach:
Import pygame.Initialize pygame.Form a screen by using pygame.display.set_mode() method.Get size of formed screen by using screen.get_size() method.Quit pygame.
Import pygame.
Initialize pygame.
Form a screen by using pygame.display.set_mode() method.
Get size of formed screen by using screen.get_size() method.
Quit pygame.
Below are some examples based on the above approach:
Example 1:
Python3
# import package pygameimport pygame # initialize pygamepygame.init() # Form screenscreen = pygame.display.set_mode() # get the default sizex, y = screen.get_size() # quit pygamepygame.display.quit() # view size (width x height)print(x, y)
Output :
1536 864
Example 2:
Python3
# import package pygameimport pygame # initialize pygamepygame.init() # Form screenscreen = pygame.display.set_mode((500, 500)) # get the sizex, y = screen.get_size() # quit pygamepygame.display.quit() # view size (width x height)print(x, y)
Output :
500 500
arorakashish0911
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
How to change file or directory permission in Linux/Unix?

We know that the Linux/Unix is a multiuser operating system files and directories are associated with permission so that only authorized users can access the files.
The chmod command is used to change the access permission of files or directories.
The general syntax of the chmod command is as follows −
chmod [OPTION]... [Mode]... [File]...
Syntax of chmod command is as followed, it contains some three parameters that will help to set or change the permission of the file.
We will discuss each parameter in detail so that you can have a better idea of using the chmod command.
A brief description of options available in the chmod command −
Mode can be represented in two different ways.
Numeric notation
Symbolic notation
In numeric notation, a three figures octal number (0-7) sequence is followed. Each digit holds Its own class. First digit for user Second digit for group and the last one is for others. If digits are out of range then it will be considered as zeros.
Symbolic notation is a combination of letters that specifies the permission. Some important letters are (u) for user (g) for group (o) for others and (a) for all the users.
Some arithmetic operators are used for certain permission.
“+” Plus, the operator will be used for adding the next permission to the existing one.
“- “Minus operator for removing.
“=” And equal means that it is the only permission is being used.
We can change the permission of a file and allow only the owner to read the file using the chmod command.
First, we will check permission of a file using the below command.
$ ls -l
Then we will change the permission of a file using the chmod command. We can provide permission numeric mode or symbolic mode.
Numeric notation –
$ chmod 400 file.txt
Or we can use the below command instead of numeric notation.
Symbolic notation –
$ chmod u + r hello.txt
As mentioned in the above tabular form, the option 200 allows the owner only to write into the file.
After executing the below command, only the owner of the file is allowed to modify it.
$ chmod 200 file.txt
To display more information about the chmod command, we use the --help option with the chmod command as shown below.
$ chmod --help
How to style multi-line conditions in 'if' statements in Python?

There are many ways you can style multiple if conditions. You don't need to use 4 spaces on your second conditional line. So you can use something like &minusl;
if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):
# Actual code
You can also start the conditions from the next line −
if (
   cond1 == 'val1' and cond2 == 'val2' and
   cond3 == 'val3' and cond4 == 'val4'
):
# Actual code
Or you can provide enough space between if and ( to accomodate the conditions in the same vertical column.
if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):
# Actual code
You can also do this without brackets, but note that PEP8 guidelines discourage this. For example,
if cond1 == 'val1' and cond2 == 'val2' and \
   cond3 == 'val3' and cond4 == 'val4':
# Actual code
MySQL - SQRT Function

MySQL SQRT function is used to find out the square root of any number. You can use SELECT statement to find out square root of any number as follows −
mysql>  select SQRT(16);
+----------+
| SQRT(16) |
+----------+
| 4.000000 |
+----------+
1 row in set (0.00 sec)
You are seeing float value here because internally MySQL will manipulate square root in float data type.
You can use SQRT function to find out square root of various records as well. To understand SQRT function in more detail, consider an employee_tbl table, which is having following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to calculate square root  of all the dialy_typing_pages, then you can do so by using the following command −
mysql> SELECT name, SQRT(daily_typing_pages)
   -> FROM employee_tbl;
+------+--------------------------+
| name | SQRT(daily_typing_pages) |
+------+--------------------------+
| John |         15.811388        |
| Ram  |         14.832397        |
| Jack |         13.038405        |
| Jack |         10.000000        |
| Jill |         14.832397        |
| Zara |         17.320508        |
| Zara |         18.708287        |
+------+--------------------------+
7 rows in set (0.00 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Print all k-sum paths in a binary tree in C++

In this problem, we are given a binary tree and a number K and we have to print all paths in the tree which have the sum of nodes in the path equal k.
Here, the path of the tree can start from any node of the tree and end at any node. The path should always direct from the root node to the leaf node. The values of the nodes of the tree can be positive, negative, or zero.
Let’s take an example to understand the problem −
K = 5
Output −
1 3 1
3 2
1 4
To solve this problem, we will treat each node as the root node of the tree and find the path from the temporary root to other nodes that sum values to K.
We store all nodes of the path in vector and check the sum value to be evaluated to k.
Program to show the implementation of the algorithm −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *left,*right;
   Node(int x){
      data = x;
      left = right = NULL;
   }
};
void printPath(const vector<int>& v, int i) {
   for (int j=i; j<v.size(); j++)
      cout<<v[j]<<"\t";
   cout<<"\n";
}
void findKSumPath(Node *root, vector<int>& path, int k) {
   if (!root)
      return;
   path.push_back(root->data);
   findKSumPath(root->left, path, k);
   findKSumPath(root->right, path, k);
   int f = 0;
   for (int j=path.size()-1; j>=0; j--){
      f += path[j];
      if (f == k)
         printPath(path, j);
   }
   path.pop_back();
}
int main() {
   Node *root = new Node(1);
   root->left = new Node(3);
   root->left->left = new Node(1);
   root->left->right = new Node(2);
   root->right = new Node(4);
   root->right->right = new Node(7);
   int k = 5;
   cout<<"Paths with sum "<<k<<" are :\n";
   vector<int> path;
   findKSumPath(root, path, k);
   return 0;
}
Paths with sum 5 are −
1 3 1
3 2
1 4
C++ String Library - c_str

It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
Following is the declaration for std::string::c_str.
const char* c_str() const;
const char* c_str() const noexcept;
const char* c_str() const noexcept;
none
It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
if an exception is thrown, there are no changes in the string.
In below example for std::string::c_str.
#include <iostream>
#include <cstring>
#include <string>

int main () {
   std::string str ("Please divide this sentance into parts");

   char * cstr = new char [str.length()+1];
   std::strcpy (cstr, str.c_str());

   char * p = std::strtok (cstr," ");
   while (p!=0) {
      std::cout << p << '\n';
      p = std::strtok(NULL," ");
   }

   delete[] cstr;
   return 0;
}
The sample output should be like this −
Please
divide
this
sentance
into
parts

 Print
 Add Notes
 Bookmark this page
How to stop Tkinter Frame from shrinking to fit its contents?

The sizing property of all the widgets in the Tkinter frame is by default set to the size of the widgets themselves. The frame container shrinks or grows automatically to fit the widgets inside it. To stop allowing the frame to shrink or grow the widget, we can use propagate(boolean) method with one of any pack or grid geometry manager. This method stops the frame from propagating the widgets to be resized.
There are two general ways we can define the propagate property,
pack_propagate (False) – If the Frame is defined using the Pack Geometry Manager.
pack_propagate (False) – If the Frame is defined using the Pack Geometry Manager.
grid_propagate (False) – If the Frame is defined using the Grid Geometry Manager.
grid_propagate (False) – If the Frame is defined using the Grid Geometry Manager.
In this example, we will create two entry widget inside a frame which don’t allow the widget to be shrink or fit.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

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

#Set the geometry of tkinter frame
win.geometry("750x250")

#Define a function to show a message
def submit():
   messagebox.showinfo("Success", "Submitted Successfully!")

#Creates top frame
frame1 = LabelFrame(win, width= 400, height= 180, bd=5)
frame1.pack()

#Stop the frame from propagating the widget to be shrink or fit
frame1.pack_propagate(False)

#Create an Entry widget in Frame1
entry1 = ttk.Entry(frame1, width= 40)
entry1.insert(INSERT,"Enter Your Name")
entry1.pack(pady=30)
entry2= ttk.Entry(frame1, width= 40)
entry2.insert(INSERT, "Enter Your Email")
entry2.pack()

#Creates bottom frame for button
frame2 = LabelFrame(win, width= 150, height=100)
frame2.pack()

#Create a Button to enable frame
button1 = ttk.Button(frame2, text="Submit", command= submit)
button1.pack()

win.mainloop()
Run the above code to display a window that contains two frames with widgets defined in it.
In the given output, the window contains a frame with entry widget that doesn’t shrink the widgets defined inside it.
How to Execute a .class File in Java?

02 Dec, 2020
A Java class file is a compiled java file. It is compiled by the Java compiler into bytecode to be executed by the Java Virtual Machine.
1. To compile your .java files, open Terminal (Mac) or Command Prompt (Windows).
2. Navigate to the folder your java file is at.
3. To compile, type
javac <javaFileName>
4. After hitting enter, .class files will appear in the same folder for each .java file.
5. To run the class file, it must have a main method, 
java <classname>
6. The result will be displayed in the Terminal or Command Prompt.
Example
Java
// Run a class file in java  import java.io.*;  class GFG {    public static void main(String[] args)    {          // prints GFG!        System.out.println("GFG!");    }}
GFG!
java-basics
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java