code-rag-bench/online-tutorials huggingface dataset:
How can I match a comma separated list against a value in MySQL?

Let us first create a table −
mysql> create table DemoTable
(
   `Values` varchar(50)
);
Query OK, 0 rows affected (1.15 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('23,45,78,56');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('384,476,7456');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('68,8,88,89');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('78,80,84');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| Values       |
+--------------+
| 23,45,78,56  |
| 384,476,7456 |
| 68,8,88,89   |
| 78,80,84     |
+--------------+
4 rows in set (0.00 sec)
Following is the query to match a comma-separated list against a value −
mysql> select *from DemoTable where find_in_set('8',`Values`)!=0;
This will produce the following output −
+------------+
| Values     |
+------------+
| 68,8,88,89 |
+------------+
1 row in set (0.00 sec)
Adding two values at a time from an array - JavaScript

Let’s say, we are required to write a JavaScript function that takes in an array of Numbers and returns a new array with elements as sum of two consecutive elements from the original array.
For example, if the input array is −
const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8];
Then the output should be −
const output = [9, 90, 26, 4, 14];
Following is the code −
const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8];
const twiceSum = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i += 2){
      res.push(arr[i] + (arr[i+1] || 0));
   };
   return res;
};
console.log(twiceSum(arr));
This will produce the following output in console −
[ 9, 90, 26, 4, 14 ]
How can we compare data in two MySQL tables?

Sometimes we need to identify the unmatched data from two tables, especially in the case when data is migrated. It can be done by comparing the tables. Consider the example below in which we have two tables named ‘students’ and ‘student1’.
mysql> Select * from students;
+--------+--------+----------+
| RollNo | Name   | Subject  |
+--------+--------+----------+
|    100 | Gaurav | Computer |
|    101 | Raman  | History  |
|    102 | Somil  | Computer |
+--------+--------+----------+
3 rows in set (0.00 sec)

mysql> select * from student1;
+--------+--------+----------+
| RollNo | Name | Subject |
+--------+--------+----------+
|    100 | Gaurav | Computer |
|    101 | Raman  | History  |
|    102 | Somil  | Computer |
|    103 | Rahul  | DBMS     |
|    104 | Aarav  | History  |
+--------+--------+----------+
5 rows in set (0.00 sec)
Now, with the help of query below, we can compare these tables and get the unmatched rows as the result set.
mysql> Select RollNo,Name,Subject from(select RollNo,Name,Subject from students union all select RollNo,Name,Subject from Student1)as std GROUP BY RollNo,Name,Subject HAVING Count(*) = 1 ORDER BY RollNo;
+--------+-------+---------+
| RollNo | Name  | Subject |
+--------+-------+---------+
|    103 | Rahul | DBMS    |
|    104 | Aarav | History |
+--------+-------+---------+
1 rows in set (0.02 sec)
Understanding the Node lifecycle and event loop in node.js

Simple http server in node.js will register an event loop which will keep on listening for http requests.
Execution of file containing code for creation of server will work as shown below −
node App.js => Start executing script => Code parsing, Register events and functions => event loop=> keeps on running as long as event are registered.
This is the single threaded event driven approach of the node.js. For accessing and updating of values in database also works using the event driven approach. Even though it’s a single threaded, it can handle multiple requests at a time due to its speed of handling.
Example −
const server = http.createServer( (req, res)=>{ console.log(‘hello’); } );
In above example code, createServer method takes request listener as an argument which an event . This event will keep on listening to an http requests on specified port.
How to exit from event loop
process.exit() is the function that will stop the event loop.
App.js
const http = require(‘http’);
const server = http.createServer( (req, res)=>{ console.log(‘hello’); process.exit(); } );
server.listen(3000);
Now, once we run the App.js file using node App.js using terminal, the event loop will start. The event loop will stop on receiving the first http request. This can be checked from opening a browser and navigate to localhost:3000, and se the console log in terminal. It will print hello message and also stops the event loop.
process.exit() is rarely used as we always to keep the event loop running to listen http requests or connection to database. It can be used based on specific requirements only.
If we just need to exit from terminal by stopping node process, we can use ctrl + c in terminal to stop the node process.
Event loop follows a non blocking code execution.
Simple Event Emitter example
// import the core module events from node.js
const events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('TutorialsPointEvent', function (data) {
   console.log(' Hello Tutorials point Event': ' + data);
});
// Raising FirstEvent
em.emit(' TutorialsPointEvent', 'This is my first Simple Node.js event emitter example on TutorialsPoint.');
How to insert date object in MySQL using Python?

To insert a date in a MySQL database, you need to have a column of Type date or datetime in your table. Once you have that, you'll need to convert your date in a string format before inserting it to your database. To do this, you can use the datetime module's strftime formatting function.
from datetime import datetime
now = datetime.now()
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# Assuming you have a cursor named cursor you want to execute this query on:
cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))
Running this will try to insert the tuple (id, date) in your table.
What are save points in JDBC? Explain?

Savepoint interface gives you the additional transactional control. Most modern DBMS, support save points within their environments such as Oracle's PL/SQL.
When you set a save point you define a logical rollback point within a transaction. If an error occurs past a save point, you can use the rollback method to undo either all the changes or only the changes made after the save point.
The Connection object has two new methods that help you manage save points −
setSavepoint(String savepointName): Defines a new save point. It also returns a Savepoint object.
setSavepoint(String savepointName): Defines a new save point. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName): Deletes a Savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a save point generated by the setSavepoint() method.
releaseSavepoint(Savepoint savepointName): Deletes a Savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a save point generated by the setSavepoint() method.
There is one rollback (String savepointName) method, which rolls back work to the specified save point.
try {
   //Assume a valid connection object conn
   conn.setAutoCommit(false);
   Statement stmt = conn.createStatement();
   //set a Savepoint
   Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
   String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')";
   stmt.executeUpdate(SQL);
   //Submit a malformed SQL statement that breaks
   String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Tez')";
   stmt.executeUpdate(SQL);
   // If there is no error, commit the changes.
   conn.commit();
} catch(SQLException se){
   // If there is any error.
   conn.rollback(savepoint1);
}
Python Pillow - Colors on an Image

The ImageColor module contains colors in different format arranged in tables and it also contains converters from CSS3-style color specifiers to RGB tuples.
The ImageColor module supports the following strings formats −
Hexadecimal color specifiers, given as #rgb or #rrggbb. For example, #00ff00 represents pure green.
Hexadecimal color specifiers, given as #rgb or #rrggbb. For example, #00ff00 represents pure green.
#00ff00 hex color, red value is 0 (0% red), green value is 255(100% green) and the blue value of its RGB is 0 (0% blue).
#00ff00 hex color, red value is 0 (0% red), green value is 255(100% green) and the blue value of its RGB is 0 (0% blue).
Cylindrical – coordinate representations (also referred to as HSL) of color #00ff00 hue: 0.33, saturation: 1.00 and also the lightness value of 00ff00 is 0.50.
Cylindrical – coordinate representations (also referred to as HSL) of color #00ff00 hue: 0.33, saturation: 1.00 and also the lightness value of 00ff00 is 0.50.
The Image Color module provides around 140 standard color names, based on the color’s supported by the X Window system and most web browsers. Color names are case insensitive.
The Image Color module provides around 140 standard color names, based on the color’s supported by the X Window system and most web browsers. Color names are case insensitive.
Convert a color string to an RGB tuple. If the string cannot be parsed, a ValueError exception is raised by this function.
PIL.ImageColor.getrgb(color)

Where,
Arguments: color – A color string
Arguments: color – A color string
Return Value: (red, green, blue[, alpha])
Return Value: (red, green, blue[, alpha])
from PIL import ImageColor

# using getrgb
img = ImageColor.getrgb("blue")
print(img)

img1 = ImageColor.getrgb("purple")
print(img1)
(0, 0, 255)
(128, 0, 128)

#Import required image modules
from PIL import Image,ImageColor

# Create new image & get color RGB tuple.
img = Image.new("RGB", (256, 256), ImageColor.getrgb("#add8e6"))

#Show image
img.show()
This method is same as getrgb(), however, converts the RGB value to a greyscale value, if the mode isn’t The graphics commands support shape drawing and text annotation color or a palette image. If the string cannot be parsed, this function raises a ValueError exception.
PIL.ImageColor.getcolor(color, mode)

Where,
Arguments - A color string
Arguments - A color string
Return Value - (graylevel[, alpha]) or (red, green, blue[, alpha])
Return Value - (graylevel[, alpha]) or (red, green, blue[, alpha])
#Import required image modules
from PIL import Image,ImageColor

# using getrgb

img = ImageColor.getrgb("skyblue")
print(img)

img1 = ImageColor.getrgb("purple")
print(img1)
(135, 206, 235)
(128, 0, 128)


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to stop service with their dependent services in PowerShell?

To stop the service which has dependent service in PowerShell -Force parameter is used. First, we will check what are the dependent services for specific service, to get them -DependentService parameter is used.
For example, WMI service (Name: Winmgmt) has multiple dependent services.
Get-Service -Name Winmgmt -DependentServices
tatus   Name           DisplayName
------   ----           -----------
Running  UALSVC           User Access Logging Service
Stopped  smstsmgr           ConfigMgr Task Sequence Agent
Stopped  SepLpsService      Symantec Endpoint Protection Local ...
Stopped  NcaSvc           Network Connectivity Assistant
Running  iphlpsvc           IP Helper
Running  CcmExec           SMS Agent Host
Now, we will stop Winmgmt Service along with their dependent services with -Force parameter. To check the command process -verbose parameter is added.
Stop-Service -Name Winmgmt -Force -Verbose

With Displayname,
Stop-Service -DisplayName "Windows Management Instrument" -Force -Verbose
Another way to stop the dependent service is to get the dependent services first and then pipeline Stop-Service parameter and you don’t need to use -Force parameter this time, but this will only stop the dependent services, not the service which is specified.
Get-Service Winmgmt -DependentServices | Stop-Service -Verbose

The above command will stop the dependent services of Winmgmt but not itself.
How to verify an attribute is present in an element using Selenium WebDriver?

We can verify if an attribute is present in an element with Selenium webdriver. This is achieved with the help of the getAttribute method. In an html document, each element is identified with its tagname along with the element attributes with their values. To get an attribute value, we have to pass the element attribute as an argument to the getAttribute method.
Let us see the html code of an element and obtain the value of its src attribute. The value of its src attribute shall be /about/images/logo.png.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class AttributeVal{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l=driver.findElement(By.className("tp-logo"));
      // getAttribute() to get src value
      String value = l.getAttribute("src");
      System.out.println("Src attribute is: "+ value);
      driver.close()
   }
}
Sort ArrayList in Descending order using Comparator with Java Collections

In order to sort ArrayList in Descending order using Comparator, we need to use the Collections.reverseOrder() method which returns a comparator which gives the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
Declaration − The java.util.Collections.reverseOrder() method is declared as follows -
public static <T>Comparator<T> reverseOrder()
Let us see a program to sort an ArrayList in Descending order using Comparator  with Java Collections −
 Live Demo
import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(10);
      list.add(50);
      list.add(30);
      list.add(20);
      list.add(40);
      list.add(60);
      System.out.println("Original list : " + list);
      Comparator c = Collections.reverseOrder();
      Collections.sort(list,c);
      System.out.println("Sorted list using Comparator : " + list);
   }
}
Original list : [10, 50, 30, 20, 40, 60]
Sorted list using Comparator : [60, 50, 40, 30, 20, 10]
How to format date in JSP?

The <fmt:formatDate> tag is used to format dates in a variety of ways.
The <fmt:formatDate> tag has the following attributes −
The pattern attribute is used to specify even more precise handling of the date −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
   <head>
      <title>JSTL fmt:dateNumber Tag</title>
   </head>
   <body>
      <h3>Number Format:</h3>
      <c:set var = "now" value = "<% = new java.util.Date()%>" />
      <p>Formatted Date (1): <fmt:formatDate type = "time" value = "${now}" /></p>
      <p>Formatted Date (2): <fmt:formatDate type = "date" value = "${now}" /></p>
      <p>Formatted Date (3): <fmt:formatDate type = "both" value = "${now}" /></p>
      <p>Formatted Date (4): <fmt:formatDate type = "both" dateStyle = "short" timeStyle = "short" value = "${now}" /></p>
      <p>Formatted Date (5): <fmt:formatDate type = "both" dateStyle = "medium" timeStyle = "medium" value = "${now}" /></p>
      <p>Formatted Date (6): <fmt:formatDate type = "both" dateStyle = "long" timeStyle = "long" value = "${now}" /></p>
      <p>Formatted Date (7): <fmt:formatDate pattern = "yyyy-MM-dd" value = "${now}" /></p>
   </body>
</html>
The above code will generate the following result −
Date Format:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23
Program to find number of subsequences that satisfy the given sum condition using Python

Suppose we have an array called nums and another value k. We have to find the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is smaller or equal to k. The answers may be very large so return answer mod 10^9 + 7.
So, if the input is like nums = [4,6,7,8] k = 11, then the output will be 4 because there are subsequences like
[4], here minimum is 4, maximum is 4, so 4+4 <= 11
[4], here minimum is 4, maximum is 4, so 4+4 <= 11
[4,6], here minimum is 4, maximum is 6, so 4+6 <= 11
[4,6], here minimum is 4, maximum is 6, so 4+6 <= 11
[4,6,7], here minimum is 4, maximum is 7, so 4+7 <= 11
[4,6,7], here minimum is 4, maximum is 7, so 4+7 <= 11
[4,7], here minimum is 4, maximum is 7, so 4+7 <= 11
[4,7], here minimum is 4, maximum is 7, so 4+7 <= 11
To solve this, we will follow these steps −
sort the list nums
sort the list nums
m := 10^9 + 7
m := 10^9 + 7
left := 0
left := 0
right := size of nums - 1
right := size of nums - 1
res := 0
res := 0
while left <= right, doif nums[left] + nums[right] > k, thenright := right - 1otherwise,num_inside := right - leftres :=(res + (2^num_inside) mod m) mod mleft := left + 1
while left <= right, do
if nums[left] + nums[right] > k, thenright := right - 1
if nums[left] + nums[right] > k, then
right := right - 1
right := right - 1
otherwise,num_inside := right - leftres :=(res + (2^num_inside) mod m) mod mleft := left + 1
otherwise,
num_inside := right - left
num_inside := right - left
res :=(res + (2^num_inside) mod m) mod m
res :=(res + (2^num_inside) mod m) mod m
left := left + 1
left := left + 1
return res
return res
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums, k):
   nums.sort()
   m = 10**9 + 7
   left = 0
   right = len(nums) - 1
   res = 0
   while(left <= right):
      if nums[left] + nums[right] > k:
         right -= 1
      else:
         num_inside = right - left
         res = (res + pow(2, num_inside, m)) % m
         left += 1
   return res
nums = [4,6,7,8]
k = 11
print(solve(nums, k))
[4,6,7,8], 11
4
How to apply Histogram Equalizer in OpenCV using C++?

The histogram represents the depth intensity of an image. For example, consider an image with a color depth of 8 bit. It means every pixel can have color depth from 0 to  Means from 0 to 255. If the image is an RGB image, it has a red, green, and blue channel. For example, at the point of the image, there is only red. Then the color depth of that image is in the red channel, and the value of the pixel will vary from 0 to 255. 0 means no red and 255 means more read.
The histogram shows this kind of result for all of the channels and all of the colors. By changing the value of the pixels, you can change the intensity of some specific color pixels. For example, if you want to increase the red channel density, you can change the red channel's value.
First of all, we will apply histogram equalizer in a gray image. A gray image includes only black and white. That means there is only one channel. The image is an 8-bit image. It means the color depth varies from 0 to 255. 0 means white, and 255 means black. In the following code, we will load a color image and will convert it to grayscale. Then we will use the 'equalizeHist' function of OpenCV to equalize the pixel values.
The following program shows how to apply Histogram Equalizer in OpenCV.
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat original;//Declaring a matrix//
   original = imread("view.jpg");//loading the image
   Mat gray;//declaring a matrix//
   cvtColor(original, gray, COLOR_BGR2GRAY);//converting to grayscale//
   Mat hist;//declaring a matrix//
   equalizeHist(gray, hist);//applying histogram equalizer
   namedWindow("Original");//window for actual image//
   namedWindow("gray");//window for grayscale image//
   namedWindow("histogram");//window for histogram//
   imshow("Original", original);//showing actual image//
   imshow("gray", gray);//showing grayscale image//
   imshow("histogram", hist);//showing histogram effect
   waitKey(0);//wait for keystroke//
   return(0);
}
Custom Keras Generators. A short intro to writing Keras... | by Nilesh | Towards Data Science

The idea behind using a Keras generator is to get batches of input and corresponding output on the fly during training process, e.g. reading in 100 images, getting corresponding 100 label vectors and then feeding this set to the gpu for training step.
The problem I faced was memory requirement for the standard Keras generator. The in-memory generator creates copies of the original data as well as has to convert the dtype from uint8 to float64. On the other hand, the Keras generator to read from directory expects images in each class to be in an independent directory (Not possible in multi-label problems, segmentation problems etc.)
So, I like to split the batch generator into 4 steps:
1. Get input            : input_path -> image2. Get output           : input_path -> label3. Pre-process input    : image -> pre-processing step -> image4. Get generator output : ( batch_input, batch_labels )
Step 1 : Define a function to get input (can be subsetting a numpy array, pandas dataframe, reading in from disk etc.) :
from skimage.io import imreaddef get_input(path):        img = imread( path )        return( img )
Step 2 : Define a function to get output :
import numpy as npimport pandas as pddef get_output( path, label_file = None ):        img_id = path.split('/')[-1].split('.')[0]    labels = label_file.loc[img_id].values        return(labels)
Step 3 : Define a function to preprocess input :
def preprocess_input( image ):        --- Rescale Image    --- Rotate Image    --- Resize Image    --- Flip Image    --- PCA etc.        return( image )
Step 4 : Bring everything together to define your generator :
def image_generator(files, label_file, batch_size = 64):        while True:          # Select files (paths/indices) for the batch          batch_paths  = np.random.choice(a    = files,                                           size = batch_size)          batch_input  = []          batch_output = []                     # Read in each input, perform preprocessing and get labels          for input_path in batch_paths:              input = get_input(input_path )              output = get_output(input_path,label_file=label_file )                          input = preprocess_input(image=input)              batch_input += [ input ]              batch_output += [ output ]          # Return a tuple of (input, output) to feed the network          batch_x = np.array( batch_input )          batch_y = np.array( batch_output )                  yield( batch_x, batch_y )
And there you have it, you can add to pre-processing function as defined by your specific data-set , have the output as an image mask ( segmentation problems, localization problems etc. ).
After this, using this custom generator is the same as using a predefined Keras ImageDataGenerator and simply pass the generator object to model.fit_generator().
How to set X-axis values in Matplotlib Python?

To set X-axis values in matplotlib in Python, we can take the following steps −
Create two lists for x and y data points.
Create two lists for x and y data points.
Get the xticks range value.
Get the xticks range value.
Plot a line using plot() method with xtick range value and y data points.
Plot a line using plot() method with xtick range value and y data points.
Replace xticks with X-axis value using xticks() method.
Replace xticks with X-axis value using xticks() method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [45, 1, 34, 78, 100]
y = [8, 10, 23, 78, 2]
default_x_ticks = range(len(x))
plt.plot(default_x_ticks, y)
plt.xticks(default_x_ticks, x)
plt.show()
Golang program to create an integer array that takes inputs from users.

Approach
Ask the user to enter the size of array.
Ask the user to enter the size of array.
Make an integer array of given size.
Make an integer array of given size.
Ask the user to enter elements.
Ask the user to enter elements.
At the end, print the array.
At the end, print the array.
 Live Demo
package main
import (
   "fmt"
)
func main(){
   fmt.Printf("Enter size of your array: ")
   var size int
   fmt.Scanln(&size)
   var arr = make([]int, size)
   for i:=0; i<size; i++ {
      fmt.Printf("Enter %dth element: ", i)
      fmt.Scanf("%d", &arr[i])
   }
   fmt.Println("Your array is: ", arr)
}
Enter size of your array: 6
Enter 0th element: 10
Enter 1th element: 20
Enter 2th element: 30
Enter 3th element: 40
Enter 4th element: 50
Enter 5th element: 60
Your array is: [10 20 30 40 50 60]
Banker's Algorithm in Operating System - GeeksforGeeks

15 Jun, 2021
Prerequisite – Resource Allocation Graph (RAG), Banker’s Algorithm, Program for Banker’s Algorithm Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm test for safety simulating the allocation for predetermined maximum possible amounts of all resources, then makes an “s-state” check to test for possible activities, before deciding whether allocation should be allowed to continue.
In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is it safe to allocate a resource to a process and if not then resource is not allocated to that process. Determining a safe sequence(even if there is only 1) will assure that system will not go into deadlock.
Banker’s algorithm is generally used to find if a safe sequence exist or not. But here we will determine the total number of safe sequences and print all safe sequences.
The data structure used are: 
Available vector
Max Matrix
Allocation Matrix
Need Matrix
Example:Input: 
 
 
Output: Safe sequences are:
P2--> P4--> P1--> P3
P2--> P4--> P3--> P1
P4--> P2--> P1--> P3
P4--> P2--> P3--> P1

There are total 4 safe-sequences 
Explanation: Total resources are R1 = 10, R2 = 5, R3 = 7 and allocated resources are R1 = (0+2+3+2 =) 7, R2 = (1+0+0+1 =) 2, R3 = (0+0+2+1 =) 3. Therefore, remaining resources are R1 = (10 – 7 =) 3, R2 = (5 – 2 =) 3, R3 = (7 – 3 =) 4. Remaining available = Total resources – allocated resources and Remaining need = max – allocated 
So, we can start from either P2 or P4. We can not satisfy remaining need from available resources of either P1 or P3 in first or second attempt step of Banker’s algorithm. There are only four possible safe sequences. These are : P2–> P4–> P1–> P3 P2–> P4–> P3–> P1 P4–> P2–> P1–> P3 P4–> P2–> P3–> P1
Implementation:
.
Output: 
Safe sequences are:
P2--> P4--> P1--> P3
P2--> P4--> P3--> P1
P4--> P2--> P1--> P3
P4--> P2--> P3--> P1

There are total 4 safe-sequences
 
princiraj1992
Rajput-Ji
rutvik_56
dharanendralv23
Algorithms
GATE CS
Matrix
Operating Systems
Operating Systems
Matrix
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Difference between Informed and Uninformed Search in AI
Cyclomatic Complexity
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
C++ Program to Find Factorial of Large Numbers

The following is an example to find the factorial.
#include <iostream>
using namespace std;
int fact(unsigned long long int n) {
   if (n == 0 || n == 1)
   return 1;
   else
   return n * fact(n - 1);
}
int main() {
   unsigned long long int n;
   cout<<"Enter number : ";
   cin>>n;
   cout<< “\nThe factorial : “ << fact(n);
   return 0;
}
Enter number : 19
The factorial : 109641728
In the above program, we have declared a variabe with the following data type for large numbers.
unsigned long long int n;
The actual code is in fact() function as follows −
int fact(unsigned long long int n) {
   if (n == 0 || n == 1)
   return 1;
   else
   return n * fact(n - 1);
}
In the main() function, a number is entered by the user and fact() is called. The factorial of entered number is printed.
cout<<"Enter number : ";
cin>>n;
cout<<fact(n);
How to decrease the density of x-ticks in Seaborn?

To decrease the density of x-ticks in Seaborn, we can use set_visible=False for odd positions.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a dataframe with X-axis and Y-axis keys.
Create a dataframe with X-axis and Y-axis keys.
Show the point estimates and confidence intervals with bars, using barplot() method.
Show the point estimates and confidence intervals with bars, using barplot() method.
Iterate bar_plot.get_xticklabels() method. If index is even, then make them visible; else, not visible.
Iterate bar_plot.get_xticklabels() method. If index is even, then make them visible; else, not visible.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas
import matplotlib.pylab as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pandas.DataFrame({"X-Axis": [i for i in range(10)], "Y-Axis": [i for i in range(10)]})
bar_plot = sns.barplot(x='X-Axis', y='Y-Axis', data=df)
for index, label in enumerate(bar_plot.get_xticklabels()):
   if index % 2 == 0:
      label.set_visible(True)
   else:
      label.set_visible(False)
plt.show()
How to test if a letter in a string is uppercase or lowercase using javascript?

To test if a letter in a string is uppercase or lowercase using javascript, you can simply convert the char to its respective case and see the result.
function checkCase(ch) {
   if (!isNaN(ch * 1)){
      return 'ch is numeric';
   }
    else {
      if (ch == ch.toUpperCase()) {
         return 'upper case';
      }
      if (ch == ch.toLowerCase()){
         return 'lower case';
      }
   }
}
console.log(checkCase('a'))
console.log(checkCase('A'))
console.log(checkCase('1'))
This will give the output −
lower case
upper case
ch is numeric
Left pad a string in Java

To left pad a string, use the String.format and set the spaces.
String.format("|%20s|", "demotext")
If you add 30 above, it will display the first string after 30 spaces from the beginning.
String.format("|%30s|", "demotext")
 Live Demo
public class Demo {
   public static void main(String []args) {
      System.out.print(String.format("|%20s|", "demotext"));
      System.out.println("Left padded!");
   }
}
| demotext|Left padded
Explain aggregate functions with the help of SQL queries

Aggregate functions perform Calculation on a set of values and return a single value. They ignore NULL values except COUNT and are used with GROUP BY clause of SELECT statement.
The different types of aggregate functions are −
AVG
MAX
MIN
SUM
COUNT()
COUNT(*)
Let’s consider an employee table. We will perform the calculations on this table by using aggregate functions.
The keyword used to calculate the average of given items is AVG. It returns the average of the data values.
Syntax
The syntax is as follows −
select <column name> from <table name>;
Example
An example of use of average function is as follows −
select AVG(salary) from employee;
Output
You will get the following output −
AVG(salary)= 16800
The keyword used to return maximum value for a column is MAX.
Syntax
The syntax is as follows −
select MAX <column name> from <table name>;
Example
An example of use of maximum function is as follows −
select MAX(salary) from employee;
Output
You will get the following output −
Max(salary)=30000
The keyword used to return the minimum value for a column is MIN.
Syntax
The syntax is as follows −
select MIN <column-name> from <table-name>;
Example
An example of use of minimum function is as follows −
select MIN (salary) from employee;
Output
You will get the following output −
MIN(salary)=4000
It returns the sum(addition) of the data values. The keyword used to perform addition on data items is SUM.
Syntax
The syntax is as follows −
select SUM <column-name> from <table-name>;
Example
An example of use of SUM function is as follows −
select SUM (salary) from employee where city=’Pune’;
Output
You will get the following output −
SUM (salary)= 50000
It returns the total number of values in a given column.
Syntax
The syntax is given below −
select COUNT <column-name> from <table-name>;
Example
An example of use of COUNT function is as follows −
select COUNT(Empid) from employee;
Output
You will get the following output −
COUNT(Empid)= 5
It returns the number of rows in a table.
Syntax
The syntax is as follows −
select COUNT(*) from <table-name>;
Example
An example of use of COUNT(*) function is as follows:
select COUNT(*) from employee;
Output
You will get the following output −
COUNT(*) =5
LISP - Constants

In LISP, constants are variables that never change their values during program execution. Constants are declared using the defconstant construct.
The following example shows declaring a global constant PI and later using this value inside a function named area-circle that calculates the area of a circle.
The defun construct is used for defining a function, we will look into it in the Functions chapter.
Create a new source code file named main.lisp and type the following code in it.
(defconstant PI 3.141592)
(defun area-circle(rad)
   (terpri)
   (format t "Radius: ~5f" rad)
   (format t "~%Area: ~10f" (* PI rad rad)))
(area-circle 10)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.
Radius:  10.0
Area:   314.1592


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
How to get primary key of a table in MySQL?

To get the primary key of a table, you can use the show command. The syntax is as follows −
SHOW INDEX FROM yourDatebaseName.yourTableName WHERE Key_name = 'PRIMARY';
Suppose, we have a table with two primary keys; one of them is “Id” and second is “RollNum". The query for a table is as follows −
mysql> create table TwoOrMorePrimary
   −> (
   −> Id int,
   −> Name varchar(200), 
   −> RollNum int
   −> ,
   −> Primary key(Id,Age)
   −> );
Query OK, 0 rows affected (0.85 sec)
Apply the above syntax to get primary key of a table. The query is as follows −
mysql> SHOW INDEX FROM business.TwoOrMorePrimary
−> WHERE Key_name = 'PRIMARY';
The following is the output −
+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table            | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| twoormoreprimary |          0 | PRIMARY  | 1            | Id          | A         | 0           | NULL     | NULL   |      | BTREE      |         |               | YES     | NULL       |
| twoormoreprimary |          0 | PRIMARY  | 2            | RollNum     | A         | 0           | NULL     | NULL   |      | BTREE      |         |               | YES      | NULL      |
+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
2 rows in set (0.12 sec)
Stop making form to reload a page in JavaScript

Let’s say what we need to achieve is when the user submits this HTML form, we handle the
submit event on client side and prevent the browser to reload as soon as the form is submitted
HTML form
<form name="formcontact1" action="#">
<input
type='text'
name='email'
size="36"
placeholder="Your e-mail :)"/>
<input
   type="submit"
   name="submit"
   value="SUBMIT"
   onclick="ValidateEmail(document.formcontact1.email)"
/>
</form>
Now, the easiest and the most reliable way of doing so is by tweaking our ValidateEmail()
function to include the following line right at the top of its definition −
function ValidateEmail(event, inputText){
   event.preventDefault();
   //remaining function logic goes here
}
What preventDefault() does is that it tells the browser to prevent its default behaviour and let us
handle the form submitting event on the client side itself.
The full HTML code for this is −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="formcontact1" action="#">
<input
type='text'
name='email'
size="36"
placeholder="Your e-mail :)"/>
<input
   type="submit"
   name="submit"
   value="SUBMIT"
   onclick="ValidateEmail(document.formcontact1.email)"
/>
</form>
<script>
{
   function ValidateEmail(event, inputText){
      event.preventDefault();
      //remaining function logic goes here
   }
}
</script>
</body>
</html>
Clone() method in C#

The Clone() method in C# is used to create a similar copy of the array.
Let us see an example to clone an array using the Clone() method −
 Live Demo
using System;
class Program {
   static void Main() {
      string[] arr = { "one", "two", "three", "four", "five" };
      string[] arrCloned = arr.Clone() as string[];
      Console.WriteLine(string.Join(",", arr));
      // cloned array
      Console.WriteLine(string.Join(",", arrCloned));
      Console.WriteLine();
   }
}
one,two,three,four,five
one,two,three,four,five
Above, we have a string array −
string[] arr = { "one", "two", "three", "four", "five" };
With that, in a new string array, we have used the Clone() method with the as operator to clone the array −
string[] arrCloned = arr.Clone() as string[];
Shifting values of rows in MySQL to change the existing id values for existing rows?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (1.07 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Robert      |
|         3 | David       |
|         4 | Mike        |
+-----------+-------------+
4 rows in set (0.00 sec)
Here is the query to shift id values of existing rows in MySQL −
mysql> update DemoTable set StudentId=StudentId+1000;
Query OK, 4 rows affected (0.18 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|      1001 | Chris       |
|      1002 | Robert      |
|      1003 | David       |
|      1004 | Mike        |
+-----------+-------------+
4 rows in set (0.00 sec)
Git Security SSH

Up to this point, we have used HTTPS to connect to our remote repository.
HTTPS will usually work just fine, but you should use SSH if you work with unsecured networks. And sometimes, a project will require that you use SSH.
SSH is a secure shell network protocol that is used for network management, 
remote file transfer, and remote system access.
SSH uses a pair of SSH keys to establish an authenticated and encrypted 
secure network protocol. It allows for secure remote communication on unsecured 
open networks.
SSH keys are used to initiate a secure "handshake". When generating a set of 
keys, you will generate a "public" and "private" key.
The "public" key is the one you share with the remote party. Think of this 
more as the lock.
The "private" key is the one you keep for yourself in a secure place. Think of 
this as the key to the lock.
SSH keys are generated through a security algorithm. It is all very complicated, but it uses prime numbers, and 
large random numbers to make the public and private key.
It is created so that the public key can be derived from the private 
key, but not the other way around.
In rhe command line for Linux, Apple, and in the Git Bash for Windows, you can 
generate an SSH key.
Let's go through it, step by step.
Start by creating a new key, using your email as a label:
ssh-keygen -t rsa -b 4096 -C "test@w3schools.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa):
Created directory '/Users/user/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/user/.ssh/id_rsa
Your public key has been saved in /Users/user/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:******************************************* test@w3schools.com
The key's randomart image is:
+---[RSA 4096]----+
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
+----[SHA256]-----+
You will be prompted with the following through this creation:
Enter file in which to save the key (/c/Users/user/.ssh/id_rsa):
Select a file location, or press "Enter" to use the default file location.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Entering a secure passphrase will create an additional layer of security. Preventing anyone who gains access to the computer to use that key without the passphrase. However, it will require you to supply the passphrase anytime the SSH key is used.
Now we add this SSH key pair to the SSH-Agent (using the file location from above):
ssh-add /Users/user/.ssh/id_rsa
Enter passphrase for /Users/user/.ssh/id_rsa:
Identity added: /Users/user/.ssh/id_rsa (test@w3schools.com)
You will be prompted to supply the passphrase, if you added one.
Now the SSH key pair is ready to use.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Byte Struct in C# - GeeksforGeeks

03 Jan, 2020
In C#, Byte Struct is used to represent 8-bit unsigned integers. The Byte is an immutable value type and the range of Byte is from 0 to 255. This class allows you to create Byte data types and you can perform mathematical and bitwise operations on them like addition, subtraction, multiplication, division, XOR, AND etc.
Example:
// C# program to illustrate the concept// of MaxValue and MinValue fields in Byteusing System;  public class GFG {      // Main method    static public void Main()    {          // Display the minimum and        // the maximum value of Byte        Console.WriteLine("The minimum value "+                 "of Byte: {0}", Byte.MinValue);          Console.WriteLine("The maximum value "+                 "of Byte: {0}", Byte.MaxValue);    }}
The minimum value of Byte: 0
The maximum value of Byte: 255

Example:
// C# program to illustrate the concept// of CompareTo(Byte) method in Byteusing System;  public class GFG {      // Main method    static public void Main()    {          // val1, val2, and val3 are of byte type        byte val1 = 32;        byte val2 = 40;        byte val3 = 10;          // Display the comparison        // Using CompareTo(Byte) method        Console.WriteLine("Comparison 1: {0}",                         val1.CompareTo(val2));          Console.WriteLine("Comparison 2: {0}",                          val2.CompareTo(val3));          Console.WriteLine("Comparison 3: {0}",                         val3.CompareTo(val3));          Console.WriteLine("Comparison 4: {0}",                         val1.CompareTo(val3));    }}
Comparison 1: -8
Comparison 2: 30
Comparison 3: 0
Comparison 4: 22

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.byte?view=netframework-4.7.2
Akanksha_Rai
CSharp-Byte-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
Difference between Ref and Out keywords in C#
Introduction to .NET Framework
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
C# | Delegates
Top 50 C# Interview Questions & Answers
Different ways to sort an array in descending order in C#
C# | Replace() Method
Merge JavaScript objects with the same key value and count them

Suppose, we have an array of objects like this −
const arr = [{
   "value": 10,
   "id": "111",
   "name": "BlackCat",
}, {
   "value": 10,
   "id": "111",
   "name":
   "BlackCat",
}, {
   "value": 15,
   "id": "777",
   "name": "WhiteCat",
}];
We are required to write a JavaScript function that takes in one such array.
The function should then merge all those objects together that have the common value for "id" property.
Therefore, for the above array, the output should look like −
const output = [{
   "value": 10,
   "id": "111",
   "name": "BlackCat",
   "count": 2,
}, {
   "value": 15,
   "id": "777",
   "name": "WhiteCat",
   "count": 1,
}]
const arr = [{
   "value": 10,
   "id": "111",
   "name": "BlackCat",
}, {
   "value": 10,
   "id": "111",
   "name": "BlackCat",
}, {
   "value": 15,
   "id": "777",
   "name": "WhiteCat",
}];
const combinedItems = (arr = []) => {
   const res = arr.reduce((acc, obj) => {
      let found = false;
      for (let i = 0; i < acc.length; i++) {
         if (acc[i].id === obj.id) {
            found = true;
            acc[i].count++;
         };
      }
      if (!found) {
         obj.count = 1;
         acc.push(obj);
      }
      return acc;
   }, []);
   return res;
}
console.log(combinedItems(arr));
And the output in the console will be −
[
   { value: 10, id: '111', name: 'BlackCat', count: 2 },
   { value: 15, id: '777', name: 'WhiteCat', count: 1 }
]
How to make hollow square marks with Matplotlib in Python?

To make hollow square marks with matplotlib, we can use marker 'ks', markerfacecolor='none', markersize=15, and markeredgecolor=red.
Creat x and y data points using numpy.
Creat x and y data points using numpy.
Create a figure or activate an existing figure, add an axes to the figure as part of a subplot arrangement.
Create a figure or activate an existing figure, add an axes to the figure as part of a subplot arrangement.
Plot x and y data points using plot() method. To make hollow square marks, we can use marker "ks" and markerfacecolor="none", markersize="15" and markeredge color="red".
Plot x and y data points using plot() method. To make hollow square marks, we can use marker "ks" and markerfacecolor="none", markersize="15" and markeredge color="red".
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
y = np.sin(x)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y, 'ks', markerfacecolor='none', ms=15, markeredgecolor='red')
plt.show()