code-rag-bench/online-tutorials huggingface dataset:
MATLAB - Appending Vectors

MATLAB allows you to append vectors together to create new vectors.
If you have two row vectors r1 and r2 with n and m number of elements, to create a row vector r of n plus m elements, by appending these vectors, you write −
r = [r1,r2]

You can also create a matrix r by appending these two vectors, the vector r2, will be the second row of the matrix −
r = [r1;r2]

However, to do this, both the vectors should have same number of elements.
Similarly, you can append two column vectors c1 and c2 with n and m number of elements. To create a column vector c of n plus m elements, by appending these vectors, you write −
c = [c1; c2]

You can also create a matrix c by appending these two vectors; the vector c2 will be the second column of the matrix −
c = [c1, c2]

However, to do this, both the vectors should have same number of elements.
Create a script file with the following code −
r1 = [ 1 2 3 4 ];
r2 = [5 6 7 8 ];
r = [r1,r2]
rMat = [r1;r2]
 
c1 = [ 1; 2; 3; 4 ];
c2 = [5; 6; 7; 8 ];
c = [c1; c2]
cMat = [c1,c2]
When you run the file, it displays the following result −
r =

Columns 1 through 7:

         1          2          3          4          5          6          7

Column 8:

         8

rMat =

         1          2          3          4
         5          6          7          8

c =

         1
         2
         3
         4
         5
         6
         7
         8

cMat =

         1          5
         2          6
         3          7
         4          8



    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Express.js res.json() Function

05 May, 2021
The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method.Syntax:  
res.json( [body] )
Parameters: The body parameter is the body which is to be sent in the response.Return Value: It returns an Object.Installation of express module:  
1. You can visit the link to Install express module. You can install this package by using this command.  
npm install express
2. After installing the express module, you can check your express version in command prompt using the command.  
npm version express
3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.  
node index.js
Example 1: Filename: index.js  
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){    res.json({ user: 'geek' });}); app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Steps to run the program:  
1. The project structure will look like this:  
2. Make sure you have installed express module using the following command:  
npm install express
3. Run index.js file using below command:  
node index.js
Output:  
Server listening on PORT 3000
4. Now open browser and go to http://localhost:3000/, now on your screen you will see the following output:  
{"user":"geek"}
 
Example 2: Filename: index.js  
javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){    res.json({title: "GeeksforGeeks"})    next();}) app.get('/', function(req, res){     console.log("User Page")     res.end();}); app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Run index.js file using below command:  
node index.js
Now open a browser and go to http://localhost:3000/, now on your screen you will see the following output:  
{"title":"GeeksforGeeks"}
And you will see the following output on your console:  
User Page
Reference: https://expressjs.com/en/4x/api.html#res.json 
simmytarika5
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exception Handling in Lambda Expressions

Lambda expressions are difficult to write when the function throws a checked expression. See the example below −
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.stream.Collectors;

public class FunctionTester {
   public static void main(String[] args) {
      String url = "www.google.com";
      System.out.println(encodedAddress(url));
   }   

   public static String encodedAddress(String... address) {
      return Arrays.stream(address)
         .map(s -> URLEncoder.encode(s, "UTF-8"))
         .collect(Collectors.joining(","));
   }
}
The above code fails to compile because URLEncode.encode() throws UnsupportedEncodingException and cannot be thrown by encodeAddress() method.
One possible solution is to extract URLEncoder.encode() into a separate method and handle the exception there.
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.stream.Collectors;

public class FunctionTester {
   public static void main(String[] args) {
      String url = "www.google.com";       
      System.out.println(encodedAddress(url));
   }   

   public static String encodedString(String s) {
      try {
         URLEncoder.encode(s, "UTF-8");
      }
      catch (UnsupportedEncodingException e) {        
         e.printStackTrace();
      }
      return s;
   }

   public static String encodedAddress(String... address) {
      return Arrays.stream(address)
         .map(s -> encodedString(s))
         .collect(Collectors.joining(","));
   }   
}
But above approach is not good when we have multiple such methods which throws exception. See the following generalized solution using functional interface and a wrapper method.
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FunctionTester {
   public static void main(String[] args) {
      String url = "www.google.com";       
      System.out.println(encodedAddress(url));
   }   
   public static String encodedAddress(String... address) {
      return Arrays.stream(address)
         .map(wrapper(s -> URLEncoder.encode(s, "UTF-8")))
         .collect(Collectors.joining(","));
   }

   private static <T, R, E extends Exception> Function<T, R> 
   wrapper(FunctionWithThrows<T, R, E> fe) {
      return arg -> {
         try {
            return fe.apply(arg);
         } catch (Exception e) {
            throw new RuntimeException(e);
         }
      };
   }
}

@FunctionalInterface
interface FunctionWithThrows<T, R, E extends Exception> {
   R apply(T t) throws E;
}
www.google.com


    32 Lectures 
     3.5 hours 

 Pavan Lalwani

    11 Lectures 
     1 hours 

 Prof. Paul Cline, Ed.D

    72 Lectures 
     10.5 hours 

 Arun Ammasai

    51 Lectures 
     2 hours 

 Skillbakerystudios

    43 Lectures 
     4 hours 

 Mohammad Nauman

    8 Lectures 
     1 hours 

 Santharam Sivalenka
 Print
 Add Notes
 Bookmark this page
Merging boolean array with AND operator - JavaScript

Let’s say, we have an array of arrays of boolean like this −
const arr = [[true,false,false],[false,false,false],[false,false,true]];
We are required to write a function that merges this array of arrays into a one-dimensional array by combining the corresponding elements of each subarray using the AND (&&) operator.
Let’s write the code for this function. We will be using Array.prototype.reduce() function to achieve this.
Following is the code −
const arr = [[true,false,false],[false,false,false],[false,false,true]];
const andMerge = (arr = []) => {
   return arr.reduce((acc, val) => {
      val.forEach((bool, ind) => {
         acc[ind] = acc[ind] && bool || false;
      });
      return acc;
   }, []);
};
console.log(andMerge(arr));
This will produce the following output in console −
[ false, false, false ]
How to convert String to Date in java?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.
 Live Demo
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateString {
   public static void main(String args[]) throws Exception{
      String date = "21-9-2017";
      SimpleDateFormat sdt = new SimpleDateFormat("dd-MM-YYYY");
      Date result = sdt.parse(date);
      System.out.println(result);
   }
}
Sun Jan 01 00:00:00 IST 2017
What is the usage of onblur event in JavaScript?

The blur event triggers when object lose focus. You can try to run the following code to learn how to implement onblur event in JavaScript.
<!DOCTYPE html>
<html>
   <body>
      <p>Write below:</p>
      <input type = "text" onblur = "newFunc(this)">
      <script>
         function newFunc(a) {
            a.style.background = "green";
         }
      </script>
   </body>
</html>
R - Web Data

Many websites provide data for consumption by its users. For example the World Health Organization(WHO) provides reports on health and medical information in the form of CSV, txt and XML files. Using R programs, we can programmatically extract specific data from such websites. Some packages in R which are used to scrap data form the web are − "RCurl",XML", and "stringr". They are used to connect to the URL’s, identify required links for the files and download them to the local environment.
The following packages are required for processing the URL’s and links to the files. If they are not available in your R Environment, you can install them using following commands.
install.packages("RCurl")
install.packages("XML")
install.packages("stringr")
install.packages("plyr")

We will visit the URL weather data and download the CSV files using R for the year 2015.
We will use the function getHTMLLinks() to gather the URLs of the files. Then we will use the function download.file() to save the files to the local system. As we will be applying the same code again and again for multiple files, we will create a function to be called multiple times. The filenames are passed as parameters in form of a R list object to this function.
# Read the URL.
url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/"

# Gather the html links present in the webpage.
links <- getHTMLLinks(url)

# Identify only the links which point to the JCMB 2015 files. 
filenames <- links[str_detect(links, "JCMB_2015")]

# Store the file names as a list.
filenames_list <- as.list(filenames)

# Create a function to download the files by passing the URL and filename list.
downloadcsv <- function (mainurl,filename) {
   filedetails <- str_c(mainurl,filename)
   download.file(filedetails,filename)
}

# Now apply the l_ply function and save the files into the current R working directory.
l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/")
After running the above code, you can locate the following files in the current R working directory.
"JCMB_2015.csv" "JCMB_2015_Apr.csv" "JCMB_2015_Feb.csv" "JCMB_2015_Jan.csv"
   "JCMB_2015_Mar.csv"


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
JavaScript undefined Property - GeeksforGeeks

06 Jul, 2020
Below is the example of the undefined Property.
Example:<script>    var a ="Geeksforgeeks"    function test() {        if (typeof a === "undefined") {            txt = "'a' is undefined";        } else {            txt = "'a' is defined";        }        document.write(txt);    }    test();</script>
<script>    var a ="Geeksforgeeks"    function test() {        if (typeof a === "undefined") {            txt = "'a' is undefined";        } else {            txt = "'a' is defined";        }        document.write(txt);    }    test();</script>
Output:'a' is defined
'a' is defined
The undefined property is used to check if a value is assigned to a variable or not.
Syntax:
var x;
if (typeof x === "undefined") {
  txt = "x is undefined";
} else {
  txt = "x is defined";
}
Return Value: It returns ‘defined’ if the variable is assigned any value and ‘undefined’ if the variable is not assigned any value.
More example code for the above property are as follows:Program 1:
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color: green">        GeeksforGeeks    </h1>        <button onclick="test()">        Press    </button>        <h4>        Click on the Press button to         check if "a" is defined or undefined.    </h4>        <p id="gfg"></p>        <script>            function test() {                if (typeof a === "undefined") {                    txt = "'a' is undefined";                } else {                    txt = "'a' is defined";                }                document.getElementById(                "gfg").innerHTML = txt;            }        </script>    </center></body>  </html>
Output:
Supported Browsers:
Google Chrome
Firefox
Internet Explorer
Opera
Safari
JavaScript-Properties
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to use Boto3 to check the statusof all the runsof a given Glue Job?

Problem Statement − Use boto3 library in Python to check statuses of all runs of a given job.
Example − Get the status of all runs of a glue job named as ‘run_s3_file_job’.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − job_name is the mandatory parameters. The function will fetch the details of a given job_name.
Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4 − Create an AWS client for glue.
Step 5 − Now use get_job_runs function and pass the job_name as JobName parameter.
Step 6 − It fetches the details of all past job runs of the given job.
Step 7 − Use for loop to get details of specific job runs one by one.
Step 8 − Now, get the specific status of the job and corresponding job run id. Status could be Running if the job is not completed, else SUCCEEDED/FAILED.
Step 9 − Handle the generic exception if something went wrong while checking the job.
Use the following code to check statuses of all runs of a given job −
import boto3
from botocore.exceptions import ClientError

def get_status_of_job_all_runs(job_name):
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.get_job_runs(JobName=job_name)
      for res in response['JobRuns']:
         print("Job Run id is:"+res.get("Id"))
         print("status is:"+res.get("JobRunState"))
   except ClientError as e:
      raise Exception("boto3 client error in get_status_of_job_all_runs: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in get_status_of_job_all_runs: " + e.__str__())
get_status_of_job_all_runs("run_s3_file_job"))
job id
is:jr_6ef92e90ad66b1a6c7abb1c2659d114a34962b8c6ae4bf9b328ac90b99a33b7d
status is:FAILED
job id
is:jr_9fef13265036406e03e7cae79257305353203ab20b5f400e0c429e10a4999dba
status is:FAILED
job id
is:jr_f9d715a33e83460fc2ef6dee0840a98ef52c06c2ff569627633c4505fda7d835
status is:FAILED
job id
is:jr_71b57633ac4d8c24f904f0ae01f613f6d54baee440d0ede23f6030cffb0bf4d7
status is:FAILED
job id
is:jr_b7ead6b6ae43da2580888c73d6896c177510df73bd77c843d3e77b4dc5f22e2f
status is:FAILED
job id
is:jr_6e757509d51066648d49c22a47c26e728d6f842a1c5d2fd4f41941ca868460e6
status is:FAILED
job id
is:jr_89c1a7b8ea045fac36d25733d7fc657d3560eb159e7e122a8960981dd225a9d0
status is:FAILED
job id
is:jr_87522bcb924e41a6cf0294185b0a09e46a4ff4c67db5007ff7c10f959836a44b
status is:FAILED
job id
is:jr_08bb54854c8e5c60e96a3e2bade1184963973c1ea7a1e760029e740d4c4c5d7d
status is:FAILED
job id
is:jr_540a90407bb7fbde72b3e1d6cbc98c3b246c21c87d836ff389491bf95520bb41
status is:FAILED
job id
is:jr_f27227cb16ec9d3df665d8753b09c2e2d24d5b5e5263f3d3f17a9bd4669bee67
status is:FAILED
job id
is:jr_a1ae4ad2edcbdac5c948b8be92a79a37c27517113364ddc88c8a93bc712fe6c1
status is:SUCCEEDED
SQL Tryit Editor v1.6

SELECT TOP 3 * FROM Customers;
​
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, Opera, and Edge(79).
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.
p5.js | setup() Function - GeeksforGeeks

23 Aug, 2019
The setup() function runs when the program starts. It is used to set the initial environment properties such as text-color, screen size, background-color and load the media file such as images and fonts. The program contains only one setup() function. The setup() function can not be called again after its initial execution.
Note: The variable declaration within setup() function can not be access by other functions including draw() function.
Syntax:
setup()
Below examples illustrate the setup() function in p5.js:
Example 1:
function setup() {           // Create Canvas of given size     createCanvas(400, 300);   }   function draw() {           background(220);           // Use color() function     let c = color('green');       // Use fill() function to fill color     fill(c);           // Draw a rectangle     rect(50, 50, 300, 200);       } 
Output:
Example 2:
function setup() {            // Create Canvas of given size     var cvs = createCanvas(600, 250);}   function draw() {         // Set the background color    background('green');          // Use createDiv() function to    // create a div element    var myDiv = createDiv('GeeksforGeeks');         var myDiv1 = createDiv('A computer science portal for geeks');         // Use child() function    myDiv.child(myDiv1);         // Set the position of div element    myDiv.position(150, 100);           myDiv.style('text-align', 'center');         // Set the font-size of text    myDiv.style('font-size', '24px');         // Set the font color    myDiv.style('color', 'white');   }
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Tryit Editor v3.7

CSS Style Images
Tryit: Create a responsive image
How to remove rows that contain NAs in R matrix?

To remove rows that contain NAs in R matrix, we can follow the below steps −
First of all, create a matrix.
First of all, create a matrix.
Then, use na.omit function to remove rows that contains NAs.
Then, use na.omit function to remove rows that contains NAs.
Let’s create a matrix as shown below −
M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)
M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
    [,1] [,2] [,3] [,4]
[1,]  4   4    2    NA
[2,]  4   NA   NA   4
[3,]  4   4    4    6
[4,]  4   3    4    3
[5,]  4   4    4    4
[6,]  4   4    4    4
[7,]  4   4    4    6
[8,]  NA  4    4    4
[9,]  4   4    2    4
[10,] 2   4    4    4
[11,] 6   4    NA   3
[12,] NA  3    4    4
[13,] 2   6    3    4
[14,] 4   4    4    NA
[15,] NA  4    4    4
[16,] 2   4    3    4
[17,] 4   2    4    4
[18,] 4   4    4    4
[19,] 4   4    NA   4
[20,] 4   4    4    4
[21,] 4   6    2    2
[22,] 3   4    2    4
[23,] 4   4    4    6
[24,] 4   NA   4    NA
[25,] NA  4    4    4
Remove rows that contains NAs
Using na.omit function to remove rows that contains NAs in matrix M −
M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)
M<-na.omit(M)
M
    [,1] [,2] [,3] [,4]
[1,]  4   4    4    6
[2,]  4   3    4    3
[3,]  4   4    4    4
[4,]  4   4    4    4
[5,]  4   4    4    6
[6,]  4   4    2    4
[7,]  2   4    4    4
[8,]  2   6    3    4
[9,]  2   4    3    4
[10,] 4   2    4    4
[11,] 4   4    4    4
[12,] 4   4    4    4
[13,] 4   6    2    2
[14,] 3   4    2    4
[15,] 4   4    4    6
attr(,"na.action")
[1] 8 12 15 25 2 24 11 19 1 14
attr(,"class")
[1] "omit"
How to create a linear model with interaction term only in R?

To create a linear model with interaction term only, we can use the interaction variable while creating the model. For example, if we have a data frame called df that has two independent variables say V1 and V2 and one dependent variable Y then the linear model with interaction term only can be created as lm(Y~V1:V2,data=df).
Consider the below data frame −
 Live Demo
x1<-rnorm(20,5,1.2)
x2<-rnorm(20,2,1.2)
y1<-rnorm(20,3,1.25)
df1<-data.frame(x1,x2,y1)
df1
     x1       x2         y1
1 4.442636  2.63714281  0.9120181
2 5.912804  1.72409663  2.2746513
3 7.881736  3.48780844  3.2675991
4 6.145395  1.51225991  3.2177194
5 6.303181  4.34733534  3.3361897
6 5.689431  0.08564247  2.0863346
7 6.008397  1.30221198  2.7183725
8 6.580716  1.45239970  4.0301650
9 4.000381  3.71539569  3.9404225
10 5.535338  3.48976926  4.9557343
11 5.968661  2.18208048  3.9992293
12 4.783326  -0.90756376 4.2661775
13 3.843528  -0.50299042 0.6496255
14 6.034803  1.06019093  5.2339701
15 4.177977  1.70476660  2.5932408
16 5.746300  0.85021792  3.0145627
17 4.658000  1.49894326  5.2826538
18 3.797983  0.46900834  3.6511403
19 5.415130  -0.31811078  2.6574529
20 4.709443  2.72001915  1.8893078
Creating linear model for y1 with interaction between x1 and x2 −
Model1<-lm(y1~x1:x2,data=df1)
summary(Model1)
Call −
lm(formula = y1 ~ x1:x2, data = df1)
Residuals −
Min 1Q Median 3Q Max
-2.3517 -0.6387 -0.1708 0.7321 2.1390
Coefficients −
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.96669 0.42803 6.931 1.77e-06 ***
x1:x2 0.02535 0.03434 0.738 0.47
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.299 on 18 degrees of freedom
Multiple R-squared: 0.02939, Adjusted R-squared: -0.02454
F-statistic: 0.545 on 1 and 18 DF, p-value: 0.4699
 Live Demo
v1<-rpois(20,2)
v2<-rpois(20,2)
v3<-rpois(20,2)
Response<-rpois(20,5)
df2<-data.frame(v1,v2,v3,Response)
df2
  v1 v2 v3 Response
1 2  2  4  10
2 1  1  2  2
3 3  4  3  4
4 2  1  2  5
5 0  0  2  4
6 0  2  1  5
7 1  3  0  5
8 0  0  1  6
9 1  3  1  6
10 3 0  2  6
11 2 1  0  3
12 1 3  1  2
13 2 1  3  5
14 0 1  0  8
15 0 3  1  4
16 1 0  3  2
17 3 1  3  2
18 0 4  1  9
19 1 2  3  9
20 3 2  0  9
Creating linear model for Response with interaction between v1, v2, and v3 −
Model2<-lm(Response~v1:v2+v2:v3+v1:v3+v1:v2:v3,data=df2)
summary(Model2)
Call −
lm(formula = Response ~ v1:v2 + v2:v3 + v1:v3 + v1:v2:v3, data = df2)
Residuals −
Min 1Q Median 3Q Max
-4.3677 -1.7339 -0.0289 1.7127 4.0160
Coefficients −
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.98404 1.21641 3.275 0.00511 **
v1:v2 0.31934 0.44221 0.722 0.48131
v2:v3 0.83716 0.46012 1.819 0.08886 .
v1:v3 0.02783 0.30125 0.092 0.92762
v1:v2:v3 -0.37123 0.28280 -1.313 0.20901
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.609 on 15 degrees of freedom
Multiple R-squared: 0.1907, Adjusted R-squared: -0.02517
F-statistic: 0.8834 on 4 and 15 DF, p-value: 0.4973
\hskip - Tex Command

\hskip - Used to create horizontal space.
{ \hskip }
\hskip command draws horizontal space.

w\hskip1em i\hskip2em d\hskip3em e\hskip4em r

wider



w\hskip1em i\hskip2em d\hskip3em e\hskip4em r

wider


w\hskip1em i\hskip2em d\hskip3em e\hskip4em r

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Math.Min() Method in C#

The Math.Min() method in C# is used to return the larger of two specified numbers. This method works for both the numbers being Double, Decimal, Int16, Int32, etc.
Following is the syntax −
public static ulong Min (ulong val1, ulong val2);
public static uint Min (uint val1, uint val2);
public static ushort Min (ushort val1, ushort val2);
public static float Min (float val1, float val2);
public static byte Min (byte val1, byte val2);
public static long Min (long val1, long val2);
Let us now see an example to implement Math.Min() method −
using System;
public class Demo {
   public static void Main(){
      byte val1 = 10, val2 = 15;
      decimal val3 = 1000M, val4 = 1500M;
      double val5 = 15.896745, val6 = 25.676843;
      short val7 = 20, val8 = 30;
      Console.WriteLine("Minimum Value from two byte values = "+Math.Min(val1, val2));
      Console.WriteLine("Minimum Value from two decimal values = "+Math.Min(val3, val4));
      Console.WriteLine("Minimum Value from two double values = "+Math.Min(val5, val6));
      Console.WriteLine("Minimum Value from two short values = "+Math.Min(val7, val8));
   }
}
This will produce the following output −
Minimum Value from two byte values = 10
Minimum Value from two decimal values = 1000
Minimum Value from two double values = 15.896745
Minimum Value from two short values = 20
Let us see another example to implement Math.Min() method −
using System;
public class Demo {
   public static void Main(){
      int val1 = 10, val2 = 15;
      float val3 = 12.8f, val4 = 25.6f;
      Console.WriteLine("Minimum Value from two int values = "+Math.Min(val1, val2));
      Console.WriteLine("Minimum Value from two float values = "+Math.Min(val3, val4));
   }
}
This will produce the following output &minuns;
Minimum Value from two int values = 10
Minimum Value from two float values = 12.8
What happens when we use COMMIT in MySQL stored procedure and one of the transaction, under START transaction, fails?

Suppose one of the queries fails or generates errors and another query (s) properly executed the MySQL still commit the changes of the properly executed query(s). It can be understood from the following example in which we are using the table ‘employee.tbl’ having the following data −
mysql> Select * from employee.tbl;
+----+---------+
| Id | Name    |
+----+---------+
| 1  | Mohan   |
| 2  | Gaurav  |
| 3  | Sohan   |
| 4  | Saurabh |
| 5  | Yash    |
+----+---------+
5 rows in set (0.00 sec)

mysql> Delimiter //

mysql> Create Procedure st_transaction_commit_save()
    -> BEGIN
    -> START TRANSACTION;
    -> INSERT INTO employee.tbl (name) values ('Rahul');
    -> UPDATE employee.tbl set name = 'Gurdas' WHERE id = 10;
    -> COMMIT;
    -> END //
Query OK, 0 rows affected (0.00 sec)
Now, when we invoke this procedure, we know that the UPDATE query will produce an error because we do not have id =10 on our table. But as the first query will execute successfully hence the COMMIT will save changes into the table.
mysql> Delimiter ;
mysql> Call st_transaction_commit_save()//
Query OK, 0 rows affected (0.07 sec)

mysql> Select * from employee.tbl;
+----+---------+
| Id | Name    |
+----+---------+
| 1  | Mohan   |
| 2  | Gaurav  |
| 3  | Sohan   |
| 4  | Saurabh |
| 5  | Yash    |
| 6  | Rahul   |
+----+---------+
6 rows in set (0.00 sec)
C program to calculate power of a given number

Take two integers from the user for base and exponent and calculate the power as explained below.
Consider the following for writing a C program.
Suppose base =3
Exponent = 4
Power=3*3*3*3
Follow the algorithm given below −
Step 1: Declare int and long variables.
Step 2: Enter base value through console.
Step 3: Enter exponent value through console.
Step 4: While loop.
Exponent !=0
   i. Value *=base
   ii. –exponent
Step 5: Print the result.
The following program explains how to calculate power of given number in C language.
#include<stdio.h>
int main(){
   int base, exponent;
   long value = 1;
   printf("Enter a base value:\n ");
   scanf("%d", &base);
   printf("Enter an exponent value: ");
   scanf("%d", &exponent);
   while (exponent != 0){
      value *= base;
      --exponent;
   }
   printf("result = %ld", value);
   return 0;
}
When the above program is executed, it produces the following result −
Run 1:
Enter a base value:
5
Enter an exponent value: 4
result = 625
Run 2:
Enter a base value:
8
Enter an exponent value: 3
result = 512
If we want to find the power of real numbers, we can use pow function which is a predefined function present in math.h.
#include<math.h>
#include<stdio.h>
int main() {
   double base, exponent, value;
   printf("Enter a base value: ");
   scanf("%lf", &base);
   printf("Enter an exponent value: ");
   scanf("%lf", &exponent);
   // calculates the power
   value = pow(base, exponent);
   printf("%.1lf^%.1lf = %.2lf", base, exponent, value);
   return 0;
}
When the above program is executed, it produces the following result −
Enter a base value: 3.4
Enter an exponent value: 2.3
3.4^2.3 = 16.69
Inserting data in table in SAP HANA

Like other database, you can insert rows in column based table in SAP HANA using Insert statement. Insert statement can be written in SQL editor in HANA.
To open SQL editor, you can select HANA system and click on SQL sign at top.
Below SQL statements can be used to insert the data −
INSERT INTO TEST.PROD_DESC VALUES (11,’E’,’Table’);
INSERT INTO TEST.PROD_DESC VALUES (11,’D’,’Chair’);
INSERT INTO TEST.PROD_DESC VALUES (14,’E’,’32 LED’);
INSERT INTO TEST.PROD_DESC VALUES (14,’D’,’32 inch LCD’);
INSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Comp Table’);
INSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Mixer’);
Class getEnumConstants() method in Java with Examples - GeeksforGeeks

27 Dec, 2019
The getEnumConstants() method of java.lang.Class class is used to get the Enum constants of this class. The method returns the Enum constants of this class in the form of an array of objects comprising the enum class represented by this class.
Syntax:
public T[] getEnumConstants()

Parameter: This method does not accepts any parameter
Return Value: This method returns the specified Enum constants of this class in the form of an array of Enum objects.
Below programs demonstrate the getEnumConstants() method.
Example 1:
// Java program to demonstrate// getEnumConstants() method  import java.util.*;  enum A {}  public class Test {      public Object obj;      public static void main(String[] args)    {          // returns the Class object for this class        Class myClass = A.class;          System.out.println("Class represented by myClass: "                           + myClass.toString());          // Get the Enum constants of myClass        // using getEnumConstants() method        System.out.println(            "Enum constants of myClass: "            + Arrays.toString(                  myClass.getEnumConstants()));    }}
Class represented by myClass: class A
Enum constants of myClass: []

Example 2:
// Java program to demonstrate// getEnumConstants() method  import java.util.*;  enum A {    RED,    GREEN,    BLUE;}  class Main {      private Object obj;      public static void main(String[] args)    {          try {              // returns the Class object for this class            Class myClass = A.class;              System.out.println("Class represented by myClass: "                               + myClass.toString());              // Get the Enum constants of myClass            // using getEnumConstants() method            System.out.println(                "Enum constants of myClass: "                + Arrays.toString(                      myClass.getEnumConstants()));        }        catch (Exception e) {            System.out.println(e);        }    }}
Class represented by myClass: class A
Enum constants of myClass: [RED, GREEN, BLUE]

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnumConstants–
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
C# - Param Arrays

At times, while declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into help at such times.
The following example demonstrates this −
using System;

namespace ArrayApplication {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;
         
         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }
   class TestClass {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(512, 720, 250, 567, 889);
         
         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
The sum is: 2938


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
JSTL - fn:substringBefore() Function

The fn:substringBefore() function returns the part of a string before a specified substring.
The fn:substringBefore() function has the following syntax −
java.lang.String substringBefore(java.lang.String, java.lang.String)

Following example explains the functionality of the fn:substringBefore() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

<html>
   <head>
      <title>Using JSTL Functions</title>
   </head>

   <body>
      <c:set var = "string1" value = "This is first String."/>
      <c:set var = "string2" value = "${fn:substringBefore(string1, 'first')}" />
      <p>Final sub string : ${string2}</p>
   </body>
</html>
You will receive the following result −
Final sub string : This is 


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Swift - Switch Statement

A switch statement in Swift completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases like it happens in C and C++ programing languages. Following is a generic syntax of switch statement in C and C++ −
switch(expression) {
   case constant-expression  :
      statement(s);
      break; /* optional */
   case constant-expression  :
      statement(s);
      break; /* optional */
  
   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

Here we need to use break statement to come out of a case statement otherwise execution control will fall through the subsequent case statements available below to matching case statement.
Following is a generic syntax of switch statement available in Swift −
switch expression {
   case expression1  :
      statement(s)
      fallthrough /* optional */
   case expression2, expression3  :
      statement(s)
      fallthrough /* optional */
  
   default : /* Optional */
      statement(s);
}

If we do not use fallthrough statement, then the program will come out of switch statement after executing the matching case statement. We will take the following two examples to make its functionality clear.
Following is an example of switch statement in Swift programming without using fallthrough −
import Cocoa

var index = 10

switch index {
   case 100  :
      println( "Value of index is 100")
   case 10,15  :
      println( "Value of index is either 10 or 15")
   case 5  :
      println( "Value of index is 5")
   default :
      println( "default case")
}
When the above code is compiled and executed, it produces the following result −
Value of index is either 10 or 15

Following is an example of switch statement in Swift programming with fallthrough −
import Cocoa

var index = 10

switch index {
   case 100  :
      println( "Value of index is 100")
      fallthrough
   case 10,15  :
      println( "Value of index is either 10 or 15")
      fallthrough
   case 5  :
      println( "Value of index is 5")
   default :
      println( "default case")
}
When the above code is compiled and executed, it produces the following result −
Value of index is either 10 or 15
Value of index is 5


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
Balanced Binary Tree in Python

In a binary tree, each node contains two children, i.e left child and right child. Let us suppose we have a binary tree and we need to check if the tree is balanced or not. A Binary tree is said to be balanced if the difference of height of left subtree and right subtree is less than or equal to '1'.
Example
Input-1: 
Output:
True
Explanation:
The given binary tree is [1,2,3, NULL, NULL, 6, 7]. The height difference of its left subtree and right subtree is equal to '1', thus it is a height Balanced tree.
Input-2: 
              
Output:
False
Explanation:
The given binary tree is [1,2,3,4, NULL, NULL,NULL,5]. The height difference of its left subtree and right subtree is greater than '1', thus it is not a height balanced tree. 
The recursive approach to solve this problem is to find the height of the left subtree and the right subtree and then check if (height(leftsubstree) - height(rightsubtree) <= 1) and return True or False accordingly. Then, we will check recursively for each node of the binary tree.
Take input of nodes of a Binary Tree.
Define a function to find the height of the tree.
A Boolean function to check recursively if the height difference of left subtree and right subtree is not more than '1', then return True.
Return the Result.
Live Demo
class treenode:
   def __init__(self, data):
      self.data = data
      self.left = self.right = None
# funtion to find the height of the left subtree and right subtree
class height:
   def __init__(self):
      self.height = 0
# function to check if the tree is balanced or not
def isBalanced(root):
   lh = height()
   rh = height()
   if root is None:
      return True
   return (
      (abs(lh.height - rh.height) <= 1)
      and isBalanced(root.left)
      and isBalanced(root.right)
   )
root = treenode(1)
root.left = treenode(2)
root.right = treenode(3)
root.left.left = None
root.left.right = None
root.right.left = treenode(6)
root.right.right = treenode(7)
if isBalanced(root):
   print("Balanced")
else:
   print("Not Balanced")
Running the above code will generate the output as,
Balanced
The given binary tree [1, 2, 3, NULL, NULL, 6, 7]. The height difference of its left subtree and right subtree is equal to '1', thus it is a height Balanced tree.
Rank function in MySQL?

The rank() function can be used to give a rank for every row within the partition of a result set.
First, let us create a table −
mysql> create table RankDemo
   mysql> (
   mysql> id int
   mysql> );
Query OK, 0 rows affected (0.53 sec)
Inserting records into table.
mysql> insert into RankDemo values(1);
Query OK, 1 row affected (0.19 sec)

mysql>  insert into RankDemo values(3);
Query OK, 1 row affected (0.12 sec)

mysql>  insert into RankDemo values(3);
Query OK, 1 row affected (0.11 sec)

mysql>  insert into RankDemo values(4);
Query OK, 1 row affected (0.12 sec)

mysql>  insert into RankDemo values(5);
Query OK, 1 row affected (0.17 sec)
Displaying all records from the table with the help of select statement. The query is as follows −
mysql> select *from RankDemo;
The following is the output.
+------+
| id   |
+------+
|    1 |
|    3 |
|    3 |
|    4 |
|    5 |
+------+
5 rows in set (0.00 sec)

Let us now apply the rank() function as I have discussed above.
mysql> SELECT
   mysql> id,RANK() OVER (ORDER BY id ) Ranking
   mysql> from RankDemo;
The following is the output that displays the rank.
+------+---------+
| id   | Ranking |
+------+---------+
|    1 |       1 |
|    3 |       2 |
|    3 |       2 |
|    4 |       4 |
|    5 |       5 |
+------+---------+
5 rows in set (0.04 sec)
Playit

#myDIV {  background-color:lightblue;  transform:scale(1.1);}
Python - cmath.polar() function - GeeksforGeeks

28 May, 2020
cMath module contains a number of functions which is used for mathematical operations for complex numbers. The cmath.polar() function is used to convert a complex number to polar coordinates. The value passed in this function can be int, float, and complex numbers.
Syntax: cmath.polar(x)
Parameter:This method accepts the following parameters.
x :This parameter is the number to find polar coordinates of.
Returns:This method returns a tuple value that represent the polar coordinates.
Below examples illustrate the use of above function:
Example #1 : 
Python3
# Python code to implement# the polar()function        # importing "cmath"# for mathematical operations  import cmath     # using cmath.polar() method val = cmath.polar(1) print(val)
Output:
(1.0, 0.0)
Example 2:
Python3
# Python code to implement# the polar()function        # importing "cmath"# for mathematical operations  import cmath     # using cmath.polar() method val = cmath.polar(2 + 4j)print(val)
Output:
(4.47213595499958, 1.1071487177940904)
Python Cmath-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
arc function in C - GeeksforGeeks

23 May, 2019
The header file graphics.h contains arc() function which draws an arc with center at (x, y) and given radius. start_angle is the starting point of angle and end_angle is the ending point of the angle. The value of the angle can vary from 0 to 360 degree.
Syntax :
void arc(int x, int y, int start_angle,
            int end_angle, int radius);

where,
(x, y) is the center of the arc.
start_angle is the starting angle and 
end_angle is the ending angle.
'radius' is the Radius of the arc.

Examples :
Input : x=250, y=250, start_angle = 155, end_angle = 300, radius = 100
Output :


Input : x=250, y=250, start_angle = 0, end_angle = 300, radius = 100;
Output :


Below is the implementation of arc() function :
// C implementation of arc function#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // location of the arc    int x = 250;    int y = 250;      // starting angle and ending angle    // of the arc    int start_angle = 155;    int end_angle = 300;      // radius of the arc    int radius = 100;      // initgraph initializes the graphics system    // by loading a graphics driver from disk    initgraph(&gd, &gm, "");      // arc function    arc(x, y, start_angle, end_angle, radius);      getch();      // closegraph function closes the graphics    // mode and deallocates all memory allocated    // by graphics system    closegraph();      return 0;}
Output:


Kirti_Mangal
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Understanding "extern" keyword in C
Storage Classes in C
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++
Python List sort() Method

Python list method sort() sorts objects of list, use compare func if given.
Following is the syntax for sort() method −
list.sort([func])

NA
NA
This method does not return any value but it changes from the original list.
The following example shows the usage of sort() method.
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print "List : ", aList
When we run above program, it produces following result −
List :  [123, 'abc', 'xyz', 'xyz', 'zara']


    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
GATE | GATE CS 1997 | Question 40 - GeeksforGeeks

20 Nov, 2018
Consider a logic circuit shown in figure below. The functions f1,f2 and f (in canonical sum of products form in decimal notation) are :f1(w,x,y,z) = ∑ 8,9,10f2(w,x,y,z) = ∑ 7,8,12,13,14,15f(w,x,y,z)  = ∑ 8,9
The Function f3 is
a. ∑9,10
b. ∑9
c. ∑1,8,9
d. ∑8,10,15
(A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this Question
GATE CS 1997
GATE-GATE CS 1997
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90