code-rag-bench/online-tutorials huggingface dataset:
How to create date object in Java?

You can create a Date object using the Date() constructor of java.util.Date constructor as shown in the following example. The object created using this constructor represents the current time.
Live Demo
import java.util.Date;
public class CreateDate {
   public static void main(String args[]) {      
      Date date = new Date();
      System.out.print(date);
   }
}
Thu Nov 02 15:43:01 IST 2018
Using the SimpleDateFormat class and the parse() method of this you can parse a date string in the required format and create a Date object representing the specified date.
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
   public static void main(String args[]) throws ParseException {  
       String date_string = "26-09-1989";
       //Instantiating the SimpleDateFormat class
       SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");      
       //Parsing the given String to Date object
       Date date = formatter.parse(date_string);      
       System.out.println("Date value: "+date);
   }
}
Date value: Tue Sep 26 00:00:00 IST 1989
A LocalDate object is similar to the date object except it represents the date without time zone, you can use this object instead of Date.
The now() method of this class returns a LocalDate object representing the current time
The of() method accepts the year, month and day values as parameters an returns the respective LocalDate object.
The parse() method accepts a date-string as a parameter and returns the LocalDate object5 representing the given date.
Live Demo
import java.time.LocalDate;
public class Test {
   public static void main(String args[]) {  
      LocalDate date1 = LocalDate.of(2014, 9, 11);
      System.out.println(date1);
      LocalDate date2 = LocalDate.parse("2007-12-03");
      System.out.println(date2);
      LocalDate date3 = LocalDate.now();
      System.out.println(date3);
   }
}
2014-09-11
2007-12-03
2020-11-05
How to add values in columns having same name and merge them in R?

To add values in columns having same name and merge them in R, we can follow the
below steps −
First of all, create a data frame.
Add column values that have same name and merge them by using cbind with
do.call.
Let's create a data frame as shown below −
df<-
data.frame(x=rpois(25,1),y=rpois(25,2),x=rpois(25,5),z=rpois(25,2),y=rpois(25,1),z=rpoi
s(25,5),check.names=FALSE)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
  x y x z y z
1 1 1 7 1 1 1
2 3 2 4 0 3 4
3 1 3 4 2 0 3
4 1 1 9 2 3 3
5 1 2 3 0 3 8
6 1 3 2 1 0 4
7 1 2 5 2 2 4
8 0 1 6 3 2 7
9 1 4 4 2 1 1
10 1 2 3 3 0 3
11 2 2 10 1 0 14
12 2 2 2 2 0 1
13 0 3 5 3 0 6
14 2 1 3 2 0 5
15 0 2 5 6 1 4
16 1 2 3 0 0 5
17 0 2 7 2 2 11
18 3 2 4 1 2 5
19 0 7 5 1 0 10
20 0 3 3 1 0 6
21 1 1 5 7 5 6
22 1 0 5 3 2 5
23 3 3 3 3 0 2
24 2 0 6 4 1 7
25 0 7 1 2 1 4
Use do.call function with cbind function to add column values with colSums function as shown below −
df<-
data.frame(x=rpois(25,1),y=rpois(25,2),x=rpois(25,5),z=rpois(25,2),y=rpois(25,1),z=rpoi
s(25,5),check.names=FALSE)
Merged_df<-as.data.frame(do.call(cbind,
by(t(df),INDICES=names(df),FUN=colSums)))
Merged_df
   x y z
V1 8 2 2
V2 7 5 4
V3 5 3 5
V4 10 4 5
V5 4 5 8
V6 3 3 5
V7 6 4 6
V8 6 3 10
V9 5 5 3
V10 4 2 6
V11 12 2 15
V12 4 2 3
V13 5 3 9
V14 5 1 7
V15 5 3 10
V16 4 2 5
V17 7 4 13
V18 7 4 6
V19 5 7 11
V20 3 3 7
V21 6 6 13
V22 6 2 8
V23 6 3 5
V24 8 1 11
V25 1 8 6
How to create a Borderless Window in Java?

To create a borderless window in Java, do not decorate the window. The following is an example to create a BorderLess Window −
package my;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JWindow frame = new JWindow();
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label2 = new JLabel("Age", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField emailId = new JTextField(20);
      JTextField rank = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(rank);
      frame.add(passwd);
      Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
      int width = 500;
      int height = 200;
      frame.setBounds(center.x - width / 2, center.y - height / 2, width, height);
      frame.setVisible(true);
   }
}
Disable images in Selenium Google ChromeDriver.

We can disable images in Selenium in chromedriver. The images are sometimes disabled so that page load takes less time and execution is quick. In Chrome, we can do this with the help of the prefs setting.
prefs.put("profile.managed_default_content_settings.images", 2);
Let’s us make an attempt to disable all image from the below page −
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.HashMap;
import java.util.Map;
public class ChromeDisableImg {
   public static void main(String[] args) throws IOException {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      Map<String, Object> prefs = new HashMap<String, Object>();
      // browser setting to disable image
      prefs.put("profile.managed_default_content_settings.images", 2);
      //adding capabilities to browser
      ChromeOptions op = new ChromeOptions();
      op.setExperimentalOption("prefs", prefs);
      // putting desired capabilities to browser
      WebDriver driver= new ChromeDriver(op);
      driver.get("https://www.tutorialspoint.com/index.htm/");
   }
}
How to create a bar graph using ggplot2 without horizontal gridlines and Y-axes labels in R?

A bar graph plotted with ggplot function of ggplot2 shows horizontal and vertical gridlines. If we are interested only in the bar heights then we might prefer to remove the horizontal gridlines. In this way, we can have X-axis that helps us to look at the different categories we have in our variable of interest and get rid of the unnecessary information. This can be done by setting breaks argument to NULL in scale_y_discrete function.
Consider the below data frame −
> x<-1:5
> y<-c(20,18,10,15,17)
> df<-data.frame(x,y)
Loading ggplot2 package −
> library(ggplot2)
Creating the plot with all gridlines −
> ggplot(df,aes(x,y))+
+ geom_bar(stat='identity')
Creating the plot without horizontal gridlines −
> ggplot(df,aes(x,y))+
+ geom_bar(stat='identity')+
+ scale_y_discrete(breaks = NULL)
Dart Programming - Collection Queue

A Queue is a collection that can be manipulated at both ends. Queues are useful when you want to build a first-in, first-out collection. Simply put, a queue inserts data from one end and deletes from another end. The values are removed / read in the order of their insertion.
Identifier = new Queue()

The add() function can be used to insert values to the queue. This function inserts the value specified to the end of the queue.  The following example illustrates the same.
import 'dart:collection'; 
void main() { 
   Queue queue = new Queue(); 
   print("Default implementation ${queue.runtimeType}"); 
   queue.add(10); 
   queue.add(20); 
   queue.add(30); 
   queue.add(40); 
   
   for(var no in queue){ 
      print(no); 
   } 
}      
It should produce the following output −
Default implementation ListQueue
10 
20 
30 
40 

The addAll() function enables adding multiple values to a queue, all at once. This function takes an iterable list of values.
import 'dart:collection'; 
void main() { 
   Queue queue = new Queue(); 
   print("Default implementation ${queue.runtimeType}"); 
   queue.addAll([10,12,13,14]); 
   for(var no in queue){ 
      print(no); 
   } 
}
It should produce the following output −
Default implementation ListQueue 
10 
12 
13 
14 

The addFirst() method adds the specified value to the beginning of the queue. This function is passed an object that represents the value to be added. The addLast() function adds the specified object to the end of the queue.
The following example shows how you can add a value at the beginning of a Queue using the addFirst() method −
import 'dart:collection'; 
void main() { 
   Queue numQ = new Queue(); 
   numQ.addAll([100,200,300]); 
   print("Printing Q.. ${numQ}");
   numQ.addFirst(400); 
   print("Printing Q.. ${numQ}"); 
}   
It should produce the following output −
Printing Q.. {100, 200, 300} 
Printing Q.. {400, 100, 200, 300}

The following example shows how you can add a value at the beginning of a Queue using the addLast() method −
import 'dart:collection'; 
void main() { 
   Queue numQ = new Queue(); 
   numQ.addAll([100,200,300]); 
   print("Printing Q.. ${numQ}");  
   numQ.addLast(400); 
   print("Printing Q.. ${numQ}"); 
} 
It should produce the following output −
Printing Q.. {100, 200, 300} 
Printing Q.. {100, 200, 300, 400} 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
tee command in Linux with examples - GeeksforGeeks

19 Feb, 2021
tee command reads the standard input and writes it to both the standard output and one or more files. The command is named after the T-splitter used in plumbing. It basically breaks the output of a program so that it can be both displayed and saved in a file. It does both the tasks simultaneously, copies the result into the specified files or variables and also display the result.
SYNTAX:
tee [OPTION]... [FILE]...

Options :1.-a Option : It basically do not overwrite the file but append to the given file.Suppose we have file1.txt
Input: geek
       for
       geeks

and file2.txt
Input:geeks
      for
      geeks

SYNTAX :
geek@HP:~$ wc -l file1.txt|tee -a file2.txt

OUTPUT :
3 file1.txt

geek@HP:~$cat file2.txt
OUTPUT:
      geeks
      for
      geeks
      3 file1.txt

2.–help Option : It gives the help message and exit.SYNTAX :
geek@HP:~$ tee --help

3.–version Option : It gives the version information and exit.SYNTAX :
geek@HP:~$ tee --version

Application
Suppose we want to count number of characters in our file and also want to save the output to new text file so to do both activities at same time, we use tee command.
geek@HP:~$ wc -l file1.txt| tee file2.txt
OUTPUT:
geek@HP:~$15 file1.txt

Here we have file1 with 15 characters, so the output will be 15 and the output will be stored to file2. In order to check the output we use :
geek@HP:~$ cat file2.txt
OUTPUT:
geek@HP:~$15 file1.txt

YouTubeGeeksforGeeks500K subscribersLinux Tutorials | Pipe and tee | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:11 / 3:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=19mmVar-s5Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-Shell-Commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
curl command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Tail command in Linux with examples
Thread functions in C/C++
How can we add multiple sub-panels to the main panel in Java?

A JPanel is a subclass of JComponent class and it is an invisible component in Java. The FlowLayout is a default layout for a JPanel. We can add most of the components like buttons, text fields, labels, tables, lists, trees, etc. to a JPanel.
We can also add multiple sub-panels to the main panel using the add() method of Container class.
public Component add(Component comp)
import java.awt.*;
import javax.swing.*;
public class MultiPanelTest extends JFrame {
   private JPanel mainPanel, subPanel1, subPanel2;
   public MultiPanelTest() {
      setTitle("MultiPanel Test");
      mainPanel = new JPanel(); // main panel
      mainPanel.setLayout(new GridLayout(3, 1));
      mainPanel.add(new JLabel("Main Panel", SwingConstants.CENTER));
      mainPanel.setBackground(Color.white);
      mainPanel.setBorder(BorderFactory.createLineBorder(Color.black, 1));
      subPanel1 = new JPanel(); // sub-panel 1
      subPanel1.add(new JLabel("Panel One", SwingConstants.CENTER));
      subPanel1.setBackground(Color.red);
      subPanel2 = new JPanel(); // sub-panel 2
      subPanel2.setBackground(Color.blue);
      subPanel2.add(new JLabel("Panel Two", SwingConstants.CENTER));
      mainPanel.add(subPanel1);
      mainPanel.add(subPanel2);
      add(mainPanel);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new MultiPanelTest();
   }
}
Python - Remove Negative Elements in List - GeeksforGeeks

03 Jul, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to remove all the negative elements from list. This kind of problem can have application in many domains such as school programming and web development. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [6, 4, 3]Output : [6, 4, 3]
Input : test_list = [-6, -4]Output : []
Method #1 : Using list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of removing negative elements by iteration in one liner using list comprehension
# Python3 code to demonstrate working of # Remove Negative Elements in List# Using list comprehension  # initializing listtest_list = [5, 6, -3, -8, 9, 11, -12, 2]   # printing original listprint("The original list is : " + str(test_list))  # Remove Negative Elements in List# Using list comprehensionres = [ele for ele in test_list if ele > 0]  # printing result print("List after filtering : " + str(res))
The original list is : [5, 6, -3, -8, 9, 11, -12, 2]
List after filtering : [5, 6, 9, 11, 2]

 
Method #2 : Using filter() + lambdaThe combination of above functions can also offer an alternative to this problem. In this, we extend logic of retaining positive formed using lambda function and extended using filter().
# Python3 code to demonstrate working of # Remove Negative Elements in List# Using filter() + lambda  # initializing listtest_list = [5, 6, -3, -8, 9, 11, -12, 2]   # printing original listprint("The original list is : " + str(test_list))  # Remove Negative Elements in List# Using filter() + lambdares = list(filter(lambda x : x > 0, test_list))  # printing result print("List after filtering : " + str(res))
The original list is : [5, 6, -3, -8, 9, 11, -12, 2]
List after filtering : [5, 6, 9, 11, 2]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
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 print without newline in Python?
How to check if a string contains only decimal characters?

There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. You can call it as follows:
>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
But this would fail for floating-point numbers. We can use the following method for those numbers:
def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False
isfloat('12.345')
isfloat('12a')
This will give the output:
True
False
You can also use regexes for the same result. For matching decimals, we can call the re.match(regex, string) using the regex: "^\d+?\.\d+?$". For example,
>>> bool(re.match("^\d+?\.\d+?$", '123abc'))
False
>>> bool(re.match("^\d+?\.\d+?$", '12.345'))
True
How to find out all the indexes for a DB2 table TAB1?

To find out all the indexes built on the DB2 table TAB1 we can use the DB2 system table SYSIBM.SYSINDEXES. The SYSINDEXES database has one row for every index present in DB2. We can find indexes built on a particular table using the below SQL query.
SELECT NAME, UNIQUERULE, CLUSTERING
   FROM SYSIBM.SYSINDEXES WHERE TBNAME=’TAB1’
The column UNIQUERULE in the SELECT statement returns ‘P’ for primary index and ‘U’ for alternate index. The CLUSTERING column will be returned as ‘YES’ for clustered index and ‘NO’ for non-clustered index.
C# Program to access first element in a Dictionary

The following is our Dictionary with some elements −
Dictionary<int, string> d = new Dictionary<int, string>() {
   {1,"Electronics"},
   {2, "Clothing"},
   {3,"Toys"},
   {4,"Footwear"},
   {5, "Accessories"}
};
Now to display the first element, set the key like this.
d[1];
The above displays the first element.
 Live Demo
using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary<int, string> d = new Dictionary<int, string>() {
         {1,"Electronics"},
         {2, "Clothing"},
         {3,"Toys"},
         {4,"Footwear"},
         {5, "Accessories"}
      };
      foreach (KeyValuePair<int, string> ele in d) {
         Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
      }
      Console.WriteLine("First element: "+d[1]);
   }
}
Key = 1, Value = Electronics
Key = 2, Value = Clothing
Key = 3, Value = Toys
Key = 4, Value = Footwear
Key = 5, Value = Accessories
First element: Electronics
What is multithreading in C#?

In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread.
When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread.
The following is an example showing how to create a thread in C# −
using System;
using System.Threading;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Thread th = Thread.CurrentThread;
         th.Name = "MainThread";
         Console.WriteLine("This is {0}", th.Name);
         Console.ReadKey();
      }
   }
}
Here is another example showing how to manage threads in C# −
 Live Demo
using System;
using System.Threading;

namespace MultithreadingApplication {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         Console.WriteLine("Child thread starts");
         // the thread is paused for 5000 milliseconds
         int sleepfor = 5000;
         Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
         Thread.Sleep(sleepfor);
         Console.WriteLine("Child thread resumes");
      }

      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");

         Thread childThread = new Thread(childref);
         childThread.Start();
         Console.ReadKey();
      }
   }
}
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes
Count elements smaller than or equal to x in a sorted matrix in C++

We are given a matrix of size n x n, an integer variable x, and also, the elements in a matrix are placed in sorted order and the task is to calculate the count of those elements that are equal to or less than x.
Input −
matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {6, 7, 8}} and X = 4
Output −
count is 4
Explanation − we have to match our matrix data with the value x, so the elements less than or equals to x i.e. 4 are 1, 2, 3, 4. So the count is 4.
Input −
matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {6, 7, 8}} and X = 0
Output −
count is 0
Explanation − we have to match our matrix data with the value x, so there is no element that is less than or equals to x. So the count is 0.
Input the size of the matrix and then create the matrix of size nxn
Input the size of the matrix and then create the matrix of size nxn
Start the loop, I from 0 to row size
Start the loop, I from 0 to row size
Inside the loop, I, start another loop j from 0 to column size
Inside the loop, I, start another loop j from 0 to column size
Now, check if matrix[i][j] = x, IF yes then increase the count by 1 Else ignore the
condition
Now, check if matrix[i][j] = x, IF yes then increase the count by 1 Else ignore the
condition
Return the total count
Return the total count
Print the result.
Print the result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
#define size 3
//function to count the total elements
int count(int matrix[size][size], int x){
   int count=0;
   //traversing the matrix row-wise
   for(int i = 0 ;i<size; i++){
      for (int j = 0; j<size ; j++){
         //check if value of matrix is less than or
         //equals to the x
         if(matrix[i][j]<= x){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int matrix[size][size] ={
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
   };
   int x = 5;
   cout<<"Count of elements smaller than or equal to x in a sorted matrix is: "<<count(matrix,x);
   return 0;
}
If we run the above code we will get the following output −
Count of elements smaller than or equal to x in a sorted matrix is: 5
How to simulate a keypress event in JavaScript?

To simulate a key press event, use event handlers. You can try to run the following code to simulate a key press event
Live Demo
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         jQuery(document).ready(function($) {
            $('body').keypress(function(e) {
               alert(String.fromCharCode(e.which));
            });
         });
         jQuery.fn.simulateKeyPress = function(character) {
            jQuery(this).trigger({
               type: 'keypress',
               which: character.charCodeAt(0)
            });
         };
         setTimeout(function() {
            $('body').simulateKeyPress('z');
         }, 2000);
      </script>
   </head>
   <body>
      <p>press any key</p>
   </body>
</html>
Count all sub-sequences having product <= K – Recursive approach in C++

In this tutorial, we will be discussing a program to find the number of sub-sequences having product <= k.
For this we will be provided with an array and a value K. Our task is to find the number of sub sequences having their product as K.
 Live Demo
#include <bits/stdc++.h>
#define ll long long
using namespace std;
//keeping count of discarded sub sequences
ll discard_count = 0;
ll power(ll a, ll n){
   if (n == 0)
      return 1;
   ll p = power(a, n / 2);
   p = p * p;
   if (n & 1)
      p = p * a;
   return p;
}
//recursive approach to count
//discarded sub sequences
void solve(int i, int n, float sum, float k,
float* a, float* prefix){
   if (sum > k) {
      discard_count += power(2, n - i);
      return;
   }
   if (i == n)
      return;
      float rem = prefix[n - 1] - prefix[i];
   if (sum + a[i] + rem > k)
      solve(i + 1, n, sum + a[i], k, a, prefix);
   if (sum + rem > k)
      solve(i + 1, n, sum, k, a, prefix);
}
int countSubsequences(const int* arr,
int n, ll K){
   float sum = 0.0;
   float k = log2(K);
   float prefix[n], a[n];
   for (int i = 0; i < n; i++) {
      a[i] = log2(arr[i]);
      sum += a[i];
   }
   prefix[0] = a[0];
   for (int i = 1; i < n; i++) {
      prefix[i] = prefix[i - 1] + a[i];
   }
   ll total = power(2, n) - 1;
   if (sum <= k) {
      return total;
   }
   solve(0, n, 0.0, k, a, prefix);
   return total - discard_count;
}
int main() {
   int arr[] = { 4, 8, 7, 2 };
   int n = sizeof(arr) / sizeof(arr[0]);
   ll k = 50;
   cout << countSubsequences(arr, n, k);
   return 0;
}
9
How to solve the simultaneous linear equations in R?

The data in simultaneous equations can be read as matrix and then we can solve those matrices to find the value of the variables. For example, if we have three equations as −
x + y + z = 6
3x + 2y + 4z = 9
2x + 2y – 6z = 3
then we will convert these equations into matrices and solve them using solve function in R.
 Live Demo
> A<-matrix(c(1,1,2,3,2,4,2,3,-6),nrow=3,byrow=TRUE)
> A
   [,1] [,2] [,3]
[1,] 1    1    2
[2,] 3    2    4
[3,] 2    3    -6
 Live Demo
> b<-matrix(c(6,9,3))
> b
[,1]
[1,] 6
[2,] 9
[3,] 3
> solve(A,b)
[,1]
[1,] -3.0
[2,] 6.0
[3,] 1.5
Hence, the answer is x = -3, y = 6, and z = 1.5.
4x - 3y + x = -10
2x + y + 3z = 0
-1x + 2y - 5z = 17
 Live Demo
> A<-matrix(c(4,-3,1,2,1,3,-1,2,-5),nrow=3,byrow=TRUE)
> A
   [,1] [,2] [,3]
[1,] 4    -3    1
[2,] 2    1     3
[3,] -1    2    -5
Live Demo
> b<-matrix(c(-10,0,17))
> b
[,1]
[1,] -10
[2,] 0
[3,] 17
> solve(A,b)
[,1]
[1,] 1
[2,] 4
[3,] -2
4x – 2y + 3z = 1
x + 3y – 4z = -7
3x + y + 2z = 5
Live Demo
> A<-matrix(c(4,-2,3,1,3,-4,3,1,2),nrow=3,byrow=TRUE)
> A
   [,1] [,2] [,3]
[1,] 4    -2    3
[2,] 1    3    -4
[3,] 3    1    2
 Live Demo
> b<-matrix(c(1,-7,5))
> b
[,1]
[1,] 1
[2,] -7
[3,] 5
> solve(A,b)
[,1]
[1,] -1
[2,] 2
[3,] 3
x + 2y – 3z + 4t = 12
2x + 2y – 2z + 3t = 10
y + z = -1
x - y + z – 2t = -4
Live Demo
> A<-matrix(c(1,2,-3,4,2,2,-2,3,0,1,1,0,1,-1,1,-2),nrow=4,byrow=TRUE)
> A
   [,1] [,2] [,3] [,4]
[1,] 1    2    -3    4
[2,] 2    2    -2    3
[3,] 0    1    1    0
[4,] 1    -1    1    -2
 Live Demo
> b<-matrix(c(12,10,-1,-4))
> b
[,1]
[1,] 12
[2,] 10
[3,] -1
[4,] -4
> solve(A,b)
[,1]
[1,] 1
[2,] 0
[3,] -1
[4,] 2
How to write a simple calculator program using C language?

Begin by writing the C code to create a simple calculator. Then, follow the algorithm given below to write a C program.
Step 1: Declare variables
Step 2: Enter any operator at runtime
Step 3: Enter any two integer values at runtime
Step 4: Apply switch case to select the operator:
        // case '+': result = num1 + num2;
               break;
           case '-': result = num1 - num2;
               break;
           case '*': result = num1 * num2;
               break;
           case '/': result = num1 / num2;
               break;
           default: printf("\n Invalid Operator ");
Step 5: Print the result
Following is the C program for calculator by using the Switch Case −
 Live Demo
#include <stdio.h>
int main(){
   char Operator;
   float num1, num2, result = 0;
   printf("\n Enter any one operator like +, -, *, / : ");
   scanf("%c", &Operator);
   printf("Enter the values of Operands num1 and num2 \n : ");
   scanf("%f%f", &num1, &num2);
   switch(Operator){
      case '+': result = num1 + num2;
         break;
      case '-': result = num1 - num2;
         break;
      case '*': result = num1 * num2;
         break;
      case '/': result = num1 / num2;
         break;
      default: printf("\n Invalid Operator ");
   }
   printf("The value = %f", result);
   return 0;
}
When the above program is executed, it produces the following result −
Enter any one operator: +
Enter values of Operands num1 and num2:
23
45
The value = 68.000000
How to reuse plots in Matplotlib?

To reuse plots in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Plot a line with some input lists.
To reuse the plot, update y data and the linewidth of the plot
To display the figure, use show() method.
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

line, = plt.plot([1, 3], [3, 4], label="line plot", color='red', lw=0.5)

line.set_ydata([3.5])
line.set_linewidth(4)

plt.show()
LESS - Lighten

It lightens the color in the element. It has the following parameters −
color − It represents the color object.
color − It represents the color object.
amount − It contains percentage between 0 - 100%.
amount − It contains percentage between 0 - 100%.
method − It is an optional parameter which is used for adjustment to be relative to current value by setting it to relative.
method − It is an optional parameter which is used for adjustment to be relative to current value by setting it to relative.
The following example demonstrates the use of lighten color operation in the LESS file −
<html>
   <head>
      <title>Lighten</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css"/>
   </head>

   <body>
      <h2>Example of Lighten Color Operation</h2>
      <div class = "myclass1">
         <p>color :<br> #426105</p>
      </div><br>

      <div class = "myclass2">
         <p>result :<br> #639108</p>
      </div>
   </body>
</html>
Next, create the style.less file.
.myclass1 {
   height:100px;
   width:100px;
   padding: 30px 0px 0px 25px;
   background-color: hsl(80, 90%, 20%);
   color:white;
}

.myclass2 {
   height:100px;
   width:100px;
   padding: 30px 0px 0px 25px;
   background-color: lighten(hsl(80, 90%, 20%), 10%);
   color:white;
}
You can compile the style.less 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 −
.myclass1 {
   height: 100px;
   width: 100px;
   padding: 30px 0px 0px 25px;
   background-color: #426105;
   color: white;
}

.myclass2 {
   height: 100px;
   width: 100px;
   padding: 30px 0px 0px 25px;
   background-color: #639108;
   color: white;
}
Follow these steps to see how the above code works −
Save the above html code in the lighten.html file.
Save the above html code in the lighten.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
JavaScript | Object.isExtensible() Method - GeeksforGeeks

17 Sep, 2021
The Object.preventExtensions() method in JavaScript is standard built-in objects which checks whether an object is extensible or not.Syntax:  
Object.isExtensible( obj )
Parameters: This method accepts single parameter as mentioned above and described below:  
obj: This parameter holds the object which which should be checked for extensiblity.
Return value: This method returns a Boolean value indicating if the given object is extensible or not.Below examples illustrate the Object.isExtensible() Method in JavaScript:Example 1:  
javascript
const geeks1 = {};console.log(Object.isExtensible(geeks1));Object.preventExtensions(geeks1);console.log(Object.isExtensible(geeks1)); const geeks2 = {}; Object.preventExtensions(geeks2); console.log(     Object.isExtensible(geeks2) ); 
Output:  
true
false
false
Example 2:  
javascript
var geeks1 = {};document.writeln(Object.isExtensible(geeks1));document.writeln("<br>");document.writeln(Object.preventExtensions(geeks1));document.writeln("<br>");document.writeln(Object.isExtensible(geeks1));document.writeln("<br>"); var geeks2 = Object.seal({});document.writeln(Object.isExtensible(geeks2));document.writeln("<br>"); var geeks3 = Object.freeze({});document.writeln(Object.isExtensible(geeks3));
Output:  
true
[object Object]
false
false
false
Supported Browsers: The browsers supported by Object.isExtensible() method are listed below: 
Google Chrome 6 and above
Edge 12 and above
Firefox 4 and above
Internet Explorer 9
Opera 12 and above
Safari 5.1 and above
 
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Pascal - Constants

A constant is an entity that remains unchanged during program execution. Pascal allows only constants of the following types to be declared −
Ordinal types
Set types
Pointer types (but the only allowed value is Nil).
Real types
Char
String
Syntax for declaring constants is as follows −
const
identifier = constant_value;
The following table provides examples of some valid constant declarations −
Real type constant
Ordinal(Integer)type constant
valid_age = 21;
Set type constant
Vowels = set of (A,E,I,O,U);
Pointer type constant
P = NIL;
e = 2.7182818;
velocity_light = 3.0E+10;
Character type constant
Operator = '+';
String type constant
president = 'Johnny Depp';
The following example illustrates the concept −
program const_circle (input,output);
const
PI = 3.141592654;

var
r, d, c : real;   {variable declaration: radius, dia, circumference}

begin
   writeln('Enter the radius of the circle');
   readln(r);
   
   d := 2 * r;
   c :=  PI * d;
   writeln('The circumference of the circle is ',c:7:2);
end.
When the above code is compiled and executed, it produces the following result −
Enter the radius of the circle
23
The circumference of the circle is 144.51

Observe the formatting in the output statement of the program. The variable c is to be formatted with total number of digits 7 and 2 digits after the decimal sign. Pascal allows such output formatting with the numerical variables.

    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
MySQL Tryit Editor v1.0

SELECT LOCATE("3", "W3Schools.com") AS MatchPosition;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Sort array of points by ascending distance from a given point JavaScript

Let’s say, we have an array of objects with each object having exactly two properties, x and y
that represent the coordinates of a point. We have to write a function that takes in this array and
an object with x and y coordinates of a point and we have to sort the points (objects) in the array
according to the distance from the given point (nearest to farthest).
It is a mathematical formula that states that the shortest distance between two points (x1, y1)
and (x2, y2) in a two-dimensional plane is given by −
S=((x2−x1)2+(y2−y1)2)
We will be using this formula to calculate the distance of each point from the given point and
sort them according to that.
const coordinates =
[{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}];
const distance = (coor1, coor2) => {
   const x = coor2.x - coor1.x;
   const y = coor2.y - coor1.y;
   return Math.sqrt((x*x) + (y*y));
};
const sortByDistance = (coordinates, point) => {
   const sorter = (a, b) => distance(a, point) - distance(b, point);
   coordinates.sort(sorter);
};
sortByDistance(coordinates, {x: 5, y: 4});
console.log(coordinates);
The output in the console will be −
[
   { x: 6, y: 2 },
   { x: 2, y: 6 },
   { x: 7, y: 10 },
   { x: 11, y: 6 },
   { x: 14, y: 10 }
]
And this is in fact the correct order as (6, 2) is nearest to (5,4), then comes (2, 6) then (7, 10)
and so on.
Instruction type PUSH rp in 8085 Microprocessor

In 8085 Instruction set, PUSH rp instruction stores contents of register pair rp by pushing it into two locations above the top of the stack. rp stands for one of the following register pairs.
rp = BC, DE, HL, or PSW

As rp can have any of the four values, there are four opcodes for this type of instruction. It occupies only 1-Byte in memory.
In the above mention Opcodes, 2-bits are occupied to mention the register pair. 2-bits can have 4 combinations. So 4 register pairs can be mentioned with POP. As mentioned earlier, they are BC, DE, HL and AF or PSW.
Note with LXI instruction, we are having 4 possible register pairs can be used i.e. BC, DE, HL and SP. So at the same time we can’t have SP and PSW applicable with the same instruction.
Let us consider PUSH B as an example instruction of this category. It is a 1-Byte instruction.
The result of execution of this instruction is shown below with an example.
(BC)
(SP)
(3FFFH)
(3FFEH)
The timing diagram against this instruction PUSH B execution is as follows −
Summary − So this instruction PUSH B requires 1-Byte, 3-Machine Cycles (Opcode Fetch, Memory Write, Memory Write) and 12 T-States for execution as shown in the timing diagram.
How to plot single data with two Y-axes (two units) in Matplotlib?

To plot single data with two Y-Axes (Two units) in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create speed and acceleration data points using numpy.
Add a subplot to the current figure.
Plot speed data points using plot() method.
Create a twin Axes sharing the X-axis.
Plot acceleration data point using plot() method.
Place a legend on the figure.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

speed = np.array([3, 1, 2, 0, 5])
acceleration = np.array([6, 5, 7, 1, 5])

ax1 = plt.subplot()
l1, = ax1.plot(speed, color='red')
ax2 = ax1.twinx()
l2, = ax2.plot(acceleration, color='orange')

plt.legend([l1, l2], ["speed", "acceleration"])

plt.show()
strdup() and strdndup() in C/C++


The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string.
Here is the syntax of strdup() in C language,
char *strdup(const char *string);
Here is an example of strdup() in C language,
 Live Demo
#include <stdio.h>
#include<string.h>
int main() {
   char *str = "Helloworld";
   char *result;
   result = strdup(str);
   printf("The string : %s", result);
   return 0;
}
The string : Helloworld
The function strndup works similar to the function strndup(). This function duplicates the string at most size bytes i.e. the given size in the function. It also returns a pointer to null-terminated byte string.
Here is the syntax of strndup() in C language,
char *strndup(const char *string , size_t size);
Here is an example of strndup() in C language,
 Live Demo
#include <stdio.h>
#include<string.h>
int main() {
   char *str = "Helloworld";
   char *result;
   result = strndup(str, 3);
   printf("The string : %s", result);
   return 0;
}
The string : Hel
Google Guice - Provider Class

As @provides method becomes more complex, this method can be moved to separate classes using Provider interface.
class SpellCheckerProvider implements Provider<SpellChecker> {
   @Override
   public SpellChecker get() {
      String dbUrl = "jdbc:mysql://localhost:5326/emp";
      String user = "user";
      int timeout = 100;
      SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
      return SpellChecker;
   } 
}
Next, you have to map the provider to type.
bind(SpellChecker.class).toProvider(SpellCheckerProvider.class);

See the complete example below.
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck();
   } 
}
class TextEditor {
   private SpellChecker spellChecker;
   
   @Inject
   public TextEditor( SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
   public void makeSpellCheck() {
      spellChecker.checkSpelling();
   } 
}

//Binding Module
class TextEditorModule extends AbstractModule {
   @Override
   
   protected void configure() {
      bind(SpellChecker.class).toProvider(SpellCheckerProvider.class);
   } 
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   private String dbUrl;
   private String user;
   private Integer timeout;

   @Inject
   public SpellCheckerImpl(String dbUrl, 
      String user, 
      Integer timeout) {
      this.dbUrl = dbUrl;
      this.user = user;
      this.timeout = timeout;
   } 
   @Override
   public void checkSpelling() { 
      System.out.println("Inside checkSpelling." );
      System.out.println(dbUrl);
      System.out.println(user);
      System.out.println(timeout);
   }
}
class SpellCheckerProvider implements Provider<SpellChecker> {
   @Override
   
   public SpellChecker get() {
      String dbUrl = "jdbc:mysql://localhost:5326/emp";
      String user = "user";
      int timeout = 100;

      SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
      return SpellChecker;
   }
}
Now, compile and run the file. You can see the following output −
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
user
100


    27 Lectures 
     1.5 hours 

 Lemuel Ogbunude
 Print
 Add Notes
 Bookmark this page
C program to perform union operation on two arrays

A union is a special data type available in C programming language that allows to store different data types in the same memory location. Unions provide an efficient way of using the same memory location for multiple-purpose.
If array 1 = { 1,2,3,4,6}
    Array 2 = {1,2,5,6,7}
Then, union of array1 and array 2 is
Array1 U array 2 = {1,2,3,4,6} U {1,2,5,6,7}
                              = {1,2,3,4,5,6,7}
Set of all elements without repetition is called union.
The logic for union is as follows −
for(i=0;i<size1;i++){
   uni[j]=a[i];
   j++;
}
for(i=0;i<size2;i++){
   uni[j]=b[i];
   j++;
}
The logic for removing repeated elements is as follows −
int removerepeated(int size,int a[]){
   int i,j,k;
   for(i=0;i<size;i++){
      for(j=i+1;j<size;){
         if(a[i]==a[j]){
            for(k=j;k<size;k++){
               a[k]=a[k+1];
            }
            size--;
         }else{
            j++;
         }
      }
   }
   return(size);
}
Following is the C program to perform union operation on two arrays −
 Live Demo
#include<stdio.h>
int removerepeated(int size,int a[]);
void sort(int size,int a[]);
main(){
   int i,size1,size2,size,j=0,k;
   printf("Enter size of an array1\n");
   scanf("%d",&size1);
   printf("Enter size of an array2\n");
   scanf("%d",&size2);
   int a[size1],b[size2],uni[size1+size2];
   printf("Enter numbers for array 1\n");
   for(i=0;i<size1;i++){
      scanf("%d",&a[i]);
   }
   printf("Enter numbers for array 2\n");
   for(i=0;i<size2;i++){
      scanf("%d",&b[i]);
   }
   //union start
   for(i=0;i<size1;i++){
      uni[j]=a[i];
      j++;
   }
   for(i=0;i<size2;i++){
      uni[j]=b[i];
      j++;
   }
   //Sorting
   sort(size1+size2,uni);
   //Remove repeated elements
   size=removerepeated(size1+size2,uni);
   printf("Array afetr Union \n");
   for(i=0;i<size;i++){
      printf("%d\n",uni[i]);
   }
   //Sorting
}
int removerepeated(int size,int a[]){
   int i,j,k;
   for(i=0;i<size;i++){
      for(j=i+1;j<size;){
         if(a[i]==a[j]){
            for(k=j;k<size;k++){
               a[k]=a[k+1];
            }
            size--;
         }else{
            j++;
         }
      }
   }
   return(size);
}
void sort(int size,int a[]){
   int i,j,temp;
   for(i=0;i<size;i++){
      for(j=i+1;j<size;j++){
         if(a[i]>a[j]){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
         }
      }
   }
}
When the above program is executed, it produces the following result −
Enter size of an array1
4
Enter size of an array2
3
Enter numbers for array 1
1
2
3
4
Enter numbers for array 2
3
5
6
Array after Union
1
2
3
4
5
6
JavaScript - Math sqrt Method

This method returns the square root of a number. If the value of a number is negative, sqrt returns NaN.
Its syntax is as follows −
Math.sqrt( x ) ;

x − A number
Returns the square root of a given number.
Try the following example program.
<html>   
   <head>
      <title>JavaScript Math sqrt() Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var value = Math.sqrt( 0.5 );
         document.write("First Test Value : " + value );
         
         var value = Math.sqrt( 81 );
         document.write("<br />Second Test Value : " + value ); 
         
         var value = Math.sqrt( 13 );
         document.write("<br />Third Test Value : " + value ); 
         
         var value = Math.sqrt( -4 );
         document.write("<br />Fourth Test Value : " + value ); 
      </script>      
   </body>
</html>
First Test Value : 0.7071067811865476
Second Test Value : 9
Third Test Value : 3.605551275463989
Fourth Test Value : NaN  


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page