code-rag-bench/online-tutorials huggingface dataset:
How to find the maximum value of an array in JavaScript?

we can find the Maximum value of an array using Math.max() and sort() functions.
Math.max() function usually takes all the elements in an array and scrutinize each and every value to get the maximum value.It's methodology is discussed in the below example. 
Live Demo
<html>
<body>
<script>
   function maximum(value) {
      if (toString.call(value) !== "[object Array]")
      return false;
      return Math.max.apply(null, value);
   }
   document.write(maximum([6,39,55,1,44]));
</script>
</body>
</html>
55.
Using sort and compare functions we can arrange the elements in array in descending or ascending order, later on using the length property we can find the required value.
 Live Demo
<html>
<body>
<input type ="button" onclick="myFunction()" value = "clickme">
<p id="max"></p>
<script>
   var numbers = [6,39,55,1,44];
   document.getElementById("max").innerHTML = numbers;
   function myFunction() {
   numbers.sort(function(a, b){return a - b});
   document.getElementById("max").innerHTML = numbers;
   document.write(numbers[numbers.length-1]);
   }
</script>
</body>
</html>
From the above program the output is displayed as the following image
Later on clicking the above  click me button the maximum value is displayed  as the following
55
Explain about Modigliani – miller theory of capital structure.

Company finances its assets by capital structure. It can finance its assets by either only equity or combination of debt and equity.
Modigliani and miller proposed a theory in 1950s, which says, valuation of a company is irrelevant to its capital structure. It is also irrelevant, to whether company is highly leveraged or low debt because of its market value. It depends only on operating profits of company. This theory is also called as capital structure irrelevance principle.
Modigliani and miller approach states the valuation of company is irrelevant to its capital structure. Let us say, Company X is financed by equity only (unlevered) and company Y is financed by combination of equity and debt (levered).
According to Modigliani and miller approach value of both company’s X and Y are same. Value of company is independent of its capital structure/financing decisions.
Assumptions of Modigliani and miller theory are as follows −
No taxes.
No taxes.
Transaction cost equals to zero.
Transaction cost equals to zero.
Floatation cost equals to zero.
Floatation cost equals to zero.
Symmetrical information (same information is accessed by both investors and corporates).
Symmetrical information (same information is accessed by both investors and corporates).
No corporate dividend tax.
No corporate dividend tax.
Market value doesn’t affect the value of company. That means, leverage of company has no effect on its value. Both equity shareholders and debt shareholders will be given same priority.
VL = V�
Financial leverage has direct proportion to cost of equity. That means, if debt component increases, equity shareholders perceive high risk. In this proposition, debt holders have upper hand in claiming.
RE=RO+(DE)(RO−RD)Propositions with taxesIn this, corporate taxes and its benefits are considered (as in real world will have taxes). Change in debtequity ratio has an effect on weighted average cost of capital (WACC). Higher the debt, lower the WACC.1) VL = VU + tcD
2) RE = RO + (
D
E
) (1 − tc)(RO − RD)
Modigliani and miller approach and WACC =>EWACC = (
E
VL
) RE + (
D
VL
) RD(1 − tc)Where, VL= levered firms, VU= unlevered firms, RE= return on equity, RO= return on unlevered equity, RD= return on debt, D = market value of debt, E = market value of Equity, tc= corporate tax rate.





Mandalika


Updated on 28-Sep-2020 17:48:35
Send SMS updates to mobile phone using python

03 Jul, 2022
If you are running any python script and want to send regular updates from your script to your mobile phone through SMS, you can use SinchSMS API to send SMS.Approach : Create an app on Sinch and get the key and secret of the app and use these credentials in the following script to send SMS to your mobile.Limitation of Sinch : If you don’t have any credits(you have to pay for credits), you can only send SMS to the registered mobile numbers on Sinch. You can use way2sms to send SMS to any number(I will be discussing how to use way2sms in another article), but without purchased credits, on way2sms also, you can’t send more than 100 SMS per day. 
Python
# python script for sending message update  import timefrom time import sleepfrom sinchsms import SinchSMS  # function for sending SMSdef sendSMS():      # enter all the details    # get app_key and app_secret by registering    # a app on sinchSMS    number = 'your_mobile_number'    app_key = 'your_app_key'    app_secret = 'your_app_secret'      # enter the message to be sent    message = 'Hello Message!!!'      client = SinchSMS(app_key, app_secret)    print("Sending '%s' to %s" % (message, number))      response = client.send_message(number, message)    message_id = response['messageId']    response = client.check_status(message_id)      # keep trying unless the status returned is Successful    while response['status'] != 'Successful':        print(response['status'])        time.sleep(1)        response = client.check_status(message_id)      print(response['status'])  if __name__ == "__main__":    sendSMS()
For the execution of the script, edit the number, app_key, and app_secret fields, and then simply run the script.I have written a complete script for sending SMS updates to mobile phones using sinchSMS and way2sms by fetching the latest updates from our placement website(aitplacements.com). GitHub link: stayUpdatedExercise: Create a python script that updates you on your mobile phone if the price of a particular product lowers down to a certain price on amazon.com 
punamsingh628700
varshagumber28
Python-projects
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
IPv4 Classless Subnet equation

09 Aug, 2019
Prerequisite – Classless Addressing, SupernettingProblem – How to calculate IP address subnet information (Network, Broadcast, First IP, Last IP)?It’s too simple equation to calculate IPv4 Subnet Network ID.
*Used and Tested with Class C Subnets.
First Of All, Keep this Subnet Hosts Map in mind (Number of Hosts per Prefix):
Network Prefix:  Number of IPs
24            :      256 IPs
25            :      128 IPs
26            :      64 IPs
27            :      32 IPs
28            :      16 IPs
29            :      8 IPs
30            :      4 IPs 
Using Equation:
Network ID: floor(Host Address/Subnet Number of Hosts) * Subnet Number of Hosts
Broadcast ID: (Host ID + (Subnet Number of Hosts-1))
First Host: Network ID + 1
Last Host: Broadcast ID - 1

Ex1: 192.168.1.65/28:
65/16 = 4.0625
Network ID: 4*16 = 64           (192.168.1.64)
Broadcast ID: 64+(16-1) = 79    (192.168.1.79)
First Host ID: 64 + 1 = 65      (192.168.1.65)
Last Host ID: 79 - 1 = 78       (192.168.1.78)

Ex2: 192.168.20.166/25:
166/128 = 1.296875
Network ID: 1*128 = 128         (192.168.20.128)
Broadcast ID: 128+(128-1) = 255 (192.168.20.255)
First Host ID: 128 + 1 = 129    (192.168.20.129)
Last Host ID: 255 - 1 = 254     (192.168.20.254)

Ex3: 192.168.30.14/29:
14/8 = 1.75
Network ID: 1*8 = 8             (192.168.30.8)
Broadcast ID: 8+(8-1) = 15      (192.168.30.15)
First Host ID: 8 + 1 = 9        (192.168.30.9)
Last Host ID: 15 - 1 = 14       (192.168.30.14)

Ex4: 192.168.20.86/30:
86/4 = 21.5
Network ID: 21*4 = 84           (192.168.20.84)
Broadcast ID: 84+(4-1) = 87     (192.168.20.87)
First Host ID: 84 + 1 = 85      (192.168.20.85)
Last Host ID: 87 - 1 = 86       (192.168.20.86)

Computer Networks-IP Addressing
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Wireless Application Protocol
GSM in Wireless Communication
Secure Socket Layer (SSL)
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
OpenCV Python Program to blur an image

22 Jul, 2021
Note: This post contains codes that cannot be run using an online compiler. Please make sure that you have Python 2.7 and cv2 module installed before trying to run the program on your system.
Hi everyone! I read a brilliant work by Aditya Prakash – OpenCV C++ Program to blur an image, so I decided to come up with something similar but this time in Python. So, here is a very simple program with basically the same result.
# Python Program to blur image  # Importing cv2 moduleimport cv2   # bat.jpg is the batman image.img = cv2.imread('bat.jpg')   # make sure that you have saved it in the same folder# You can change the kernel size as you wantblurImg = cv2.blur(img,(10,10)) cv2.imshow('blurred image',blurImg)  cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Now, this program above is using image blurring technique called Averaging.There are some other options available as well – Gaussian Blurring, Median Blurring, Bilateral Filtering. Let’s make a couple of additions in our program and compare the results.
# importing opencv CV2 moduleimport cv2   # bat.jpg is the batman image.img = cv2.imread('gfg.png')   # make sure that you have saved it in the same folder# Averaging# You can change the kernel size as you wantavging = cv2.blur(img,(10,10))   cv2.imshow('Averaging',avging)cv2.waitKey(0)  # Gaussian Blurring# Again, you can change the kernel sizegausBlur = cv2.GaussianBlur(img, (5,5),0) cv2.imshow('Gaussian Blurring', gausBlur)cv2.waitKey(0)  # Median blurringmedBlur = cv2.medianBlur(img,5)cv2.imshow('Media Blurring', medBlur)cv2.waitKey(0)  # Bilateral FilteringbilFilter = cv2.bilateralFilter(img,9,75,75)cv2.imshow('Bilateral Filtering', bilFilter)cv2.waitKey(0)cv2.destroyAllWindows()
Original Image:Averaging:
Gaussian Blurring:
Media Blurring:
Bilateral Filtering:
Hope you enjoyed the post! Auf Wiedersehen!
About the author:
Vishwesh Shrimali is an Undergraduate Mechanical Engineering student at BITS Pilani. He fulfils about all the requirements not taught in his branch- white hat hacker, network security operator, and an ex – Competitive Programmer. As a firm believer in power of Python, his majority work has been in the same language. Whenever he get some time apart from programming, attending classes, watching CSI Cyber, he go for a long walk and play guitar in silence. His motto of life is – “Enjoy your life, ‘cause it’s worth enjoying!”
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.
Image-Processing
OpenCV
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
10 Best Web Development Projects For Your Resume
Twitter Sentiment Analysis using Python
A Group chat application in Java
Student Information Management System
E-commerce Website using Django
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
HTML - <layer> Tag

The HTML <layer> tag is used to position and animate (through scripting) elements in a page. A layer can be thought of as a separate document that resides on top of the main one, all existing within one window.
This tag has support in Netscape 4 and higher versions of it.
This example creates three overlapping layers. The back one is red, the middle one is blue, and the front one is green.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML layer Tag</title>
   </head>

   <body>
      <layer id = "layer1" top = "250" left = "50" width = "200" 
         height = "200" bgcolor = "red">
         <p>layer 1</p>
      </layer>
      
      <layer id = "layer2" top = "350" left = "150" width = "200"
         height = "200" bgcolor = "blue">
         <p>layer 2</p>
      </layer>
      
      <layer id = "layer3" top = "450" left = "250" width = "200"
         height = "200" bgcolor = "green">
         <p>layer 3</p>
      </layer>
   </body>

</html>
This will produce the following result, it will work in Netscape 4 and higher versions.
layer 1
layer 2
layer 3
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <layer> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
Python – Sort Dictionary by Values and Keys

01 Aug, 2020
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. 
Input : test_dict = {“gfg” : 1, “is” : 1, “best” : 1, “for” : 1, “geeks” : 1}Output : {“best” : 1, “is” : 1, “for” : 1, “geeks” : 1, “gfg” : 1}Explanation : All values are equal, hence lexicographically sorted keys.
Input : test_dict = {“gfg” : 5, “is” : 4, “best” : 3, “for” : 2, “geeks” : 1}Output : {“gfg” : 5, “is” : 4, “best” : 3, “for” : 2, “geeks” : 1}Explanation : All values are different, hence descending ordered sorted.
Method : Using sorted() + items() + dictionary comprehension + lambda
The combination of above functions can be used to solve this problem. In this, we perform task of sorting using sorted(), dictionary comprehension is used to remake dictionary, items() is used to extract items to sorted. 
Python3
# Python3 code to demonstrate working of # Sort Dictionary by Values and Keys# Using sorted() + items() + dictionary comprehension + lambda  # initializing dictionarytest_dict = {"Gfg" : 1, "is" :  3, "Best" : 2, "for" : 3, "Geeks" : 2}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # - sign for descended values, omit if low-high sorting requiredres = {val[0] : val[1] for val in sorted(test_dict.items(), key = lambda x: (-x[1], x[0]))}  # printing result print("Sorted dictionary : " + str(res)) 
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2, 'for': 3, 'Geeks': 2}
Sorted dictionary : {'for': 3, 'is': 3, 'Best': 2, 'Geeks': 2, 'Gfg': 1}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Comparison between MongoDB vs. Cassandra

29 Jun, 2021
In this article we will discuss about similarities and differences between MongoDB and Cassandra.1. MongoDB :MongoDB is a cross-platform document-oriented database program. It is an open-source document database, which stores the data in the form of key-value pairs.
Supported Languages : C++, Go, JavaScript, Python.
2. Cassandra :Cassandra is a free and open-source, distributed, wide column store, NoSQL database management system. Which is used to handle large amounts of data.
Supported Languages : Java
Similarities :
MongoDB and Cassandra used TCP/IP Protocol to transfer/receive the data through a network.Locks are available in Both.Both will support Linux OS, Mac – OS and WindowsBoth will store the data in disc.MongoDB and Cassandra are open sourced(Freely available to all)Both are scalable
MongoDB and Cassandra used TCP/IP Protocol to transfer/receive the data through a network.
Locks are available in Both.
Both will support Linux OS, Mac – OS and Windows
Both will store the data in disc.
MongoDB and Cassandra are open sourced(Freely available to all)
Both are scalable
Difference between MongoDB and Cassandra :
Cassandra 
MongoDB 
 
Picked
Difference Between
MongoDB
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 Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Compile-time and Run-time Polymorphism in Java
Differences and Applications of List, Tuple, Set and Dictionary in Python
Spring Boot JpaRepository with Example
Mongoose | findByIdAndUpdate() Function
Upload and Retrieve Image on MongoDB using Mongoose
Mongoose Populate() Method
Mongoose find() Function
dstat Command in Linux With Examples

02 Jun, 2021
dstat is a tool that is used to retrieve information or statistics form components of the system such as network connections, IO devices, or CPU, etc. It is generally used by system administrators to retrieve a handful of information about the above-mentioned components of the system. It itself performs like vmstat, netstat, iostat, etc. By using this tool one can even see the throughput for block devices that make up a single filesystem or storage system. 
Installation of dstat command
On RedHat based OS 
yum install dstat
On ubuntu or debian  
sudo apt install dstat
1. To display statistics of major OS components  
dstat
 
This command will display CPU, Disk, Network, Paging and System stats. 
2. To display information that was to be displayed by vmstat tool 
dstat --vmstat 
The above command results in the process and memory stats. 
3. To display stats of process using most of the CPU. 
dstat -c --top-cpu
This will display the stats of the process which is consuming most of the CPU. 
4. To display stats of process using most of the memory.  
dstat -d --top-mem
This will display the stats of the process which is consuming most of the memory. 
5. To display the list of all plugins 
dstat --list 
Plugins are the options you want to display the stats of. The above command will list all such plugins. 
6. To force float values to be printed 
dstat --float
This will force the float values to be printed which were hidden earlier. 
7. To force bits values to be printed. 
dstat --bits
This will print all the values in bits that were earlier used to be printed in bytes. 
8. To display the output without colors 
dstat --nocolor
This command will now display the outputs in white color only. 
9. To get all stats of the processes. 
dstat -a
This command will display all the stats of the processes. 
10. To display help 
dstat --help
This will display the help section of the dstat command. 
saurabh1990aror
linux-command
Linux-networking-commands
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Collect.js toArray() Method

03 Dec, 2020
The toArray() method is used to convert the given collection into a normal array. An array containing the values will be returned if the collection is an object.
Syntax:
collect(array).toArray()
Parameters: The collect() method takes one argument that is converted into the collection and the toArray() method is applied to it.
Return Value: This method returns an array of the given collection.
Below example illustrate the toArray() method in collect.js:
Example 1:
Javascript
const collect = require('collect.js');   let arr = ['kripa', 'biltu', 'chinu', 1, 2, 3];     const collection = collect(arr);     const newObject = collection.toArray();   console.log(newObject);
Output:
["kripa", "biltu", "chinu", 1, 2, 3]
Example 2:
Javascript
const collect = require('collect.js');  let obj ={    name: 'TATA',    companies: [        'tcs', 'tata motors',        'tata tea', 'tata salt', 'sonata'    ],};  const collection = collect(obj);  const newObject = collection.toArray();  console.log(newObject);
Output:
[ 'TATA', [ 'tcs', 'tata motors', 'tata tea', 'tata salt', 'sonata' ] ]
Collect.js
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
Remove elements from a JavaScript Array
JavaScript String includes() Method
Implementation of LinkedList in Javascript
DOM (Document Object Model)
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
DateTimeOffset.ToLocalTime() Method in C#

27 Feb, 2019
DateTimeOffset.ToLocalTime Method is used to convert the current DateTimeOffset object to a DateTimeOffset object which represents the local time.
Syntax: public DateTimeOffset ToLocalTime ();
Return Value: This method returns an object that represents the date and time of the current DateTimeOffset object converted to local time.
Below programs illustrate the use of DateTimeOffset.ToLocalTime() Method:
Example 1:
// C# program to demonstrate the// DateTimeOffset.ToLocalTime()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of  DateTimeOffset            DateTimeOffset offset = new DateTimeOffset(2007,                    6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));              // Converts the current DateTimeOffset object            // to a DateTimeOffset object that represents             // the local time instance using the             // ToLocalTime() method            DateTimeOffset value = offset.ToLocalTime();              // Display the time            Console.WriteLine("DateTimeOffset is {0}", value);        }          catch (ArgumentOutOfRangeException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
DateTimeOffset is 06/01/2007 12:55:00 +00:00

Example 2:
// C# program to demonstrate the// DateTimeOffset.ToLocalTime()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // creating object of  DateTimeOffset        DateTimeOffset offset = new DateTimeOffset(2027,                6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));          // Converts the current DateTimeOffset object        // to a DateTimeOffset object that represents         // the local time instance using the         // ToLocalTime() method        DateTimeOffset value = offset.ToLocalTime();          // Display the time        Console.WriteLine("DateTimeOffset is {0}", value);    }}
DateTimeOffset is 06/01/2027 12:55:00 +00:00

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tolocaltime?view=netframework-4.7.2
CSharp-DateTimeOffset-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
Extension Method in C#
C# | Replace() Method
Java floor() method with Examples

08 Apr, 2018
The java.lang.Math.floor() returns the double value that is less than or equal to the argument and is equal to the nearest mathematical integer.Note:
If the argument is Integer, then the result is Integer.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
public static double floor(double a)a : the argument whose floor value is to be determinedReturns : This method returns the double value that is less than or equalto the argument and is equal to the nearest mathematical integer.
Example :To show working of java.lang.Math.floor() method.
// Java program to demonstrate working// of java.lang.Math.floor() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double a = 4.3;        double b = 1.0 / 0;        double c = 0.0;        double d = -0.0;        double e = -2.3;          System.out.println(Math.floor(a));          // Input Infinity, Output Infinity        System.out.println(Math.floor(b));          // Input Positive Zero, Output Positive Zero        System.out.println(Math.floor(c));          // Input Negative Zero, Output Negative Zero        System.out.println(Math.floor(d));          // Input -2.3, Output -3.0        // Nearest Integer(-3.0) < less than (-2.3)        System.out.println(Math.floor(e));    }}
Output:
4.0
Infinity
0.0
-0.0
-3.0

Java-Library
java-math
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
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
How to use the ValidateRange attribute in PowerShell function?

Validation parameters are a set of rules that you define on the PowerShell variable and restrict users from entering some values and binding users to enter values in the specific domain. If there are not validation parameters the script would be lengthy. The ValidateRange attribute is one of them.
This parameter is to validate the specific range of numbers. For example, If we need users to enter a
value between 5 and 100 and we simply write the script using the If/else statement as shown below.
function AgeValidation {
   param(
      [int]$age
   )
   if(($age -lt 5) -or ($age -gt 100)) {
      Write-Output "Age should be between 5 and 100"
   }
   else{
      Write-Output "Age validated"
   }
}
PS C:\> AgeValidation -age 4
Age should be between 5 and 100
PS C:\> AgeValidation -age 55
Age validated
The above code works but we don’t need the user to enter the wrong age at all and throw the error
when he enters the wrong age. This can be achieved by writing a few more lines again but through
validaterange we can achieve our goal without writing more lines.
function AgeValidation {
   param(
      [ValidateRange(5,100)]
      [int]$age
   )
   Write-Output "Age validated!!!"
}
PS C:\> AgeValidation -age 3
AgeValidation: Cannot validate argument on parameter 'age'. The 3 argument is les
s than the minimum allowed range of 5. Supply an argument that is greater than or
equal to 5 and then try the command again.
PS C:\> AgeValidation -age 150
AgeValidation: Cannot validate argument on parameter 'age'. The 150 argument is g
reater than the maximum allowed range of 100. Supply an argument
that is less than or equal to 100 and then try the command again.
When you enter an age below or above allowed values, the script throws an error. This is how we can use the ValidateRange attribute.
How to find the index of an element in an array using PHP ?

13 Oct, 2021
In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. We can get the array index by using the array_search() function. This function is used to search for the given element. It will accept two parameters.
Syntax:
array_search('element', $array)
Parameters:
The first one is the element present in the array.
The second is the array name.
Return Value: It returns the index number which is an Integer.
Note: We will get the index from indexed arrays and associative arrays.
Example 1: PHP program to get the index of the certain elements from the indexed array.
PHP
<?php  // Create an indexed array with 5 subjects$array1 = array('php', 'java',          'css/html', 'python', 'c/c++');  // Get the index of PHPecho array_search('php', $array1);echo "\n";  // Get the index of javaecho array_search('java', $array1);echo "\n";  // Get the index of c/c++echo array_search('c/c++', $array1);echo "\n";  ?>
0
1
4

Example 2: The following example returns the index of an associative array.
PHP
<?php  // Create an associative array// with 5 subjects$array1 = array(      0 => 'php',       1 => 'java',      2 => 'css/html',       3 => 'python',      4 => 'c/c++');  // Get the index of phpecho array_search('php', $array1);echo "\n";  // Get the index of javaecho array_search('java', $array1);echo "\n";  // Get index of c/c++echo array_search('c/c++', $array1);echo "\n";  ?>
0
1
4

PHP-array
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between HTTP GET and POST Methods
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
How to create admin login page using PHP?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python – Extract date in String

09 May, 2021
Given a string, the task is to write a Python program to extract date from it.
Input : test_str = "gfg at 2021-01-04"
Output : 2021-01-04
Explanation : Date format string found.

Input : test_str = "2021-01-04 for gfg"
Output : 2021-01-04
Explanation : Date format string found.
Method #1 : Using re.search() + strptime() methods
In this, the search group for a particular date is fed into search(), and strptime() is used to feed in the format to be searched.
Python3
# Python3 code to demonstrate working of# Detect date in String# Using re.search() + strptime()import refrom datetime import datetime  # initializing stringtest_str = "gfg at 2021-01-04"  # printing original stringprint("The original string is : " + str(test_str))  # searching stringmatch_str = re.search(r'\d{4}-\d{2}-\d{2}', test_str)  # computed date# feeding formatres = datetime.strptime(match_str.group(), '%Y-%m-%d').date()  # printing resultprint("Computed date : " + str(res))
Output:
The original string is : gfg at 2021-01-04
Computed date : 2021-01-04
Method #2: Using python-dateutil() module
This is another way to solve this problem. In this inbuilt Python library python-dateutil, The parse() method can be used to detect date and time in a string. 
Python3
# Python3 code to demonstrate working of# Detect date in String# Using python-dateutil()from dateutil import parser  # initializing stringtest_str = "gfg at 2021-01-04"  # printing original stringprint("The original string is : " + str(test_str))  # extracting date using inbuilt func.res = parser.parse(test_str, fuzzy=True)  # printing resultprint("Computed date : " + str(res)[:10])
Output:
The original string is : gfg at 2021-01-04
Computed date : 2021-01-04
Python datetime-program
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Yii - Overview

The Yii[ji:] framework is an open-source PHP framework for rapidly-developing, modern Web applications. It is built around the Model-View-Controller composite pattern.
Yii provides secure and professional features to create robust projects rapidly. The Yii framework has a component-based architecture and a full solid caching support. Therefore, it is suitable for building all kinds of Web applications: forums, portals, content managements systems, RESTful services, e-commerce websites, and so forth. It also has a code generation tool called Gii that includes the full CRUD(Create-Read-Update-Delete) interface maker.
The core features of Yii are as follows −
Yii implements the MVC architectural pattern.
It provides features for both relational and NoSQL databases.
Yii never over-designs things for the sole purpose of following some design pattern.
It is extremely extensible.
Yii provides multi-tier caching support.
Yii provides RESTful API development support.
It has high performance.
Overall, if all you need is a neat interface for the underlying database, then Yii is the right choice. Currently, Yii has two versions: 1.1 and 2.0.
Version 1.1 is now in maintenance mode and Version 2 adopts the latest technologies, including Composer utility for package distribution, PSR levels 1, 2, and 4, and many PHP 5.4+ features. It is version 2 that will receive the main development effort over the next few years.
Yii is a pure OOP (Object-Oriented Programming) framework. Hence, it requires a basic knowledge of OOP. The Yii framework also uses the latest features of PHP, like traits and namespaces. It would be easier for you to pick up Yii 2.0 if you understand these concepts.
The major requirements for Yii2 are PHP 5.4+ and a web server. Yii is a powerful console tool, which manages database migrations, asset compilation, and other stuff. It is recommended to have a command line access to the machine where you develop your application.
For development purpose, we will use −
Linux Mint 17.1
PHP 5.5.9
PHP built-in web server
To check whether your local machine is good to go with the latest Yii2 version, do the following −
Step 1 − Install the latest php version.
sudo apt-get install php5 

Step 2 − Install the latest mysql version.
sudo apt-get install mysql-server

Step 3 − Download the Yii2 basic application template.
composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic

Step 4 − To start a PHP built-in server, inside the basic folder run.
php -S localhost:8080

There is a useful script, requirements.php. It checks whether your server meets the requirements to run the application. You can find this script in the root folder of your application.
If you type http://localhost:8080/requirements.php in the address bar of the web browser, the page looks like as shown in the following screenshot −
 Print
 Add Notes
 Bookmark this page
MathF.Truncate() Method in C# with Examples

The MathF.Truncate() method in C# is used to calculate an integral part of a specified single number or single-precision floating-point number.
Following is the syntax −
public static float Truncate (float val);
Above, Val is the specified number to be truncated
Let us now see an example to implement the MathF.Truncate() method −
using System;
public class Demo {
   public static void Main(){
      float val1 = float.PositiveInfinity;
      float val2 = float.NegativeInfinity;
      Console.WriteLine("MathF.Truncate(val1) = "+MathF.Truncate(val1));
      Console.WriteLine("MathF.Truncate(val2) = "+MathF.Truncate(val2));
   }
}
This will produce the following output −
MathF.Truncate(val1) = Infinity
MathF.Truncate(val2) = -Infinity
Let us now see another example to implement the MathF.Truncate() method −
using System;
public class Demo {
   public static void Main(){
      float val1 = 76.8787f;
      float val2 = 4646.5656f;
      Console.WriteLine("MathF.Truncate(val1) = "+MathF.Truncate(val1));
      Console.WriteLine("MathF.Truncate(val2) = "+MathF.Truncate(val2));
   }
}
This will produce the following output −
MathF.Truncate(val1) = 76
MathF.Truncate(val2) = 4646
GATE | GATE CS 2019 | Question 37 - GeeksforGeeks

26 Feb, 2019
Consider three machines M, N and P with IP addresses 100.10.5.2, 100.10.5.5 and 100.10.5.6 respectively. The subnet mask is set to 255.255.255.252 for all the three machines. Which one of the following is true?
(A) M, N and P all belong to the same subnet(B) Only N and P belong to the same subnet(C) M, N, and P belong to three different subnets(D) Only M and N belong to the same subnetAnswer: (B)Explanation: First, we will do bitwise AND between Subnet mask and given IP address one by oneFor M: 100.10.5.2Bitwise AND:
    01100100.00001010.00000101.00000010 (100.10.5.2)
AND 11111111.11111111.11111111.11111100 (255.255.255.252)
___________________________________________________________
   = 01100100.00001010.00000101.00000000 (100.10.5.0)
For N: 100.10.5.5Bitwise AND:
    01100100.00001010.00000101.00000101 (100.10.5.5)
AND 11111111.11111111.11111111.11111100 (255.255.255.252)
___________________________________________________________
   = 01100100.00001010.00000101.00000100 (100.10.5.4)
For P: 100.10.5.2Bitwise AND:
    01100100.00001010.00000101.00000110 (100.10.5.6)
AND 11111111.11111111.11111111.11111100 (255.255.255.252)
___________________________________________________________
   = 01100100.00001010.00000101.00000100 (100.10.5.4)
It is sure from the above computation that N and P belong to the same network (i.e., 100.10.5.4), while M can belong to the same network or it can be from any other network.
So, option (B) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
Perl chown Function

This function changes the owner (and group) of a list of files. The first two elements of the list must be the numeric uid and gid, in that order. This funcation call works in similar way as unix command chown. Thus you should have sufficient privilege to change the permission of the file.
Following is the simple syntax for this function −
chown USERID, GROUPID, LIST

This function returns the number of files successfully changed.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$cnt = chown $uid, $gid, 'foo', 'bar';
chown $uid, $gid, @filenames;

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Example program on Dynamic memory allocation in C language

Find out the maximum and minimum from an array using dynamic memory allocation in C.
The Dynamic memory allocation enables the C programmers to allocate memory at runtime.
The different functions that we used to allocate memory dynamically at run time are −
The malloc () − allocates a block of memory in bytes at runtime.
The malloc () − allocates a block of memory in bytes at runtime.
The calloc () − allocates continuous blocks of memory at runtime.
The calloc () − allocates continuous blocks of memory at runtime.
The realloc () − used to reduce (or) extend the allocated memory.
The realloc () − used to reduce (or) extend the allocated memory.
The free () − deallocates previously allocated memory space.
The free () − deallocates previously allocated memory space.
The logic for finding maximum element in an array −
First allocate memory to the array
p=(int*)malloc(n*sizeof(int)); //dynamic memory allocation
for(i=0;i<n;i++){
   scanf("%d",p+i);
   if(*(p+i)>max) //finding max element
      max=*(p+i);
}
The logic for finding minimum element in an array −
for(i=0;i<n;i++){
   scanf("%d",p+i);
   if(*(p+i)<min) //finding min element
      min=*(p+i);
}
 Live Demo
#include<stdio.h>
int main(){
   int *p,n,i,max=-32768,min=32767;
   printf("\n enter size:");
   scanf("%d",&n);
   p=(int*)malloc(n*sizeof(int)); //dynamic memory allocation
   printf("\n enter elements:");
   for(i=0;i<n;i++){
      scanf("%d",p+i);
      if(*(p+i)>max) //finding max element
         max=*(p+i);
      if(*(p+i)<min) //finding min element
         min=*(p+i);
   }
   printf("\n maximum=%d\n minimum=%d",max,min);
   free(p);
}
enter size:
enter elements:
maximum=-32768
minimum=32767
Different ways to clear a list in Python

Clearing up all the elements in a python list can be done in many ways. Below are the some of the methods which are implemented to achieve this.
This function is a part of standard library and empties the python list completely.
Syntax: list_name.clear()
list_name is the name of the list supplied by
In the below example we take a list and apply the clear (). The result is an empty list.
list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
#clear the list
list.clear()
print("After clearing the list\n")
print(list)
Running the above code gives us the following result −
Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After clearing the list
[]
The del() function you can selectively remove items at a given index or you can also remove all the elements, making the list empty.
Syntax: del list_name
In the below example we take a list, remove the element at index 2. Then we remove all the elements.
list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
#deleting one element from the list
del list[2]
print("After deleting an element\n")
print(list)
# Removing all elements
del list[:]
print("After deleting all elements\n")
print(list)
Running the above code gives us the following result −
Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After deleting an element
['Mon', 'Tue', 'Thu']
After deleting all elements
[]
In this approach we just assign 0 to all elements in the list which makes the list empty. The * is a character representing all elements.
list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
# Removing all elements
list *= 0
print("After deleting all elements\n")
print(list)
Running the above code gives us the following result −
Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After deleting all elements
[]
We can re-initialize a list by just assigning an empty list to it. In the below example we take a list and then assign an empty list to it which creates an empty list.
list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
# Removing all elements
list = []
print("After deleting all elements\n")
print(list)
Running the above code gives us the following result −
Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After deleting all elements
[]
jsoup - Extract Text

Following example will showcase use of methods to get text after parsing an HTML String into a Document object.
Document document = Jsoup.parse(html);
Element link = document.select("a").first();     
System.out.println("Text: " + link.text());

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
Jsoup − main class to parse the given HTML String.
html − HTML String.
html − HTML String.
link − Element object represent the html node element representing anchor tag.
link − Element object represent the html node element representing anchor tag.
link.text() − text() method retrives the element text.
link.text() − text() method retrives the element text.
Element object represent a dom elment and provides various method to get the text of a dom element.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content</p>"
         + "<div id='sampleDiv'><a href='www.google.com'>Google</a>"
         + "<h3><a>Sample</a><h3>"
         +"</div>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      //a with href
      Element link = document.select("a").first();         

      System.out.println("Text: " + link.text());
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Text: Google

 Print
 Add Notes
 Bookmark this page
data.table vs data.frame in R Programming - GeeksforGeeks

20 Jan, 2021
data.table in R is an enhanced version of the data.frame. Due to its speed of execution and the less code to type it became popular in R. The purpose of data.table is to create tabular data same as a data frame but the syntax varies. In the below example let we can see the syntax for the data table:
R
DataTable = data.table(name = c("a", "b", "c", "d"),                       id = (7, 0, 3, 4))DataTable
In the above example, we use the function data.table() and then we used the function called c() which means concatenation which is used to print data as a series and the names will be of string type so, we used ” ” and id as an integer type so no need to specify in quotes.
data.frame in R is similar to the data table which is used to create tabular data but data table provides a lot more features than the data frame so, generally, all prefer the data.table instead of the data.frame. But the data.frame is also best to use and now let us see the syntax below for the data frame. Similar to the syntax of data.table, data.frame is also obviously the same here, instead of data.table() we use the function data.frame().
R
# student idstuid = c(2, 5, 3, 4, 6, 7, 4, 2, 0)    # student ageage = c(23, 45, 67, 23, 41, 43, 54, 67, 89)   # sex of the studentsex = c(1, 1, 0, 0, 0, 1, 0, 1, 1)    # student infostuinfo = data.frame(empidno, age, sex, status)   stuinfo
The above example gives us the data of the students in the tabular form. If we observe here, the code for the data.table is less than the code for data.frame and hence, data.table takes less time to compile and gives the output fast so, this makes the data table use widely.
data.table
data.frame
data.table is a rewritten form of data.frame in optimized c (or)
data.table inherits from data.frame.
data.table is used for more complex data structures and for 
big data.
The in-built features such as rolling joins, overlapping range 
makes users sort out the wide range of problems.
Code efficient (we can able to write less number of lines of 
code in data.table)
We need to write some more lines of code when compared 
to data.table
Picked
R-DataFrame
Difference Between
R Language
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 Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Adding elements in a vector in R programming - append() method
Loops in R (for, while, repeat)