code-rag-bench/online-tutorials huggingface dataset:
DAX Aggregation - SUMMARIZE function

Returns a summary table for the requested totals over a set of groups.
SUMMARIZE (<table>, <groupBy_columnName>, [<groupBy_columnName>] ..., 
   [<name>, <expression>] ...) 

table
Any DAX expression that returns a table of data.
groupBy_columnName
The qualified name of an existing column to be used to create summary groups based on the values found in it. This parameter cannot be an expression.
name
The name given to a total or summarize column, enclosed in double quotes.
expression
Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context).
A table with the selected columns for the groupBy_columnName parameters and the summarized columns designed by the name parameters.
Each column for which you define a name must have a corresponding expression. Otherwise, an error is returned. The first parameter, ‘name’ defines the name of the column in the results. The second parameter, ‘expression’ defines the calculation performed to obtain the value for each row in that column.
Each column for which you define a name must have a corresponding expression. Otherwise, an error is returned. The first parameter, ‘name’ defines the name of the column in the results. The second parameter, ‘expression’ defines the calculation performed to obtain the value for each row in that column.
groupBy_columnName must be either in table or in a related table to table.
groupBy_columnName must be either in table or in a related table to table.
Each name must be enclosed in double quotation marks.
Each name must be enclosed in double quotation marks.
The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group.
The function groups a selected set of rows into a set of summary rows by the values of one or more groupBy_columnName columns. One row is returned for each group.
= SUMMARIZE ( 
   SalesTarget,SalesTarget[SalesTarget],"MaxTarget",MAX (SalesTarget[SalesTarget])) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to provide new line in JavaScript alert box?

To add a new line in JavaScript alert box, use the “\n”:
alert("Line One\n Line Two");
You can try to run the following code add a new line in an alert box in JavaScript:
Live Demo
<html>
   <head>
      <script>
         <!--
            function Warn() {
               alert ("This is a warning message!\nThis is a new line.");
               document.write ("This is a warning message!");
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button to see the result: </p>
      <form>
         <input type="button" value="Click Me" onclick="Warn();" />
      </form>
   </body>
</html>
Python program to calculate gross pay - GeeksforGeeks

26 Nov, 2020
Gross pay is the amount of money an employee earns in a specific time period before any deductions. There are lots of different ways to calculate gross pay depending on how an employee is paid. This article describes the two most common ways -hourly and salary.
If an employee is paid hourly, he is paid a fixed amount for every hour of work. So, if he gets paid Rs.100 an hour, and he works eight hours his gross pay is Rs.800. An hourly employee’s gross pay must be calculated on a weekly basis because of a Rule called overtime, the federal government’s Fair Labor Standards Act states that for overtime an employee must receive overtime pay for hours worked over 40 in a work week at a rate not less than 1.5 times regular rates of pay. 
Example:
Let’s assume A works as an hourly paid employee, and he is paid 100/hour. 
If he worked for 50 hours in a week then he will get the overtime pay for the extra hours he worked i.e. he will be paid 1.5 times of Rs.100 for 10 hours (50-40). 
if worked_hours > 40     then:total gross pay = (hourly_wage *40) + (1.5 * hourly_wage * (worked_hours-40)).
if worked_hours < 40     then:total gross pay = hourly_wage *worked_hours.ramu’s worked_hours=50 i.e. greater than 40 hours.total gross pay = 100*40 + (1.5)*100*10 => Rs.5,500. 
Program:
Python3
def weeklyPaid(hours_worked, wage):    if hours_worked > 40:        return 40 * wage + (hours_worked - 40) * wage * 1.5    else:        return hours_worked * wage    hours_worked = 50wage = 100  pay = weeklyPaid(hours_worked, wage)  print(f"Total gross pay: Rs.{pay:.2f} ")
Output:
Total gross pay: Rs.5500.00 

Salary is usually quoted annually but commonly, employees are paid monthly. To calculate gross pay of a salaried employee, we need to divide the annual salary by number of pay periods in a year (i.e. how many installments they are getting paid in a year).
Example:
Let’s assume B works as a salaried employee, and he is paid 12 lakhs per annum.If B was paid monthly then the gross payment will be 12 lakhs / 12. 
gross pay= 12/12 => 1 lakh.
Program:
Python3
def getGrossPay(annual_salary, no_of_pay_peroids):    return float(annual_salary/no_of_pay_peroids)  # driver code    # annual_salary in lakhsannual_salary = 12no_of_pay_peroids = 12pay = getGrossPay(annual_salary, no_of_pay_peroids)  print(f"Total gross pay: Rs.{pay:.2f} lakhs ")
Output:
Total gross pay: Rs.1.00 lakhs 

Time complexity : O (1) 
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Exponential Smoothing with Python | Towards Data Science

The article below is an extract from my book Data Science for Supply Chain Forecast, available here. You can find my other publications here. I am also active on LinkedIn.
This article is following another article on the theoretical introduction to simple exponential smoothing. You can find it here. You can find a similar article on how to make the same model with Python here.
We will define a function simple_exp_smooth that takes a time series d as input and returns a pandas DataFrame df with the historical demand, the forecast, and the error. The function also takes extra_periods as an input, which is the number of periods that need to be forecast into the future. The last input is the alpha parameter.
def simple_exp_smooth(d,extra_periods=1,alpha=0.4):    d = np.array(d)  # Transform the input into a numpy array    cols = len(d)  # Historical period length    d = np.append(d,[np.nan]*extra_periods)  # Append np.nan into the demand array to cover future periods    f = np.full(cols+extra_periods,np.nan)  # Forecast array    f[1] = d[0]  # initialization of first forecast    # Create all the t+1 forecasts until end of historical period    for t in range(2,cols+1):      f[t] = alpha*d[t-1]+(1-alpha)*f[t-1]    f[cols+1:] = f[t]  # Forecast for all extra periods    df = pd.DataFrame.from_dict({"Demand":d,"Forecast":f,"Error":d-f})
We can then simply call our function (here with a dummy demand time series):
import numpy as np import pandas as pdd=[28,19,18,13,19,16,19,18,13,16,16,11,18,15,13,15,13,11,13,10,12]df = simple_exp_smooth(d,extra_periods=4)
You can also quickly get the forecast accuracy with simple commands, such as shown below. See my previous article about KPI to see which one is best for your case.
MAE = df["Error"].abs().mean()  print("MAE:",round(MAE,2)) RMSE = np.sqrt((df["Error"]**2).mean())print("RMSE:",round(RMSE,2))
You should get these results:
MAE: 2.74RMSE: 3.89
Another exciting step is to plot the results to analyze how the model behaves.
df.index.name = "Periods"df[["Demand","Forecast"]].plot(figsize=(8,3),title="Simple Smoothing",ylim=(0,30),style=["-","--"])
You should get a figure similar to the one below.
www.linkedin.com
Nicolas Vandeput is a supply chain data scientist specialized in demand forecasting and inventory optimization. He founded his consultancy company SupChains in 2016 and co-founded SKU Science — a fast, simple, and affordable demand forecasting platform — in 2018. Passionate about education, Nicolas is both an avid learner and enjoys teaching at universities: he has taught forecasting and inventory optimization to master students since 2014 in Brussels, Belgium. Since 2020, he is also teaching both subjects at CentraleSupelec, Paris, France. He published Data Science for Supply Chain Forecasting in 2018 (2nd edition in 2021) and Inventory Optimization: Models and Simulations in 2020.
Data Structures | Binary Trees | Question 6 - GeeksforGeeks

06 Sep, 2021
The maximum number of binary trees that can be formed with three unlabelled nodes is:
(A) 1(B) 5(C) 4(D) 3Answer: (B)Explanation: Following are all possible unlabeled binary trees

             O
          /     \
        O        O
           (i)

            O
          /
       O
     /
   O
        (ii)

         O
       /
     O
        \
          O
       (iii)

  O
     \
       O
          \
           O
    (iv)

       O
          \
            O
          /
       O
    (v)
Note that nodes are unlabeled. If the nodes are labeled, we get more number of trees.We can find the number of binary tree by Catalan number number:Here n = 3Number of binary tree = (2nCn)/ n+1= (2*3C3)/ 4+1= 5.So, option (B) is correct.
Quiz of this Question
iqbal_bajmi
_garimaarora_
akshaysingh98088
Binary Trees Quiz
Data Structures
Data Structures-Binary Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of Linked List
Introduction to Data Structures | 10 most commonly used Data Structures
FIFO vs LIFO approach in Programming
Program to create Custom Vector Class in C++
Bit manipulation | Swap Endianness of a number
Multilevel Linked List
Advantages of vector over array in C++
Difference between data type and data structure
Data Structures | Queue | Question 11
Data Structures | Linked List | Question 6
Python | Pandas Series.cov() to find Covariance - GeeksforGeeks

08 Oct, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.cov() is used to find covariance of two series. In the following example, covariance is found using both Pandas method and manually ways and the answers are then compared.
To learn more about Covariance, click here.
Syntax: Series.cov(other, min_periods=None)Parameters: other: Other series to be used in finding covariance min_periods: Minimum number of observations to be taken to have a valid resultReturn type: Float value, Returns covariance of caller series and passed series 
Example :In this example, two lists are made and converted to series using Pandas .Series() method. The average if both series is found and a function is created to find Covariance manually. Pandas .cov() is also applied and results from both ways are stored in variables and printed to compare the outputs.
Python3
import pandas as pd # list  1a = [2, 3, 2.7, 3.2, 4.1] # list 2b = [10, 14, 12, 15, 20] # storing average of aav_a = sum(a)/len(a) # storing average of bav_b = sum(b)/len(b) # making series from list aa = pd.Series(a) # making series from list bb = pd.Series(b)    # covariance through pandas methodcovar = a.cov(b)  # finding covariance manuallydef covarfn(a, b, av_a, av_b):    cov = 0     for i in range(0, len(a)):        cov += (a[i] - av_a) * (b[i] - av_b)    return (cov / (len(a)-1)) # calling functioncov = covarfn(a, b, av_a, av_b) # printing resultsprint("Results from Pandas method: ", covar)print("Results from manual function method: ", cov)
Output: 
As it can be seen in output, the output from both ways is same. Hence this method is useful when finding co variance for large series.
Results from Pandas method:  2.8499999999999996
Results from manual function method:  2.8499999999999996
 
abhishek0719kadiyan
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
JavaScript | RegExp s Metacharacter - GeeksforGeeks

06 Apr, 2021
The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].Syntax:  
/\s/ 
or  
new RegExp("\\s")
Syntax with modifiers:  
/\s/g 
or  
new RegExp("\\s", "g")
Example 1: This example replaces the white spaces with dash. 
html
<!DOCTYPE html><html> <head>    <title>        JavaScript RegExp \s Metacharacter    </title></head> <body style="text-align:center">         <h1 style="color:green">        GeeksforGeeks    </h1>         <h2>RegExp \s Metacharacter</h2>          <p>        Input String: GeeksforGeeks is the computer        science\nportal\tfor geeks.    </p>          <button onclick="geek()">        Click it!    </button>         <p id="app"></p>          <script>        function geek() {            var regex = /\s/g;            var replace = "-";            var str = "GeeksforGeeks is the computer "                    + "science\nportal\tfor geeks.";            var str1 = str.replace(regex, replace);            alert("The new string is: \n" + str1);        }    </script></body> </html>                   
Output: Before Clicking the button:  
After Clicking the button:  
Example 2: This example replaces all the white spaces with hash(#). 
html
<!DOCTYPE html><html> <head>    <title>        JavaScript RegExp \s Metacharacter    </title></head> <body style="text-align:center">         <h1 style="color:green">        GeeksforGeeks    </h1>         <h2>RegExp \s Metacharacter</h2>          <p>        Input String: Geeks Classes is a Classroom        programme by GeeksforGeeks to enhance DSA.    </p>          <button onclick="geek()">        Click it!    </button>         <p id="app"></p>          <script>        function geek() {            var regex = new RegExp("\\s", "g");            var replace = "#";            var str = "Geeks Classes is a Classroom "                    + "programme\nby GeeksforGeeks\tto"                    + " enhance DSA";            var str1 = str.replace(regex, replace);            alert("The new string is: \n" + str1);        }    </script></body> </html>                   
Output: Before Clicking the button:  
After Clicking the button:  
Supported Browsers: The browsers supported by RegExp \s Metacharacter are listed below:  
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
 
simranarora5sos
JavaScript-RegExp
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to make POST call to an API using Axios.js in JavaScript ? - GeeksforGeeks

21 Jul, 2021
Axios is a promise-based HTTP client designed for Node.js and browser. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly. The following script src will include axios.js in the head section of your HTML code  
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
When we send a request to the API using axios, it returns a response. The response object consists of:  
data: the data returned from the server.
status: the HTTP code returned from the server.
statusText: the HTTP status returned by the server.
headers: headers obtained from the server.
config: the original request configuration.
request: the request object.
For the purpose of demonstration, we will be hosting an API on the localhost:  
http://127.0.0.1:5000
Python Script: You will be requiring the following packages to run the API: flask, requests, jsonify, flask_cors. The code for the Python API is as follows: 
Program:  
Python3
from flask import Flask, jsonify, requestfrom flask_cors import CORS app = Flask(__name__)CORS(app) @app.route('/test', methods =['POST'])def test():   return jsonify({"Result": "Welcome to GeeksForGeeks, "                                   +request.json['name']}) if __name__ == '__main__':    app.run(debug = True)
Note: You can host this API by simply running the above python code.JS Script: Include axios.js and the corresponding JS file in the HTML file. In the JS file, write the following code which makes a POST request using axios to the API. A POST request to the API requires the following variables:  
path: The path to the API method.
queryObj: Query Object which contain the header data for the POST call. The query object is in the form of a Javascript object. For example: {name:’GeeksForGeeks’, type:’Website’}
 
Program:  
javascript
function makePostRequest(path, queryObj) {    axios.post(path, queryObj).then(        (response) => {            var result = response.data;            console.log(result);        },        (error) => {            console.log(error);        }    );} queryObj = { name: 'Chitrank' };makePostRequest('http://127.0.0.1:5000/test', queryObj);
Output: It will call the API with a POST request carrying the mentioned header data. The response obtained will be obtained on the console window.  
 
varshagumber28
JavaScript-Misc
JavaScript
Node.js
Web Technologies
Write From Home
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 Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
HTML| action Attribute - GeeksforGeeks

27 Aug, 2021
The HTML | action Attribute is used to specify where the formdata is to be sent to the server after submission of the form. It can be used in the <form> element. Syntax:  
<form action="URL">
Attribute Values: URL: It is used to specify the URL of the document where the data to be sent after the submission of the form. The possible values of the URL are:  
absolute URL: It points to another website link. For Example: www.gfg.org  
relative URL: It is used to point to a file within a webpage. For Example: www.geeksforgeeks.org
Example-1: This Example illustrates the use of action Attribute.  
html
<!DOCTYPE html><html> <head>    <title>        HTML action Attribute    </title></head> <body>    <h1>GeeksforGeeks</h1>     <h2>HTML action Attribute</h2>     <form action="test.php"          method="post"          id="users">         <label for="username">          Username:      </label>        <input type="text"               name="username"               id="Username">         <br>        <br>         <label for="password">          Password:      </label>        <input type="password"               name="password">    </form>     <br>     <button onclick="myGeeks()">        Submit    </button>    <br>    <br>    <b>After Submitting the form-data will sent      to the "test.php" page on the server.</b></body> </html>
Outputs:  
Supported Browsers: The browser supported by HTML action Attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
adnanirshad158
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
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?
Avalanche Effect in Cryptography - GeeksforGeeks

14 Mar, 2022
In cryptography, the avalanche effect is a term associated with a specific behavior of mathematical functions used for encryption. Avalanche effect is considered as one of the desirable property of any encryption algorithm. A slight change in either the key or the plain-text should result in a significant change in the cipher-text. This property is termed as avalanche effect. 
In simple words, it quantifies the effect on the cipher-text with respect to the small change made in plain text or the key. 
 
Figure – Avalanche Effect 
Even though the concept of avalanche effect was identified by “Shannon’s property of confusion”, the term was first mentioned by Horst Feistel. To implement a strong cipher or cryptographic hash function, this should be considered as one of the primary design objective. 
In case of algorithm that uses hash value, even a small alteration in an input string should drastically change the hash value. In other words, flipping single bit in input string should at least flip half of the bits in the hash value. 
A good encryption algorithm should always satisfy the following relation:  
Avalanche effect > 50% 
The effect ensures that an attacker cannot easily predict a plain-text through a statistical analysis. An encryption algorithm that doesn’t satisfies this property can favor an easy statistical analysis. That is, if the alteration in a single bit of the input results in change of only single bit of the desired output, then it’s easy to crack the encrypted text. 
Examples: 
Example-1: Avalanche effect in cryptography refers (A) Large changes in cipher text when the keyword is changed minimally (B) Large changes in cipher text when the plain text is changed (C) Large impact of keyword change to length of the cipher text (D) None of the above 
Answer: (A) 
Example-2: Avalanche effect in cryptography (A) Is desirable property of cryptographic algorithm (B) Is undesirable property of cryptographic algorithm (C) Has no effect on encryption algorithm (D) None of the above 
Answer: (A) 
 
ManasChhabra2
cryptography
Network-security
Technical Scripter 2019
Computer Networks
ISRO
Technical Scripter
UGC-NET
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Network Topology
Socket Programming in Python
UDP Server-Client implementation in C
TCP 3-Way Handshake Process
Error Detection in Computer Networks
ISRO | ISRO CS 2017 - May | Question 48
ISRO | ISRO CS 2013 | Question 4
ISRO | ISRO CS 2013 | Question 54
ISRO | ISRO CS 2011 | Question 26
ISRO | ISRO CS 2008 | Question 1
TypeScript - Function Returning an Array

Allows a function to return an array.
function disp():string[] { 
   return new Array("Mary","Tom","Jack","Jill") 
} 
 
var nums:string[] = disp() 
for(var i in nums) { 
   console.log(nums[i]) 
}

On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10 
function disp() { 
   return new Array("Mary", "Tom", "Jack", "Jill"); 
} 
var nums = disp(); 
for (var i in nums) { 
   console.log(nums[i]); 
}

Its output is as follows −
Mary 
Tom 
Jack 
Jill


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Bootstrap Collapsible link

To create a collapsible link in Bootstrap, you can try to run the following code
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>More learning content</h2>
         <a href = "#test" class="btn btn-info" data-toggle = "collapse">More</a>
         <div id = "test" class = "collapse">
            We have learning content on Java, PHP, Ruby, C, C++, etc.
         </div>
      </div>
   </body>
</html>
How to simulate target=“_blank” in JavaScript ? - GeeksforGeeks

17 Feb, 2020
The HTML target attribute defines where the linked document will open when the user clicked on the link. If target=”_blank” is set with anchor element, then the linked document will open in a new tab otherwise document is open in the same tab. There are two methods to execute this task. One is the normal older and lengthy way, where target=”_blank” attribute is written inside the HTML tag. Another convenient way is to execute through javascript code.
Approach: At first we will create an event on every click function then we set the condition if there is an anchor tag and the target attribute is not mentioned, target attribute as “_blank”.
Syntax:
 document.addEventListener("click", function(e) {
    if (e.target.tagName == "A" &&
            !e.target.hasAttribute("target"))
    {
        e.target.setAttribute("target", "_blank");
    }
}); 
Below example illustrate the target=”_blank” in JavaScript:Example:
<!DOCTYPE html><html>  <head>    <title>        Simulate target=“_blank” in JavaScript    </title>          <script>        document.addEventListener("click", function(e) {            if (e.target.tagName == "A" &&                    !e.target.hasAttribute("target"))            {                e.target.setAttribute("target", "_blank");            }        });    </script></head>  <body style="text-align:center">          <a href="https://www.geeksforgeeks.org/">        GeeksforGeeks<br>        A computer science portal for geeks    </a></body>  </html>
Output:
JavaScript-Misc
Picked
Technical Scripter 2019
JavaScript
Technical Scripter
Web technologies Questions
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 Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to apply style to parent if it has child with CSS?
How to get names of all the subfolders and files present in a directory using PHP? - GeeksforGeeks

22 Jun, 2021
Given the path of the folder and the task is to print names of subfolders and files present inside them.Explaination: In our PHP code, initially, it is checked whether provided path or filename is a directory or not using is_dir() function. Now, we open the directory using opendir() function and then checking whether it is getting opened or have some errors. Then we use a while loop to get names of all the subfolders, as well as files, present inside the directory with the help of readdir() function. Now we are going inside each subfolder and reading the names of all the files present inside them following a similar procedure.Folder Structure:  
Code: Note: This Code have been saved as PHP file and accessed through wampserver  
php
<?php$gfg_folderpath = "GeeksForGeeks/";// CHECKING WHETHER PATH IS A DIRECTORY OR NOTif (is_dir($gfg_folderpath)) {    // GETTING INTO DIRECTORY    $files = opendir($gfg_folderpath); {        // CHECKING FOR SMOOTH OPENING OF DIRECTORY        if ($files) {            //READING NAMES OF EACH ELEMENT INSIDE THE DIRECTORY            while (($gfg_subfolder = readdir($files)) !== FALSE) {                // CHECKING FOR FILENAME ERRORS             if ($gfg_subfolder != '.' && $gfg_subfolder != '..') {                    echo "SUBFOLDER--" .$gfg_subfolder . "<br>                    "."Files in ".$gfg_subfolder."--<br>";                                     $dirpath = "GeeksForGeeks/" . $gfg_subfolder . "/";                    // GETTING INSIDE EACH SUBFOLDERS                    if (is_dir($dirpath)) {                        $file = opendir($dirpath); {                            if ($file) {                //READING NAMES OF EACH FILE INSIDE SUBFOLDERS               while (($gfg_filename = readdir($file)) !== FALSE) {                if ($gfg_filename != '.' && $gfg_filename != '..') {                        echo $gfg_filename . "<br>";                           }                         }                      }                   }               }                    echo "<br>";                }            }        }    }}?><!DOCTYPE html><html><head>  <title>What's there in GeeksForGeeks </title></head><body></body></html>
Output:  
 
saurabh1990aror
PHP-file-handling
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
Python | Get key with maximum value in Dictionary - GeeksforGeeks

13 Oct, 2021
Given a dictionary, the task is to find the key having the maximum value. Examples :  
Input : {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88}
Output : Jaguar

Input:  {'Geeks':1900, 'for':1292, 'geek' : 88}
Output:  Geeks
 Method #5: Using max() function 
Python3
# Python code to find key with Maximum value in Dictionary  # Dictionary InitializationTv = {'BreakingBad':100, 'GameOfThrones':1292, 'TMKUC' : 88} Keymax = max(zip(Tv.values(), Tv.keys()))[1]print(Keymax)
GameOfThrones
 
 Method 2: Using max() with lambda function 
Python3
# Python code to find key with Maximum value in Dictionary  # Dictionary InitializationTv = {'BreakingBad':100, 'GameOfThrones':1292, 'TMKUC' : 88} Keymax = max(Tv, key= lambda x: Tv[x])print(Keymax)
GameOfThrones
 
  Method 3: Using operator 
Python3
# Python code to find key with# Maximum value in Dictionaryimport operator # Dictionary InitializationCar = {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88} # Getting max itemkeyMax = max(Car.items(), key = operator.itemgetter(1))[0]print(keyMax)
Jaguar
 
  Method 4:  
Python3
# Python code to find key with Maximum value in Dictionary # Dictionary InitializationCompany = {'GFG':10000, 'Hashd':2292, 'Infy': 200} # taking list of car values in vv = list(Company.values()) # taking list of car keys in vk = list(Company.keys()) print(k[v.index(max(v))])
GFG
 
viditvarshney
avinashkmchaudhary
gabaa406
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
ReactJS Onsen UI Range Component - GeeksforGeeks

28 Jun, 2021
ReactJS Onsen-UI is a popular front-end library with a set of React components that are designed to developing HTML5 hybrid and mobile web apps in a beautiful and efficient way. Range Component allows the user to provide a range slider. We can use the following approach in ReactJS to use the Onsen-UI Range Component.
Range Props:
modifier: It is used for the appearance of progress indicator.
onChange It is a callback function that is triggered when the input changes.
value: It is used to denote the current value of the element.
disabled: It is used to specify whether the component is disabled or not.
Preset Modifiers:
material: It is used to show the material design slider.
 
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install onsenui react-onsenui 
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install onsenui react-onsenui 
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'onsenui/css/onsen-css-components.css';import { Range } from 'react-onsenui';  export default function App() {    // State for range  const [value, setValue] = React.useState(0)    return (    <div style={{      display: 'block', width: 500, paddingLeft: 30    }}>      <h6>ReactJS Onsen-UI Range Component</h6>      <Range        value={value}        onChange={(e) => { setValue(e.target.value) }}        modifier='material'      />      Range value: {value}    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://onsen.io/v2/api/react/Range.html
Onsen-UI
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
uname command in Linux with Examples - GeeksforGeeks

18 Feb, 2021
The command ‘uname‘ displays the information about the system.
Syntax:
uname [OPTION]

1. -a option: It prints all the system information in the following order: Kernel name, network node hostname, kernel release date, kernel version, machine hardware name, hardware platform, operating system.Syntax:
$uname  -a

Output:
2. -s option: It prints the kernel name.
Syntax:
$uname  -s

Output:
3. -n option: It prints the hostname of the network node(current computer).
Syntax:
$uname  -n

Output:
4. -r option: It prints the kernel release date.
Syntax:
$uname  -r

Output:
5. -v option: It prints the version of the current kernel.
Syntax:
$uname  -v

Output:
6. -m option: It prints the machine hardware name.
Syntax:
$uname  -m

Output:
7. -p option: It prints the type of the processor.
Syntax:
$uname  -p

Output:
8. -i option: It prints the platform of the hardware.
Syntax:
$uname  -i

Output:
9. -o option: It prints the name of the operating system.
Syntax :
$uname  -o

Output:
YouTubeGeeksforGeeks507K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:53 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
Tail command in Linux with examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Best-Fit Allocation in Operating System - GeeksforGeeks

27 May, 2021
For both fixed and dynamic memory allocation schemes, the operating system must keep list of each memory location noting which are free and which are busy. Then as new jobs come into the system, the free partitions must be allocated. 
These partitions may be allocated by 4 ways:  
1. First-Fit Memory Allocation
2. Best-Fit Memory Allocation
3. Worst-Fit Memory Allocation
4. Next-Fit Memory Allocation 
These are Contiguous memory allocation techniques. 
Best-Fit Memory Allocation: This method keeps the free/busy list in order by size – smallest to largest. In this method, the operating system first searches the whole of the memory according to the size of the given job and allocates it to the closest-fitting free partition in the memory, making it able to use memory efficiently. Here the jobs are in the order from smallest job to largest job. 
 
As illustrated in above figure, the operating system first search throughout the memory and allocates the job to the minimum possible memory partition, making the memory allocation efficient. 
Advantages of Best-Fit Allocation : Memory Efficient. The operating system allocates the job minimum possible space in the memory, making memory management very efficient. To save memory from getting wasted, it is the best method. 
Disadvantages of Best-Fit Allocation : It is a Slow Process. Checking the whole memory for each job makes the working of the operating system very slow. It takes a lot of time to complete the work. 
anikakapoor
memory-management
Operating Systems-Memory Management
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Normal Forms in DBMS
Differences between TCP and UDP
Cache Memory in Computer Organization
Introduction of Operating System - Set 1
Semaphores in Process Synchronization
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Cache Memory in Computer Organization
Program for Round Robin scheduling | Set 1
Data Structures and Algorithms | Set 29 - GeeksforGeeks

13 Dec, 2021
Following questions have been asked in GATE 2012 exam. 
1) The recurrence relation capturing the optimal time of the Tower of Hanoi problem with n discs is (A) T(n) = 2T(n – 2) + 2 (B) T(n) = 2T(n – 1) + n (C) T(n) = 2T(n/2) + 1 (D) T(n) = 2T(n – 1) + 1 
Answer (D) 
Following are the steps to follow to solve Tower of Hanoi problem recursively.  
Let the three pegs be A, B and C. The goal is to move n pegs from A to C.
To move n discs from peg A to peg C:
    move n-1 discs from A to B. This leaves disc n alone on peg A
    move disc n from A to C
    move n?1 discs from B to C so they sit on disc n
The recurrence function T(n) for time complexity of the above recursive solution can be written as following. 
T(n) = 2T(n-1) + 1 
2) Consider the directed graph shown in the figure below. There are multiple shortest paths between vertices S and T. Which one will be reported by Dijkstra?s shortest path algorithm? Assume that, in any iteration, the shortest path to a vertex v is updated only when a strictly shorter path to v is discovered. 
 
(A) SDT (B) SBDT (C) SACDT (D) SACET 
Answer (D) 
3) Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are (A) Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT (B) Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR (C) Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT (D) Full: (FRONT+1) mod n == REAR, empty: REAR == FRONT 
Answer (A) See this for details. 
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. 
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. 
surindertarika1234
GATE-CS-2012
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Cache Memory in Computer Organization
Semaphores in Process Synchronization
Data Structures and Algorithms | Set 25
Operating Systems | Set 1
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 1
Computer Networks | Set 2
How to measure actual MySQL query time?

To measure actual MySQL query time, we can use the concept of profiling that must be set to 1
before executing the query.
The order must be like this.
Set profiling to 1
Then execute query
Then show profiles
Now, I am applying the above order to get the actual MySQL query time −
mysql> SET profiling = 1;
Query OK, 0 rows affected, 1 warning (0.00 sec)
After that I am executing the following query −
mysql> SELECT * from MilliSecondDemo;

The following is the output
+-------------------------+
| MyTimeInMillSec         |
+-------------------------+
| 2018-10-08 15:19:50.202 |
+-------------------------+
1 row in set (0.00 sec)
To know the actual time of the above query, use the following query
mysql> SHOW PROFILES;

After executing the above query, we will get the output as shown below −
+----------+------------+------------------------------+
| Query_ID | Duration   | Query                        |
+----------+------------+------------------------------+
| 1        | 0.00051725 | SELECT * from MilliSecondDemo|
+----------+------------+------------------------------+
1 row in set, 1 warning (0.00 sec)
Python String isdigit() Method

Python string  method isdigit() checks whether the string consists of digits only.
Following is the syntax for isdigit() method −
str.isdigit()

NA
NA
This method returns true if all characters in the string are digits and there is at least one character, false otherwise.
The following example shows the usage of isdigit() method.
#!/usr/bin/python

str = "123456";  # Only digit in this string
print str.isdigit()

str = "this is string example....wow!!!";
print str.isdigit()
When we run above program, it produces following result −
True
False


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to select multiple elements of a list in R?

Generally, a list in R contains a large number of elements and each element can be of different type which is a great thing about lists. Since we can store type of data as a list element therefore storage and selection to different type of data becomes easier. And we can also select single or multiple elements of the list at a time. This can be done with the help of single square brackets.
Consider the below list −
> list_data <- list("India", "China", c(21,32,11), letters[1:5], TRUE,
+ 12, letters[-c(1:10)], c(100,101,200,201), "USA", c("Asia", "Europe"),
+ "Education", "Poverty", "Covid-19", 365, 12, 24, 60, 7)
> list_data
[[1]]
[1] "India"
[[2]]
[1] "China"
[[3]]
[1] 21 32 11
[[4]]
[1] "a" "b" "c" "d" "e"
[[5]]
[1] TRUE
[[6]]
[1] 12
[[7]]
[1] "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
[[8]]
[1] 100 101 200 201
[[9]]
[1] "USA"
[[10]]
[1] "Asia" "Europe"
[[11]]
[1] "Education"
[[12]]
[1] "Poverty"
[[13]]
[1] "Covid-19"
[[14]]
[1] 365
[[15]]
[1] 12
[[16]]
[1] 24
[[17]]
[1] 60
[[18]]
[1] 7
Selecting different elements of the list_data −
> list_data[c(1,2,3)]
[[1]]
[1] "India"
[[2]]
[1] "China"
[[3]]
[1] 21 32 11
> list_data[c(18,2,3)]
[[1]]
[1] 7
[[2]]
[1] "China"
[[3]]
[1] 21 32 11
> list_data[c(1,15,18)]
[[1]]
[1] "India"
[[2]]
[1] 12
[[3]]
[1] 7
> list_data[c(5,10,15)]
[[1]]
[1] TRUE
[[2]]
[1] "Asia" "Europe"
[[3]]
[1] 12
> list_data[c(7,3,10)]
[[1]]
[1] "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
[[2]]
[1] 21 32 11
[[3]]
[1] "Asia" "Europe"
Convert String to Float in Python - GeeksforGeeks

10 Jul, 2020
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting the string to float. In Python, we can use float() to convert String to float.
This function is used to convert any data type to a floating-point number.
Syntax:
float(x)
The method only accepts one parameter and that is also optional to use. If no argument is passed then the method returns 0.0.
Example 1:
Python3
string= "3.141"  print(string)print(type(string))  # converting string to floatFloat = float(string)    print(Float)print(type(Float))
Output:
3.141
<type 'str'>
3.141
<type 'float'>
Example 2:
Python3
string = '55.567'  float = float(string)  print(type(float))print('Float Value =', float)
Output:
<type 'float'>
('Float Value =', 55.567)
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions