code-rag-bench/online-tutorials huggingface dataset:
NumPy - Fibonacci Series using Binet Formula - GeeksforGeeks

03 Jun, 2020
All of us are familiar with Fibonacci Series. Each number in the sequence is the sum of the two numbers that precede it. So, the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...... In this tutorial, we will implement the same using NumPy with the aid of Binet formula.
Binet Formula
‘n’ is the parameter which relates the first ‘n’ numbers of Fibonacci Series. In the first example we are going to findout first 10 numbers of Fibonacci Series (n = 10), after that we takes the parameter ‘n’ from user and produce the corresponding result.
NOTE : We are ignoring the first element(0) of Fibonacci Series
Example 1: To find first 10 Fibonacci numbers .
import numpy as np   # We are creating an array contains n = 10 elements# for getting first 10 Fibonacci numbersa = np.arange(1, 11)lengthA = len(a)  # splitting of terms for easinesssqrtFive = np.sqrt(5)alpha = (1 + sqrtFive) / 2beta = (1 - sqrtFive) / 2  # Implementation of formula# np.rint is used for rounding off to integerFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrtFive))print("The first {} numbers of Fibonacci series are {} . ".format(lengthA, Fn))
Output :
The first 10 numbers of Fibonacci series are [ 1. 1. 2. 3. 5. 8. 13. 21. 34. 55.] .
Example 2 : To find first ‘n’ Fibonacci numbers ..
import numpy as np  # We are creating an array contains n elements# for getting first 'n' Fibonacci numbersfNumber = int(input("Enter the value of n + 1'th number : "))a = np.arange(1, fNumber)length_a = len(a)  # splitting of terms for easinesssqrt_five = np.sqrt(5)alpha = (1 + sqrt_five) / 2beta = (1 - sqrt_five) / 2  # Implementation of formula# np.rint is used for rounding off to integerFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrt_five))print("The first {} numbers of Fibonacci series are {} . ".format(length_a, Fn))
Output :
# Here user input was 10
Enter the value of n+1'th number :10
The first 9 numbers of Fibonacci series are [ 1.  1.  2.  3.  5.  8. 13. 21. 34.] . 
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
GATE | GATE-CS-2002 | Question 50 - GeeksforGeeks

05 Dec, 2018
Consider the following logic circuit whose inputs and function and output is f.
Given that
f1(dx, y, z) = ∑(0, 1, 3, 5),
f2(dx, y, z) = ∑(6, 7) and
f(dx, y, z) = ∑(1, 4, 5),
f3 is :(A) ∑(1, 4, 5)(B) ∑(6, 7)(C) ∑(0, 1, 3, 5)(D) None of theseAnswer: (A)Explanation: Function f will be:
f = ((f1f2)′(f3)')′ = (f1f2) + f3
Since AND of two expressions will contain the common terms and f1 and f2 don’t have any common term, so f1f2 is 0 and hence f = f3 = Σ(1,4,5).
Option (A) is correct.Quiz of this Question
GATE-CS-2002
GATE-GATE-CS-2002
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-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
PHP | array_reduce() Function - GeeksforGeeks

29 May, 2021
This inbuilt function of PHP is used to reduce the elements of an array into a single value that can be of float, integer or string value. The function uses a user-defined callback function to reduce the input array.
Syntax: 
array_reduce($array, own_function, $initial)
Parameters: The function takes three arguments and are described below:  
$array (mandatory): This is a mandatory parameter and refers to the original array from which we need to reduce.own_function (mandatory): This parameter is also mandatory and refers to the user-defined function that is used to hold the value of the $array$initial (optional): This parameter is optional and refers to the value to be sent to the function.
$array (mandatory): This is a mandatory parameter and refers to the original array from which we need to reduce.
own_function (mandatory): This parameter is also mandatory and refers to the user-defined function that is used to hold the value of the $array
$initial (optional): This parameter is optional and refers to the value to be sent to the function.
Return Value: This function returns the reduced result. It can be of any type int, float or string.
Examples:  
Input : $array = (15, 120, 45, 78)
        $initial = 25
        own_function() takes two parameters and concatenates 
        them with "and" as a separator in between
Output : 25 and 15 and 120 and 45 and 78

Input : $array = array(2, 4, 5);
        $initial = 1
        own_function() takes two parameters 
        and multiplies them.
Output : 40
In this program, we will see how an array of integer elements is reduced to a single string value. We also passed the initial element of our choice. 
PHP
<?php// PHP function to illustrate the use of array_reduce()function own_function($element1, $element2){    return $element1 . " and " . $element2;} $array = array(15, 120, 45, 78);print_r(array_reduce($array, "own_function", "Initial"));?>
Output: 
Initial and 15 and 120 and 45 and 78
In the below program, the array_reduce reduces the given array to the product of all the elements of the array using the own_function(). 
PHP
<?php// PHP function to illustrate the use of array_reduce()function own_function($element1, $element2){    $element1 = $element1 * $element2;    return $element1;} $array = array(2, 4, 5, 10, 100);print_r(array_reduce($array, "own_function", "2"));?>
Output: 
80000
Reference: http://php.net/manual/en/function.array-reduce.php 
sweetyty
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to match a particular word in a string using Pattern class in Java?

The \b meta character in Java regular expressions matches the word boundaries Therefore to find a particular word from the given input text specify the required word within the word boundaries in the regular expressions as −
"\\brequired word\\b";
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MachingWordExample1 {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.next();
      //Regular expression to find digits
      String regex = "\\bhello\\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}
Enter input string
hello welcome to Tutorialspoint
Match found
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample2 {
   public static void main( String args[] ) {
      String input = "This is sample text \n " + "This is second line " + "This is third line";
      String regex = "\\bsecond\\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}
Match found
Decimal.Truncate() Method in C#

The Decimal.Truncate() method in C# is used to return the integral digits of the specified Decimal. Remember, any fractional digits are discarded.
Following is the syntax −
public static decimal Truncate (decimal val);
Above, Val is the decimal number to truncate.
Let us now see an example to implement the Decimal.Truncate() method −
using System;
public class Demo {
   public static void Main(){
      Decimal val = 6576.876m;
      Console.WriteLine("Decimal value = "+val);
      ulong res = Decimal.ToUInt64(val);
      Console.WriteLine("64-bit unsigned integer = "+res);
      Decimal val2 = Decimal.Truncate(val);
      Console.WriteLine("Integral digits of the decimal = "+val2);
   }
}
This will produce the following output −
Decimal value = 6576.876
64-bit unsigned integer = 6576
Integral digits of the decimal = 6576
Let us now see another example to implement the Decimal.Truncate() method −
using System;
public class Demo {
   public static void Main(){
      Decimal val = 28676.935m;
      Console.WriteLine("Decimal value = "+val);
      Decimal val2 = Decimal.Truncate(val);
      Console.WriteLine("Integral digits of the decimal = "+val2);
   }
}
This will produce the following output −
Decimal value = 28676.935
Integral digits of the decimal = 28676
HTML | body text Attribute - GeeksforGeeks

25 Mar, 2022
The HTML <body> text Attribute is used to define a color for the text in the Document. Note: The <body> text attribute is not supported by HTML5.  Instead of using this attribute, we can use css color property. 
Syntax:  
<body text="color_name | hex_number | rgb_number">
Attribute Values  
color_name: It specify the name of the color for the text in the Document.
hex_number: It specify the hex code of the color of the Text in the Document.
rgb_number: It specify the rgb value of the Text in the Document
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML body Text Attribute</title></head> <!-- body tag starts here --> <body text="green">    <center>        <h1>GeeksforGeeks</h1>        <h2>HTML <body> Text Attribute</h2>           <p>It is a Computer Science portal For Geeks</p>       </center></body><!-- body tag ends here --> </html>
Output:  
Supported Browsers: The browser supported by <body> Text Attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
GATE | GATE-CS-2000 | Question 17 - GeeksforGeeks

28 Jun, 2021
Consider the following C declaration
struct {    short s [5]    union {         float y;         long z;    }u;} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is
(A) 22 bytes(B) 14 bytes(C) 18 bytes(D) 10 bytesAnswer: (C)Explanation: See question 3 of https://www.geeksforgeeks.org/c-language-set-1/Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
Minimum Size Subarray Sum in C++

Suppose we have an array of n elements, and a positive integer s. We have to find the minimal length of a contiguous subarray, of which the sum is greater or equal to s. If there isn’t one,then return 0 instead. So if the array is like [2,3,1,2,3,4] and sum is 7, then the output will be 2. This is the subarray [4,3] has the minimum length for this case.
To solve this, we will follow these steps −
ans := 0, n := size of array A, j := 0 and sum := 0
ans := 0, n := size of array A, j := 0 and sum := 0
for i in range 0 to n – 1sum := sum + A[i]while sum – A[i] >= K and j <= 1sum := sum – A[j]increase j by 1if sum >= k, thenif ans = 0 or ans > (i – j + 1), then ans := (i – j + 1)
for i in range 0 to n – 1
sum := sum + A[i]
sum := sum + A[i]
while sum – A[i] >= K and j <= 1sum := sum – A[j]increase j by 1
while sum – A[i] >= K and j <= 1
sum := sum – A[j]
sum := sum – A[j]
increase j by 1
increase j by 1
if sum >= k, thenif ans = 0 or ans > (i – j + 1), then ans := (i – j + 1)
if sum >= k, then
if ans = 0 or ans > (i – j + 1), then ans := (i – j + 1)
if ans = 0 or ans > (i – j + 1), then ans := (i – j + 1)
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minSubArrayLen(int K, vector<int>& A) {
      int ans = 0;
      int n = A.size();
      int j = 0;
      int sum = 0;
      for(int i = 0; i < n; i++){
         sum += A[i];
         while(sum - A[j] >= K && j <= i){
            sum -= A[j];
            j++;
         }
         if(sum >= K){
            if(ans == 0 || ans > (i - j + 1)) ans = (i - j + 1);
         }
      }
   return ans;
   }
};
main(){
   vector<int> v = {2,3,1,2,4,3};
   Solution ob;
   cout << ((ob.minSubArrayLen(7,v)));
}
7
[2,3,1,2,4,3]
2
Unix / Linux Shell - The if...fi statement

The if...fi statement is the fundamental control statement that allows Shell to make decisions and execute statements conditionally.
if [ expression ] 
then 
   Statement(s) to be executed if expression is true 
fi

The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false then no statement would be executed. Most of the times, comparison operators are used for making decisions.
It is recommended to be careful with the spaces between braces and expression. No space produces a syntax error.
If expression is a shell command, then it will be assumed true if it returns 0 after execution. If it is a Boolean expression, then it would be true if it returns true.
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
fi

if [ $a != $b ]
then
   echo "a is not equal to b"
fi
The above script will generate the following result −
a is not equal to b


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
ioprio_set() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
int ioprio_get(int which, int who); 
int ioprio_set(int which, int who, int ioprio); 


The
which and
who arguments identify the process(es) on which the system
calls operate.
The
which argument determines how
who is interpreted, and has one of the following values:


The
ioprio argument given to
ioprio_set() is a bit mask that specifies both the scheduling class and the
priority to be assigned to the target process(es).
The following macros are used for assembling and dissecting
ioprio values:


I/O priorities are supported for reads and for synchronous (O_DIRECT,
O_SYNC) writes.
I/O priorities are not supported for asynchronous
writes because they are issued outside the context of the program
dirtying the memory, and thus program-specific priorities do not apply.


On success,
ioprio_set() returns 0.
On error, -1 is returned, and
errno is set to indicate the error.


These system calls only have an effect when used
in conjunction with an I/O scheduler that supports I/O priorities.
As at kernel 2.6.17 the only such scheduler is the Completely Fair Queuing
(CFQ) I/O scheduler.


One can view the current I/O scheduler via the
/sys file system.
For example, the following command
displays a list of all schedulers currently loaded in the kernel:



$ cat /sys/block/hda/queue/scheduler
noop anticipatory deadline [cfq]


The scheduler surrounded by brackets is the one actually
in use for the device
(hda in the example).
Setting another scheduler is done by writing the name of the
new scheduler to this file.
For example, the following command will set the
scheduler for the
hda device to
cfq: 


$ su
Password:
# echo cfq > /sys/block/hda/queue/scheduler


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
chfn command in Linux with examples - GeeksforGeeks

15 May, 2019
chfn command in Linux allows you to change a user’s name and other details easily. chfn stands for Change finger. Basically, it is used to modify your finger information on Linux system. This information is generally stored in the file /etc/passwd that includes user’s original name, work phone number etc.
Syntax:
chfn [option] [login] 
Example: In this example we used default “chfn” command without any option. In this system asks from the user itself to change the values of some basic attributes.
Options:
-f full_name : Let you change the full name on the account.
-w work_ph : Let you change the work phone number on the account.
-r room_no : Let you change the room number on the account.
-h home_ph : Let you change the home phone number on the account.
-o other : Let you change any other detail on the account.
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Loading a csv file into Azure SQL Database from Azure Storage | by Mayank Srivastava | Towards Data Science

Over the weekend, I wanted to do a quick proof of concept on certain capabilities of Databricks and I wanted to use Azure SQL as a source. I faced quite bit of challenges and google was not kind enough to provide me a solution. I tried everything from bcp to bulk insert the file on my local computer and somehow it came out with errors which failed to fix.
Finally I managed to load the csv file into database and thought of sharing this with everyone, so that if you have to quickly load data into Azure SQL Database and you don’t want to write a script in Databricks or use Azure Data Factory for such a simple task. And before you move ahead, I am assuming that you have a fair understanding of the Azure ecosystem particularly the Storage Account.
So first things first, upload the file, you want to load into Azure SQL database, to a container in Azure Storage Account. You can use the normal Blob container and don’t have to use Azure Data Lake Storage for this.
Second, you need to create a Shared Access Signature for the storage account
Now go to the Azure SQL Database, where you would like to load the csv file and execute the following lines. Please replace the secret with the secret you have generated in the previous step. Also, please make sure you replace the location of the blob storage with the one you
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'YourStrongPassword1';CREATE DATABASE SCOPED CREDENTIAL MyAzureBlobStorageCredentialWITH IDENTITY = 'SHARED ACCESS SIGNATURE',SECRET = '******srt=sco&sp=rwac&se=2017–02–01T00:55:34Z&st=2016–12–29T16:55:34Z***************';NOTE: Make sure that you don't have a leading ? in SAS token, and that you have at least read permission on the object that should be loaded srt=o&sp=r, and expiration period is valid (all dates are in UTC time)CREATE EXTERNAL DATA SOURCE MyAzureBlobStorageWITH ( TYPE = BLOB_STORAGE,LOCATION = 'https://****************.blob.core.windows.net/adventureworks' , CREDENTIAL= MyAzureBlobStorageCredential
Once you have done the above steps, you are left with only one last step and that is to insert the file into the table. Please remember to create the table in the database before you load the file and also remember to keep the schema of table exactly as the file structure, else you might run into errors. And the last step is
BULK INSERT [dbo].[lnd_lending_club_acc_loans] FROM 'accepted_2007_to_2018Q4.csv'WITH (    CHECK_CONSTRAINTS,    DATA_SOURCE = 'MyAzureBlobStorage',    DATAFILETYPE='char',    FIELDTERMINATOR=',',    ROWTERMINATOR='0x0a', FIRSTROW=3,    KEEPIDENTITY,    TABLOCK);
And if you have done everything correct, you can expect the table to be loaded with the data in the csv file. There are many other ways of doing this, but this one worked for me and was quite quick.
How to create a dynamic 2D array in Java?

If you wish to create a dynamic 2d array in Java without using List. And only create a dynamic 2d array in Java with normal array then click the below link
You can achieve the same using List. See the below program. You can have any number of rows or columns.
import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      List<int[]> rows = new ArrayList<>();
      rows.add(new int[]{1,2,3});
      rows.add(new int[]{1,2});
      rows.add(new int[]{1});
      //get element at row : 0, column : 0
      System.out.println("[0][0] : " + rows.get(0)[0]);
      //get element at row : 1, column : 1
     System.out.println("[1][1] : " + rows.get(1)[1]);
   }
}
[0][0] : 1
[1][1] : 2
How to execute a particular test method multiple times (say 5 times) in
TestNG?

We can execute a particular test method multiple times (say 5 times) with the help of the invocationCount helper attribute.
@Test
public void PaymentDetails(){
   System.out.println("Payment details validation is successful”);
}
@Test(invocationCount=5)
public void LoginAdmin(){
   System.out.println("Login in admin is successful”);
}
@Test
public void LeaseDetails(){
   System.out.println("Lease details verification is successful”);
}
In the Java class file, the LoginAdmin() method with invocationCount set to 5 will result in Login in admin is a successful message to be printed five times on the console.
Ternary Operators in C/C++

The operators, which require three operands to act upon, are known as ternary operators. It can be represented by “ ? : ”. It is also known as conditional operator. The operator improves the performance and reduces the line of code.
Here is the syntax of ternary operator in C language,
Expression1 ? Expression2 : Expression3
Here is an example of Ternary Operators in C language,
 Live Demo
#include <stdio.h>
int main() {
   int a = -1;
   double b = 26.4231;
   int c = a? printf("True value : %lf",b):printf("False value : 0");
   return 0;
}
True value : 26.423100
Expression1 will evaluate always while expression2 & expression3 are dependent on the outcome of expression1. If the outcome of expression1 is non-zero or negative, expression2 will display, otherwise expression3 will display.
The ternary operator has a return type. The return type depends on expression2 and also on the convertibility of expression3 to expression2. If they are not convertible, the compiler will throw an error.
Here is another example of ternary operator in C language,
 Live Demo
#include <stdio.h>
int main() {
   int x = -1, y = 3;
   double b = x+y+0.5;
   int c = x<y? printf("True value : %lf",b):printf("False value : 0");
   return 0;
}
True value : 2.500000
Best Time to Buy and Sell Stock II in Python

Suppose we have an array A, here A[i] is indicating the price of a given stock on day i. We have to find the maximum profit. We can complete as many transactions as we like. (Transaction means to buy and sell stocks). But we have to keep in mind that we may not engage in multiple transactions at the same time. So we have to sell the stock before buying the new one.
Suppose the array is like A = [7, 1, 5, 3, 6, 4], then the result will be 7. As we can see, if we buy on day 2 (index 1), then it will take 1 as a buying price. Then if we sell on day 3, the profit will be 5 – 1 = 4. Then buy on day 4, and sell on day 5, so profit will be 6 – 3 = 3
To solve this, follow these steps −
let answer = 0
for i in range 0 to n – 1 (n is the number of elements in A) −if A[i] – A[i – 1] > 0, thenanswer := answer + A[i] – A[i – 1]
if A[i] – A[i – 1] > 0, thenanswer := answer + A[i] – A[i – 1]
answer := answer + A[i] – A[i – 1]
return answer
Let us see the implementation to get a better understanding
 Live Demo
class Solution(object):
   def maxProfit(self, prices):
      """
      :type prices: List[int]
      :rtype: int
      """
      ans = 0
      for i in range(1,len(prices)):
         if prices[i] - prices[i-1] >0:
            ans+=(prices[i] - prices[i-1])
      return ans
ob1 = Solution()
print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))
print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))
13
How can I find the index of a 2d array of objects in JavaScript?

To find the index of a two-dimensional array of objects, use two for loops, one for row and another for column. Following is the code −
function matrixIndexed(details, name) {
   var r;
   var c;
   for (r = 0; r < details.length; ++r) {
      const nsDetails = details[r];
      for (c = 0; c < nsDetails.length; ++c) {
         const tempObject = nsDetails[c];
         if (tempObject.studentName === name) {
            return { r, c};
         }
      }
   }
   return {};
}
const details = [
   [
      {studentName: 'John'}, {studentName:'David'}
   ],
   [
      {studentName:"Mike"},{studentName:'Bob'},{studentName:'Carol'}
   ]
];
var {r, c } = matrixIndexed(details, 'Bob');
console.log(r, c);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo160.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo160.js
1 1
MySQL - SET autocommit Statement

The COMMIT statement saves all the modifications made in the current. If you commit a database, it saves all the changes that have been done till that particular point. By default, the MySQL database commits/saves the changes done automatically.
You can turn off/on the auto-commit using the SET autocommit statement.
Following is the syntax of the SET autocommit statement −
SET autocommit=0;

MySQL saves the changes done after the execution of each statement. To save changes automatically, set the autocommit option as shown below −
SET autocommit=0;

Assume we have created a table in MySQL with name EMPLOYEES as shown below −
mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT);
Query OK, 0 rows affected (0.36 sec)
Following query saves the changes −
mysql> COMMIT;
Query OK, 0 rows affected (0.35 sec)
Let us insert 4 records in to it using INSERT statements as −
mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000); 
Query OK, 4 rows affected (0.17 sec)
Records: 4 Duplicates: 0 Warnings: 0
Now, update the age of the employees by one year −
mysql> UPDATE EMPLOYEE SET AGE = AGE + 1;
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
If you retrieve the contents of the table, you can see the updated values as −
mysql> select * from EMPLOYEE;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 20   | M    | 2000   |
| Raj        | Kandukuri | 21   | M    | 7000   |
| Ramya      | Ramapriya | 26   | F    | 5000   |
| Mac        | Mohan     | 27   | M    | 2000   |
+------------+-----------+------+------+--------+
4 rows in set (0.09 sec)
Following statement reverts the changes after the last commit.
mysql> ROLLBACK;
Query OK, 0 rows affected (0.00 sec)
Since we have executed the COMMIT statement before inserting records if you verify the contents of the EMPLOYEE table, you will get an empty set as follow −
mysql> SELECT * FROM EMPLOYEE;
Empty set (0.06 sec)


    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Generating random hex color in JavaScript

We are required to write a JavaScript function randomColor that returns a randomly generated
hex color every time it is called.
Therefore, let’s write the code for this function −
The code for this will be −
const randomColor = () => {
   let color = '#';
   for (let i = 0; i < 6; i++){
      const random = Math.random();
      const bit = (random * 16) | 0;
      color += (bit).toString(16);
   };
   return color;
};
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
The output in the console will be −
#762b46
#cfa0bf
#a20ee1
#c2f7e0
#5d5822
#380f30
#805408
Rename multiple files using Python

rename() method is used to rename a file or directory in Python3. The rename() method is a part of the os module.
os.rename(src, dst)

The first argument is src which is source address of file to be renamed and second argument dstwhich is the destination with the new name.
Let's take any directory which has one image folder. Here we have this image folder.
import os
# Function to rename multiple files
def main():
   i = 0
   path="C:/Users/TP/Desktop/sample/Travel/west bengal/bishnupur/"
   for filename in os.listdir(path):
      my_dest ="soul" + str(i) + ".jpg"
      my_source =path + filename
      my_dest =path + my_dest
      # rename() function will
      # rename all the files
      os.rename(my_source, my_dest)
      i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()
CSS Margin Collapse

Sometimes two margins collapse into a single margin.
Top and bottom margins of elements are sometimes collapsed into a single 
margin that is equal to the largest of the two margins.
This does not happen on left and right margins! Only top and bottom margins!
Look at the following example:
Demonstration of margin collapse: 
In the example above, the <h1> element has a bottom margin of 50px and 
the <h2> 
element has a top margin set to 20px.
Common sense would seem to suggest that the vertical margin between the <h1> 
and the <h2> would be a total of 70px (50px + 20px). But due to margin collapse, 
the actual margin ends up being 50px.
Add a 20 pixels left margin to the <h1> element.
<style>
h1 {
  : 20px;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <p>This is a paragraph</p>
</body>

Start the Exercise
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.
Node.js – util.inherits() Method

The util.inherits() method basically inherits the methods from one construct to another. This prototype will be set to a new object to that from the superConstructor.
By doing this, we can mainly add some validations to the top of Object.setPrototypeOf(constructor.prototype, superConstructor.prototype).
util.inherits(constructor, superConstructor)
The parameters are described below -
constructor − This is a function type input that holds the prototype for constructor the user wants to be inherited.
superConstructor − This is the function that will be used for adding and validating the input validations.
Create a file "inherits.js" and copy the following code snippet. After creating the file, use the command "node inherits.js" to run this code.
 Live Demo
// util.inherit() example

// Importing the util module
const util = require('util');
const EventEmitter = require('events');

// Defining the constructor below
function Stream() {
   EventEmitter.call(this);
}

// Inheriting the stream constructor
util.inherits(Stream, EventEmitter);

// Creating the prototype for the constructor with some data
   Stream.prototype.write = function(data) {
   this.emit('data', data);
};

// Creating a new stream constructor
const stream = new Stream();

// Checking if stream is instanceOf EventEmitter
console.log(stream instanceof EventEmitter); // true
console.log(Stream.super_ === EventEmitter); // true

// Printing the data
stream.on('data', (data) => {
   console.log(`Data Received: "${data}"`);
});
// Passing the data in stream
stream.write('Its working... Created the constructor prototype!');
C:\home\node>> node inherits.js
true
true
Dta Received: "It's working... Created the constructor prototype!"
Let’s have a look at one more example
 Live Demo
// util.inherits() example

// Importing the util & events module
const util = require('util');
const { inspect } = require('util');
const emitEvent = require('events');

// Definging the class to emit stream data
class streamData extends emitEvent {
write(stream_data) {
   // This will emit the data stream
   this.emit('stream_data', stream_data);
   }
}

// Creating a new instance of the stream
const manageStream = new streamData('default');
console.log("1.", inspect(manageStream, false, 0, true))
console.log("2.", streamData)

manageStream.on('stream_data', (stream_data) => {
   // Prints the write statement after streaming
   console.log("3.", `Data Stream Received: "${stream_data}"`);
});

// Write on console
manageStream.write('Inheriting the constructor & checking from superConstructor');
C:\home\node>> node inherits.js
1. streamData {
   _events: [Object: null prototype] {},
   _eventsCount: 0,
   _maxListeners: undefined,
   [Symbol(kCapture)]: false
}
2. [class streamData extends EventEmitter]
3. Data Stream Received: "Inheriting the constructor & checking from superConstructor"
\acute - Tex Command

\acute - Command to show accent symbol over the parameter passed.
{ \acute #1 }
\acute command draws an accent symbol over the center of the passed parameter(expression).

\acute e  

e ́


 \acute E 

E ́


 \acute eu 

e ́u


 \acute {eu} 

eu ́



\acute e  

e ́


\acute e  
 \acute E 

E ́


 \acute E 
 \acute eu 

e ́u


 \acute eu 
 \acute {eu} 

eu ́


 \acute {eu} 

    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
The CSS3 matrix3d() Function

The matrix3d() function in CSS is used to define a 4x4 homogeneous 3D transformation matrix.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo_img {
   transform: matrix3d(1,1,0,0,0,1,0,0,0,0,1,0,1,100,0,1);
}
</style>
</head>
<body>
<h1>Learn</h1>
<p>Learn Apache Spark</p>
<img class="demo_img" src=
"https://www.tutorialspoint.com/machine_learning/images/machine-learning-mini-logo.jpg" alt="Apache Spark">
</body>
</html>
Let us see another example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo_img {
   transform: matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,50,-100,0,1.1);
</style>
</head>
<body>
<h1>Learn</h1>
<p>Learn Apache Spark</p>
<img class="demo_img" src=
"https://www.tutorialspoint.com/machine_learning/images/machine-learning-mini-logo.jpg" alt="Apache Spark">
</body>
</html>
Synchronization and Pooling of processes in C#

Using Synchronization, you can synchronize access to resources in multithreaded applications.
A mutex can be used to synchronize threads across processes. Use it to prevent the simultaneous execution of a block of code by more than one thread at a time.
C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block.
Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.
Let us see how to create a thread pool.
Firstly, use the following namespace −
using System.Threading;
Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem.
ThreadPool.QueueUserWorkItem(new WaitCallback(Run));
How to convert List<Integer> to int[] in Java?

You can simply iterate through list and fill the array as shown below −
import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>();
      list.add(new Integer(1));
      list.add(new Integer(2));
      list.add(new Integer(3));
      list.add(new Integer(4));
      int[] array = new int[list.size()];
      for(int i=0;i<array.length;i++) {
         array[i] = list.get(i);
         System.out.println(array[i]);
      }
   }
}
1
2
3
4
How to make the Parula colormap in Matplotlib?

To make the Parula colormap in matplotlib, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Create colormap data using numpy.
Create a 'LinearSegmentedColormap' from a list of colors.
Viscum is a little tool for analyzing colormaps and creating new colormaps.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
To display the figure, use show() method.
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import numpy as np
from viscm import viscm
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
cm_data = np.random.rand(4, 4)
parula_map = LinearSegmentedColormap.from_list('parula', cm_data)
viscm(parula_map)
plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto', cmap=parula_map)
plt.show()
How to remove all the elements of a dictionary in Python?

To remove all elements from a dictionary, the easiest way is to reassign the dictionary to an empty dictionary. 
my_dict = {'name': 'foo', 'age': 28}
my_dict = {}
print(my_dict)
This will give the output −
{}
You can also use the del function to delete a specific key or loop through all keys and delete them.
my_dict = {'name': 'foo', 'age': 28}
keys = list(my_dict.keys())
for key in keys:
  del my_dict[key]
print(my_dict)
This will give the output −
{}
Break statement in java

The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
It can be used to terminate a case in the switch statement (covered in the next chapter).
The syntax of a break is a single statement inside any loop −
break;

public class Test {

   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};

      for(int x : numbers ) {
         if( x == 30 ) {
            break;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}
This will produce the following result −
10
20


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
JavaScript | Object.getOwnPropertyDescriptor() Method - GeeksforGeeks

17 Sep, 2021
The Object.getOwnPropertyDescriptor() method in JavaScript is standard built-in objects that returns a property descriptor for an own property of a given object.Syntax:  
Object.getOwnPropertyDescriptor( obj, prop )
Parameters: This method accept two parameters as mentioned above and described below:  
obj: This parameter holds the object in which the property are to be look.
prop: This parameter holds the name or Symbol of the property whose description is to be retrieved.
Return value: This method returns a property descriptor of the given property or undefined depending upon the existence of the object.Below examples illustrate the Object.getOwnPropertyDescriptor() method in JavaScript:Example 1:  
javascript
const geeks1 = {   prop1: "GeeksforGeeks" } const geeks2 = {   prop2: "Best Platform" } const geeks3 = {   prop3: "And Computer science portal" }const descriptor1 = Object.getOwnPropertyDescriptor(geeks1, 'prop1'); const descriptor2 = Object.getOwnPropertyDescriptor(geeks2, 'prop2'); const descriptor3 = Object.getOwnPropertyDescriptor(geeks3, 'prop3'); console.log(descriptor1.enumerable); console.log(descriptor2.enumerable); console.log(descriptor1.value); console.log(descriptor2.value); console.log(descriptor3.enumerable); console.log(descriptor3.value); 
Output:  
true
true
"GeeksforGeeks"
"Best Platform"
true
"And Computer science portal"
Example 2:  
javascript
var geek, result;geek = { get foo() { return 17; } };d = Object.getOwnPropertyDescriptor(geek, 'foo');console.log(d) geek = { bar: 42 };d = Object.getOwnPropertyDescriptor(geek, 'bar');console.log(d) geek = { [Symbol.for('baz')]: 73 }d = Object.getOwnPropertyDescriptor(geek, Symbol.for('baz'));console.log(d) geek = {};Object.defineProperty(geek, 'qux', {  value: 8675309,  writable: false,  enumerable: false});d = Object.getOwnPropertyDescriptor(geek, 'qux');console.log(d)
Output:  
Object { get: get foo() { return 17; }, set: undefined, enumerable: true, configurable: true }
Object { value: 42, writable: true, enumerable: true, configurable: true }
Object { value: 73, writable: true, enumerable: true, configurable: true }
Object { value: 8675309, writable: false, enumerable: false, configurable: false }
Supported Browsers: The browsers supported by Object.getOwnPropertyDescriptor() method are listed below:  
Google Chrome 5.0 and above
Internet Explorer 9.0 and above
Mozilla 4.0 and above
Opera 12 and above
Safari 5.0 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
PHP | min( ) Function - GeeksforGeeks

08 Mar, 2018
The min() function of PHP is used to find the lowest value in an array, or the lowest value of several specified values. The min() function can take an array or several numbers as an argument and return the numerically minimum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input.
Syntax:
min(array_values)  

or

min(value1, value2, ...)

Parameters: This function accepts two different types of parameters which are explained below:
array_values : It specifies an array containing the values.value1, value2, ... : It specifies two or more than two values to be compared.
array_values : It specifies an array containing the values.
value1, value2, ... : It specifies two or more than two values to be compared.
Return Value: The min() function returns the numerically minimum value.
Examples:
Input : min(12, 4, 62, 97, 26)
Output : 4

Input : min(array(28, 36, 87, 12))
Output : 12

Below programs illustrate the working of min() in PHP:
Program 1:
<?php  echo (min(12, 4, 62, 97, 26));  ?>
Output:
4
Program 2:
<?php  echo (min(array(28, 36, 87, 12)));  ?>
Output:
12
Important points to note :
min() function is used to find the numerically minimum number.
min() function can be used on two or more than two values or it can be used on an array.
The value returned is of mixed data type.
Reference:http://php.net/manual/en/function.min.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
C++ Strings

Strings are used for storing text.
A string variable contains a collection of characters surrounded by double quotes:
Create a variable of type string and assign it a value:
To use strings, you must include an additional header file in the source 
code, the <string> library:
Fill in the missing part to create a greeting variable of type string and assign it the value Hello.
  = ;

Start the Exercise
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.