code-rag-bench/online-tutorials huggingface dataset:
Python | Extract Strings with only Alphabets

22 Apr, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to extract only those strings which contains only alphabets and discard those which include digits. This has application in day-day programming and web development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using isalpha() + list comprehensionThe combination of above functions can be used to perform this task. In this, we extract the string which are alphabets only using isalpha() and compile whole logic using list comprehension.
# Python3 code to demonstrate working of # Extract Alphabet only Strings# Using isalpha() + list comprehension  # initializing listtest_list = ['gfg', 'is23', 'best', 'for2', 'geeks']  # printing original listprint("The original list is : " + str(test_list))  # Extract Alphabet only Strings# Using isalpha() + list comprehensionres = [sub for sub in test_list if sub.isalpha()]  # printing result print("Strings after filtering : " + str(res)) 
The original list is : ['gfg', 'is23', 'best', 'for2', 'geeks']
Strings after filtering : ['gfg', 'best', 'geeks']

 
Method #2 : Using filter() + lambdaThe combination of above methods can be used to perform this task. In this, we perform filtering using filter() and logic for extension to all strings is done using lambda.
# Python3 code to demonstrate working of # Extract Alphabet only Strings# Using filter() + lambda  # initializing listtest_list = ['gfg', 'is23', 'best', 'for2', 'geeks']  # printing original listprint("The original list is : " + str(test_list))  # Extract Alphabet only Strings# Using filter() + lambdares = list(filter(lambda sub: sub.isalpha(), test_list))  # printing result print("Strings after filtering : " + str(res)) 
The original list is : ['gfg', 'is23', 'best', 'for2', 'geeks']
Strings after filtering : ['gfg', 'best', 'geeks']

Python list-programs
Python string-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to trigger onchange event on input type=range while dragging in Firefox ?

21 Jun, 2019
Onchange: Onchange executes a JavaScript when a user changes the state of a select element. This attribute occurs only when the element becomes unfocused.
Syntax:
<select onchange="function()">

Attribute Value: It works on <select> element and fires the given JavaScript after the value is committed.
Example:
<!DOCTYPE html><html>  <head>    <title>Onchange</title>    <script type="text/javascript">        function Optionselection(select) {            var chosen = select.options[select.selectedIndex];            alert("Option Chosen by you is " + chosen.value);        }    </script></head>  <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <p>Choose an option from the following:</p>                <select onchange="Optionselection (this)">            <option value="C++" />C++            <option value="Java" />Java            <option value="Python" />Python        </select>    </center></body>  </html>
Output:Before:
After:
It is a frequent UI design for a range slider to showcase the immediate change in the depicted value as the user moves the slider. This is not the case for the above-mentioned browser (chrome included).Although, one could argue that Firefox showcases the correct behavior because the onchange event executes only when the control loses focus (be it mouse drag or keyboard). But in order to display the changing value along with the moving slider, one needs to apply the oninput event attribute.
Oninput: Much like the onchange event, this attribute works when it receives user input value. The main difference being its immediate execution when the value of element changes.
Syntax:
<element oninput = "script">
Program to illustrate Solution:
<!DOCTYPE html><html>  <head>    <title>onchange event on input type=range</title></head>  <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <p>onchange event on input "type=range"</p>          <span id="value"></span>        <input type="range"                min="1"               max="10"                step="1"                oninput="DisplayChange(this.value)">        <script>            function DisplayChange(newvalue) {                document.getElementById(                  "value").innerHTML = newvalue;            }        </script>    </center></body>  </html>
Output:Before:
After:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | get_headers() Function

20 May, 2019
The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request.
Syntax:
get_headers( $url, $format, $context )
Parameters: This function accepts three parameters as mentioned above and described below:
$url: It is a mandatory parameter of type string. It defines the target URL.
$format: It is an optional parameter of type int. If its value is set to non-zero it will return an associative array otherwise indexed array.
$context: It holds the valid resource context created by stream_context_create() function.
Example 1: In this example, value of optional parameter $format is not assigned.
<?php  // Target URL$url = "https://www.geeksforgeeks.org";  // Fetching headers$headers = get_headers($url);  // Printing headersprint_r($headers);?>
Output:
Array (
     [0] => HTTP/1.1 200 OK 
     [1] => Content-Type: text/html; charset=UTF-8 
     [2] => Connection: close 
     [3] => Date: Sun, 19 May 2019 08:31:29 GMT 
     [4] => Server: Apache 
     [5] => Strict-Transport-Security: max-age=3600; includeSubDomains 
     [6] => Cache-Control: s-maxage=21600, max-age=3, must-revalidate 
     [7] => Access-Control-Allow-Credentials: true 
     [8] => X-Frame-Options: DENY 
     [9] => X-Content-Type-Options: nosniff 
     [10] => Vary: Accept-Encoding, Cookie 
     [11] => X-Cache: Miss from cloudfront 
     [12] => Via: 1.1 aa0bb866c09b4e243eb9a97bcdb7fe32.cloudfront.net (CloudFront) 
     [13] => X-Amz-Cf-Id: QAOIIj4eBsrX0hyZ-UHjOtqA2dQePcLbEUZJ3KRohjsSPfcrcAFaiQ== 
) 

Example 2: In this example, value of optional parameter $format is set to non-zero.
<?php  // Target URL$url = "https://www.geeksforgeeks.org";  // Fetching headers$headers = get_headers($url, 1);  // Printing headersprint_r($headers);?>
Output:
Array ( 
        [0] => HTTP/1.1 200 OK 
        [Content-Type] => text/html; charset=UTF-8 
        [Connection] => close 
        [Date] => Sun, 19 May 2019 08:35:47 GMT 
        [Server] => Apache 
        [Strict-Transport-Security] => max-age=3600; includeSubDomains 
        [Cache-Control] => s-maxage=21600, max-age=3, must-revalidate 
        [Access-Control-Allow-Credentials] => true 
        [X-Frame-Options] => DENY 
        [X-Content-Type-Options] => nosniff 
        [Vary] => Accept-Encoding, Cookie 
        [X-Cache] => Miss from cloudfront 
        [Via] => 1.1 95d17b4d563934eb90636ad03f8f524e.cloudfront.net (CloudFront) 
        [X-Amz-Cf-Id] => se3QRyaWDeuHI3GrisMzAr4FJBamqMtbUNzhTPqAJhBoQZbWvy3UPw== 
) 

PHP-function
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How to get parameters from a URL string in PHP?
Primitive and Reference value in JavaScript

08 Jan, 2021
In JavaScript, a variable may store two type of values, Primitive values or Reference values. This article will describe and help to compare both these type of values.
1. Primitive value: JavaScript provides six type of primitive values that includes Number, String, Boolean, Undefined, Symbol, and BigInt. The size of Primitive values are fixed, therefore JavaScript stores the primitive value in the call stack (Execution context).
When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by Value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.
Let us take an example to understand primitive value:
Primitive value
Javascript
let age = 30;let age1 = age; // Pointing to age  console.log(`age = ${age}  age1 = ${age1}`);  age = 31; // Pointing to new address  console.log(`age = ${age}  age1 = ${age1}`);
Output:
 age = 30  age1 = 30
 age = 31  age1 = 30
2. Reference Value: JavaScript provides three types of Reference values that include Array, Object, and Function. The size of a reference value is dynamic therefore It is stored on Heap.
When we access a reference value, we manipulate it through reference, not through its actual value that is stored. Thus, variables that are reference values are accessed by reference. When we assign a reference value from one variable to another, the value stored in the variable is also copied into the location of the new variable but the difference is that the values stored in both variables now are the address of the actual object stored on the heap. As a result, both variables are referencing the same object, So we can manipulate the original object from both the variable.
Let us take an example to understand reference value:
Reference value
Javascript
let info = {    Name :"Abc",    Age :10}console.log(`Name : ${info.Name} Age : ${info.Age}`);  let info1 = info;info1.Age = 14; // Change the Age of original objectconsole.log(`Name : ${info.Name} Age : ${info.Age}`);
Output: 
Name : Abc Age : 10
Name : Abc Age : 14
JavaScript-Misc
Technical Scripter 2020
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Indexing a sublist

27 Mar, 2019
In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let’s discuss certain ways in which this can be performed.
Method #1 : Using index() + list comprehensionThis method solves this problem in 2 parts, for the first part it generates a new list and then it performs indexing on it.
# Python3 code to demonstrate# indexing of sublist # using list comprehension + index()  # initializing test listtest_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]  # printing original list print("The original list : " + str(test_list))  # using list comprehension + index()# indexing of sublistres = [ele for i, ele in test_list].index('For')  # print resultprint("Index of nested element is : " + str(res))
The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]
Index of nested element is : 1

 
Method #2 : Using next() + enumerate()This problem can be solved in an efficient manner using the combination of the above functions. The next function checks for the elements and enumerate functions separates the nested list elements.
# Python3 code to demonstrate# indexing of sublist # using enumerate() + next()  # initializing test listtest_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]  # printing original list print("The original list : " + str(test_list))  # using enumerate() + next()# indexing of sublistres = next((i for i, (j, ele) in enumerate(test_list) if ele == 'For'), None)  # print resultprint("Index of nested element is : " + str(res))
The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]
Index of nested element is : 1

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to make a loading gif in PyQT5?

02 Feb, 2021
PyQt5 is a GUI toolkit which can be used to develop GUI application in Python. It provides many modules that can help to build various components of the GUI application.
pip install PyQt5
Gif Link:  https://loading.io/
Import module
Create window and labels
Load GIF
Start GIF using start() 
Add mechanism to stop GIF using stop()
Execute code
Example:
Python3
import sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom PyQt5.QtGui import QMoviefrom PyQt5.QtCore import Qt    class LoadingGif(object):      def mainUI(self, FrontWindow):        FrontWindow.setObjectName("FTwindow")        FrontWindow.resize(320, 300)        self.centralwidget = QtWidgets.QWidget(FrontWindow)        self.centralwidget.setObjectName("main-widget")          # Label Create        self.label = QtWidgets.QLabel(self.centralwidget)        self.label.setGeometry(QtCore.QRect(25, 25, 200, 200))        self.label.setMinimumSize(QtCore.QSize(250, 250))        self.label.setMaximumSize(QtCore.QSize(250, 250))        self.label.setObjectName("lb1")        FrontWindow.setCentralWidget(self.centralwidget)          # Loading the GIF        self.movie = QMovie("loader.gif")        self.label.setMovie(self.movie)          self.startAnimation()      # Start Animation      def startAnimation(self):        self.movie.start()      # Stop Animation(According to need)    def stopAnimation(self):        self.movie.stop()    app = QtWidgets.QApplication(sys.argv)window = QtWidgets.QMainWindow()demo = LoadingGif()demo.mainUI(window)window.show()sys.exit(app.exec_())
Output:
The gif loading screen.
Picked
PyQt-exercise
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Python | datetime.timedelta() function
HTTP headers | Cross-Origin-Resource-Policy

28 Nov, 2019
The Cross-Origin-Resource-Policy is an HTTP response-type header that allows the servers to protect against certain cross-origin or cross-site embedding of the returned source. It complements the Cross-Origin Read Blocking (A mechanism which is used to prevent some cross-origin reads), so it is especially valuable for resources that are not covered by CORB. This also serves as an additional layer to the Same-Origin Policy. This helps in mitigating speculative side-channel attacks as well as Cross-Site Script Inclusion attacks.The Cross Origin Resource Policy is the only way to protect the images from Spectre attacks or compromised renderers.
However, because of a chrome bug, this response header can sometimes break file downloads and prevent the users from using Save as and Save image as on the resources.
Syntax:
Cross-Origin-Resource-Policy: same-site | same-origin | cross-site
Directives: This header accepts three directives as mentioned above and describes below:
same-site: This directive allowed users to read the resources only when the browser recognizes their requests from the same site (registrable domain).
same-origin: This directive allowed users to read the resources only when the browser recognizes their requests from the same origin ([scheme, host, port]).
cross-site: This directive allowed users requests from different sites can also read the resources.
Note: If a header is set during the Cross-origin resource check, then the browser will automatically deny all the no-cors requests issued by different origin or site.
Below examples illustrate the HTTP Cross-Origin-Resource-Policy:
Examples:
In the example below, only the requests that the browser recognizes as from the same site are allowed to read the resources.Cross-Origin-Resource-Policy: same-site
Cross-Origin-Resource-Policy: same-site
In the below example, only the requests that the browser recognizes as from the same origin are allowed to read the resources.Cross-Origin-Resource-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Supported Browsers: The browsers are compatible with the HTTP Cross-Origin-Resources-Policy are listed below:
Google Chrome
Firefox
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | is_uploaded_file( ) Function

08 Jun, 2018
The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST. This function can be used to ensure that a malicious user hasn’t tried to trick the script into working on files upon which it should not be working.
Syntax:
bool is_uploaded_file($file)
Parameters Used: This function accepts single parameter $file.
$file: It is a mandatory parameter which specifies the file.
Return Value: It returns True if the $file uploaded via HTTP POST. It returns true on success or false in failure. For proper working, the function is_uploaded_file() needs an argument like $_FILES[‘userfile’][‘tmp_name’], – the name of the uploaded file on the clients machine $_FILES[‘userfile’][‘name’] does not work.
Exceptions
An E_WARNING is emitted on failure.
The result of this function are cached and therefore the clearstatcache() function is used to clear the cache.
is_uploaded_file() function returns false for non-existent files.
Below programs illustrate the is_uploaded_file() function.
Program 1:
<?php// PHP program to illustrate is_uploaded_file() function.$myfile = "gfg.txt";  // checking whether the file is uploaded via HTTP POSTif (is_uploaded_file($file))    echo ("$file is uploaded via HTTP POST");else    echo ("$file is not uploaded via HTTP POST");?>
Output:
gfg.txt is not uploaded via HTTP POST

Program 2:
<?php   // checking whether the file is uploaded via HTTP POSTif (is_uploaded_file($_FILES['userfile']['gfg.txt'])) {    echo "File ". $_FILES['userfile']['gfg.txt'] .                      " uploaded successfully.\n";                            // displaying contents of the uploaded file    echo "Contents of the file are :\n";    readfile($_FILES['userfile']['gfg.txt']);} else{    echo "File ". $_FILES['userfile']['gfg.txt'] .                  " not uploaded successfully.\n";}?>
Output:
File gfg.txt uploaded successfully.
Contents of the file are :
Portal for geeks!

Reference:http://php.net/manual/en/function.is-uploaded-file.php
PHP-file-handling
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Windows 10 Toast Notifications with Python

08 Jan, 2019
Python is a general-purpose language, can be used to develop both desktop and web applications. By using a package available in Python named win10toast , we can create desktop notifications. It is an easy way to get notified when some event occurs.
The package is available in Pypi and it is installed using pip.
pip install win10toast
About show_toast() function:
Syntax: show_toast(title=’Notification’, message=’Here comes the message’, icon_path=None, duration=5, threaded=False)
Parameters:title: It contains notification title.message: It contains notification message.icon_path: It contains the path to .ico file.duration“: It specifies the notification destruction active duration.
To create notifications we have to import the win10toast module. Then create an object to ToastNotifier class and by using the method show_toast we create a notification. It contains header or title of that notification, actual message, duration of that notification and icon for that notification. show_toast method is a instance of notification settings.
Code #1:
# import win10toast from win10toast import ToastNotifier  # create an object to ToastNotifier classn = ToastNotifier()  n.show_toast("GEEKSFORGEEKS", "You got notification", duration = 10, icon_path ="https://media.geeksforgeeks.org/wp-content/uploads/geeks.ico")
Output:
Code #2:
# import win10toast from win10toast import ToastNotifier  # create an object to ToastNotifier classn = ToastNotifier()  n.show_toast("GEEKSFORGEEKS", "Notification body", duration = 20,  icon_path ="https://media.geeksforgeeks.org/wp-content/uploads/geeks.ico")
Output:
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
Matplotlib.axis.Axis.zoom() function in Python

08 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.zoom() function in axis module of matplotlib library is used to zoom in or out on axis .
Syntax: Axis.zoom(self, direction)  
Parameters: This method accepts the following parameters. 
direction: This parameter is the value to zoom in (direction > 0) or zoom out (direction <= 0).
Return value: This method does not return any value. 
Below examples illustrate the matplotlib.axis.Axis.zoom() function in matplotlib.axis: 
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np     fig, ax = plt.subplots() ax.plot([1, 2, 3])      ax.xaxis.zoom(3)   ax.grid()    fig.suptitle("""matplotlib.axis.Axis.zoom()function Example\n""", fontweight ="bold")       plt.show()
Output:  
Example 2: 
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons        fig, ax1 = plt.subplots() plt.subplots_adjust(bottom = 0.25) t = np.arange(0.0, 1.0, 0.001)   a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t)        ax1.plot(t, s, lw = 2, color = 'green')   ax1.xaxis.zoom(-2)   ax1.grid()    fig.suptitle("""matplotlib.axis.Axis.zoom()function Example\n""", fontweight ="bold")       plt.show()
Output:  
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ ios Library - Showpoint Function

It is used to sets the showpoint format flag for the str stream. When the showpoint format flag is set, the decimal point is always written for floating point values inserted into the stream (even for those whose decimal part is zero). Following the decimal point, as many digits as necessary are written to match the precision set for the stream (if any).
Following is the declaration for std::showpoint function.
ios_base& showpoint (ios_base& str);
str − Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee − if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::showpoint function.
#include <iostream>

int main () {
   double a = 30;
   double b = 10000.0;
   double pi = 3.1416;
   std::cout.precision (5);
   std::cout <<   std::showpoint << a << '\t' << b << '\t' << pi << '\n';
   std::cout << std::noshowpoint << a << '\t' << b << '\t' << pi << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
30.000  10000.  3.1416
30      10000   3.1416

 Print
 Add Notes
 Bookmark this page
p5.js | input() Function - GeeksforGeeks

17 Jan, 2020
The input() function is invoked whenever user input is detected on the element. It can be used to detect keystrokes or changes in the values of a slider. It can also be used to attach an event listener to an element.
Syntax:
input(fxn)
Parameters: This function accepts a single parameter as mentioned above and described below.
fxn: This is the callback function that would be called whenever input is detected. It can be passed ‘false’, which would prevent the previous firing function to stop firing.
Below example illustrates the input() function in p5.js:
Example:
function setup() {  createCanvas(600, 300);  textSize(28);  fill("green")  text("Write in the input box to change the text", 10, 20);     // create input box  let inputElem = createInput('');  inputElem.input(onInput);  inputElem.position(20, 40)}   function onInput() {  clear();  text("Write in the input box to change the text", 10, 20);     fill("green")  strokeWeight(10)  rect(0, 80, 600, 100)     // get the text entered  fill("black")  text(this.value(), 20, 120)}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/input
JavaScript-p5.js
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 calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to compare two arrays in JavaScript ? - GeeksforGeeks

04 Dec, 2021
In this article, the task is to compare two arrays, & we need to check the length of both arrays that should be the same, the objects present in them are of the same type and each item in one array is equal to the counterpart in another array. By doing this, we can conclude both arrays are the same or not. JavaScript provides a function JSON.stringify() method in order to convert an object or array into a JSON string. By converting into JSON strings, we can directly check if the strings are equal or not.
Example 1: This example uses the JSON.stringify() method to convert an object or array into a JSON string, then accordingly check for the given condition. If it satisfies the specific condition then it returns true otherwise, it will return false.
Javascript
<script>  var a = [1, 2, 3, 5];  var b = [1, 2, 3, 5];     // Comparing both arrays using stringify  if(JSON.stringify(a)==JSON.stringify(b))   document.write("True");  else   document.write("False");   document.write('<br>');  var f=[1, 2, 4, 5];  if(JSON.stringify(a)==JSON.stringify(f))   document.write("True");  else   document.write("False");</script>
Output:
True
False
Example 2: In this example, we manually check each and every item and return true if they are equal otherwise return false.
Javascript
<script>  function isEqual()  {   var a = [1, 2, 3, 5];   var b = [1, 2, 3, 5];        // If length is not equal    if(a.length!=b.length)     return "False";    else    {         // Comparing each element of array     for(var i=0;i<a.length;i++)     if(a[i]!=b[i])      return "False";      return "True";    }  }  var v = isEqual();  document.write(v);</script>
Output:
True
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
bhaskargeeksforgeeks
kapoorsagar226
javascript-array
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Node.js | os.userInfo() Method - GeeksforGeeks

07 Aug, 2021
The os.userInfo() method is an inbuilt application programming interface of the os module which is used to get the information of currently effective user.
Syntax: 
os.userInfo( options )
Parameters: This method accepts single parameter options which is optional parameter. It specifies the process options to be passed, and an object which contains encoding as a parameter returns. 
encoding: It specifies the character encoding for returned data. If it is set to ‘buffer’, then username, shell, homedir values will be buffer instances. Default value is ‘utf8’.
Return Value: It returns an object that specifies the information about the current effective user, which contains username, uid, gid, shell, homedir like values.
Note: On POSIX platform, this is generally a subset of password file contains username, uid, gid, shell, and homedir. Windows shell is set to null and uid, gid are -1.
Below examples illustrate the use of os.userInfo() in Node.js:
Example 1: 
Javascript
// Node.js program to demonstrate the  // os.userInfo() Method // Allocating os moduleconst os = require('os'); // Printing os.userInfo() valuestry {     // Printing user information    console.log(os.userInfo());} catch (err) {       // Printing if any exception occurs    console.log(": error occurred" + err);}
Output: 
{ uid: -1,
  gid: -1,
  username: 'gekcho',
  homedir: 'C:\\Users\\gekcho',
  shell: null }
Example 2: 
Javascript
// Node.js program to demonstrate the  // os.userInfo() Method // Allocating os moduleconst os = require('os'); // Printing os.userInfo()try{     // Setting options for os.userInfo()    // method    var options = {        encoding: 'buffer'    };     // Printing user information    console.log(os.userInfo(options));} catch(err){     // Printing exception if any    console.log(": error occurred" + err);}
Output: 
{ uid: -1,
  gid: -1,
  username: <Buffer 6d 75 6b 75 6c>,
  homedir: <Buffer 43 3a 5c 55 73 65 72 73 5c 6d 75 6b 75 6c>,
  shell: null }
Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/os.html#os_os_userinfo_options 
sweetyty
anikaseth98
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
How to find the minimum and maximum element of an Array using STL in C++? - GeeksforGeeks

18 Aug, 2021
Given an array arr[], find the minimum and maximum element of this array using STL in C++.Example: 
Input: arr[] = {1, 45, 54, 71, 76, 12}
Output: min = 1, max = 76

Input: arr[] = {10, 7, 5, 4, 6, 12}
Output: min = 4, max = 12
Approach:  
Min or Minimum element can be found with the help of *min_element() function provided in STL.
Max or Maximum element can be found with the help of *max_element() function provided in STL.
Syntax:  
*min_element (first, last);

*max_element (first, last);
To use *min_element() and *max_element() you must include “algorithm” as a header file.
The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
Below is the implementation of the above approach: 
CPP
// C++ program to find the min and max element// of Array using sort() in STL #include <bits/stdc++.h>using namespace std; int main(){    // Get the array    int arr[] = { 1, 45, 54, 71, 76, 12 };     // Compute the sizes    int n = sizeof(arr) / sizeof(arr[0]);     // Print the array    cout << "Array: ";    for (int i = 0; i < n; i++)        cout << arr[i] << " ";     // Find the minimum element    cout << "\nMin Element = "         << *min_element(arr, arr + n);     // Find the maximum element    cout << "\nMax Element = "         << *max_element(arr, arr + n);    // Storing the pointer in an address    int &min = *min_element(arr,arr+n );    int &max = *max_element(arr,arr+n );    cout<<"\nFinding the Element using address variable";    cout<<"\nMin Element = "<<min;    cout<<"\nMax Element = "<<max;    return 0;}
Array: 1 45 54 71 76 12 
Min Element = 1
Max Element = 76
Finding the Element using address variable
Min Element = 1
Max Element = 76
shubhamlightning99
nagpalharshit31
nayakvarsha99
cpp-array
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
Python | Convert String to tuple list - GeeksforGeeks

24 Jun, 2020
Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + split() + replace()This is a brute force method to perform this task. In this, we perform the task of extracting and remaking the tuples to list in a loop using split() and replace() functionalities.
# Python3 code to demonstrate working of# Convert String to tuple list# using loop + replace() + split()  # initializing string test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)"  # printing original string print("The original string is : " + test_str)  # Convert String to tuple list# using loop + replace() + split()res = []temp = []for token in test_str.split(", "):    num = int(token.replace("(", "").replace(")", ""))    temp.append(num)    if ")" in token:       res.append(tuple(temp))       temp = []  # printing resultprint("List after conversion from string : " + str(res))
The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6)
List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)]

 
Method #2: Using eval()This inbuilt function can also be used to perform this task. This function internally evaluates the string and returns the converted list of tuples as desired.
# Python3 code to demonstrate working of# Convert String to tuple list# using eval()  # initializing string test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)"  # printing original string print("The original string is : " + test_str)  # Convert String to tuple list# using eval()res = list(eval(test_str))  # printing resultprint("List after conversion from string : " + str(res))
The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6)
List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)]

nidhi_biet
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
How to create a MySQL table with InnoDB engine table?

To create a table with InnoDB engine, we can use the ENGINE command. Here is the query to create a table.
mysql> create table EmployeeRecords
- > (
- > EmpId int,
- > EmpName varchar(100),
- > EmpAge int,
- > EmpSalary float
- > )ENGINE=INNODB;
Query OK, 0 rows affected (0.46 sec)
We have set the ENGINE as INNODB above.
Check the full description about the table using the DESC command.
mysql> DESC EmployeeRecords;
The following is the output.
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| EmpId     | int(11)      | YES  |     | NULL    |       |
| EmpName   | varchar(100) | YES  |     | NULL    |       |
| EmpAge    | int(11)      | YES  |     | NULL    |       |
| EmpSalary | float        | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+
4 rows in set (0.05 sec)
To check if the table is created with InnoDB.
mysql> SHOW TABLE STATUS FROM business LIKE 'EmployeeRecords';
Here is the output −
+-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |
+-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+
| employeerecords | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-10-22 15:22:01 | NULL | NULL | utf8mb4_unicode_ci | NULL | | |
+-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+
1 row in set (0.10 sec)
In the above output, the “Engine” is visible as “InnoDB”.
Add only numeric values present in a list in Python

We have a Python list which contains both string and numbers. In this article we will see how to sum up the numbers present in such list by ignoring the strings.
The isinstance function can be used to filter out only the numbers from the elements in the list. Then we apply and the sum function and get the final result.
 Live Demo
listA = [1,14,'Mon','Tue',23,'Wed',14,-4]
#Given dlist
print("Given list: ",listA)
# Add the numeric values
res = sum(filter(lambda i: isinstance(i, int), listA))
print ("Sum of numbers in listA: ", res)
Running the above code gives us the following result −
Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
Sum of numbers in listA: 48
It is a similar approach as a wall except that we don't use filter rather we use the follow and the is instance condition. Then apply the sum function.
 Live Demo
listA = [1,14,'Mon','Tue',23,'Wed',14,-4]
#Given dlist
print("Given list: ",listA)
# Add the numeric values
res = sum([x for x in listA if isinstance(x, int)])
print ("Sum of numbers in listA: ", res)
Running the above code gives us the following result −
Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
Sum of numbers in listA: 48
Calculating median of an array JavaScript

We are required to write a JavaScript function that takes in an array of Numbers and returns its median.
The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average.
First, we will sort the array, if its size is even, we will need extra logic to deal with two middle numbers.
In these cases, we will need to return the average of those two numbers.
const arr = [4, 6, 2, 45, 2, 78, 5, 89, 34, 6];
const findMedian = (arr = []) => {
   const sorted = arr.slice().sort((a, b) => {
      return a - b;
   });
   if(sorted.length % 2 === 0){
      const first = sorted[sorted.length / 2 - 1];
      const second = sorted[sorted.length / 2];
      return (first + second) / 2;
   }
   else{
      const mid = Math.floor(sorted.length / 2);
      return sorted[mid];
   };
};
console.log(findMedian(arr));
And the output in the console will be −
6
Build an Application to translate English to Hindi in Python - GeeksforGeeks

15 Feb, 2022
In these articles, We are going to write python scripts to translate English word to Hindi word and bind it with the GUI application. We are using the English-to-Hindi module to translate the English word to the Hindi word.
Installation:
Run this code into your terminal:
pip install English-to-Hindi
Approach:
Import English to Hindi modules.
Create an object of EngtoHindi() by passing the message.
Use convert() methods for the translation.
Example:
Python3
# importing the modulefrom english to hindi.englishtohindi import EngtoHindi # message to be translatedmessage = "Yes, I am geeks" # creating a EngtoHindi() objectres = EngtoHindi(message) # displaying the translationprint(res.convert)
Output: 
हां, मैं गीक्स हूं
English to Hindi Translator Application with Tkinter: This Script implements the above Implementation into a GUI. 
Python3
# import modulesfrom tkinter import *from englishtohindi.englishtohindi import EngtoHindi # user define functiondef eng_to_hindi():    trans = EngtoHindi(str(e.get()))    res = trans.convert    result.set(res)   # object of tkinter# and background set for greymaster = Tk()master.configure(bg = 'light grey') # Variable Classes in tkinterresult = StringVar(); # Creating label for each information# name using widget LabelLabel(master, text="Enter Text : " , bg = "light grey").grid(row = 0, sticky = W)Label(master, text="Result :", bg = "light grey").grid(row = 3, sticky = W) # Creating label for class variable# name using widget EntryLabel(master, text="", textvariable=result,bg = "light grey").grid(row = 3,                                                                   column = 1,                                                                   sticky = W) e = Entry(master, width = 100)e.grid(row = 0, column = 1) # creating a button using the widget # Button that will call the submit functionb = Button(master, text = "Show", command = eng_to_hindi, bg = "Blue")b.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5,) mainloop()
Output: 
manikarora059
nnr223442
kk9826225
bijeshkumarch
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Wand Python - Introduction and Installation - GeeksforGeeks

15 May, 2020
Imagemagick is a tool developed to convert images from one format to another. Due to a versatile range of image formats and its precise and simple working, it has a huge community support. We can get images from pdf files.Wand is a binding developed for python by Imagemagick.wWand opens and manipulate images. Wand provides a large number of functions for image manipulation.
Uses of Wand Library:1. Read/Write images of different formats2. Converting images from one form to another3. Scaling and Cropping4. Add simple effects to image5. Add Special effects to images6. Transform images7. Other color Enhancements
Installation:Using pip:Wand can be easily installed by running
$ pip install Wand
in a terminal oR Command Prompt.
Installation on Linux:we can install Wand in Linux by running the below command
sudo apt-get install libmagickwand-dev
If we need SVG, WMF, OpenEXR, DjVu, and Graphviz support we have to install libmagickcore5-extra as well, to install libmagickcore5-extra run,
sudo apt-get install libmagickcore5-extra
in your terminal.
Installation on Mac:We can simply install wand by using brew command as below
 brew install imagemagick
in terminal.
Installation on Windows:You could build ImageMagick by yourself, but it requires a build toolchain like Visual Studio to compile it. The easiest way is simply downloading a prebuilt binary of ImageMagick for your architecture (win32 or win64). You can download it from here.
Below is a simple use case example of Wand library where we write python code to convert image from jpeg format to pngExample:
from __future__ import print_functionfrom wand.image import Image  with Image(filename ='koala.jpeg') as img:    with img.convert('png') as converted:        converted.save(filename ='png_koala.png')
Output:
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Check if element exists in list in Python
String slicing in Python to rotate a string

A string is given, our task is to slicing the string into two way. One is clockwise and another anticlockwise.
1. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).
2. Right (Or clockwise) rotate the given string by d elements (where d <= n).
Input: string = "pythonprogram"
d = 2
Output: Left Rotation: thonprogrampy
Right Rotation: ampythonprogr
Step 1: Enter string.
Step 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ].
Step 3: Now concatenate these two parts second + first accordingly.
def rotate(input,d):
   # Slice string in two parts for left and right
   Lfirst = input[0 : d]
   Lsecond = input[d :]
   Rfirst = input[0 : len(input)-d]
   Rsecond = input[len(input)-d : ]
   print ("Left Rotation : ", (Lsecond + Lfirst) )
      print ("Right Rotation : ", (Rsecond + Rfirst) )
      # Driver program
   if __name__ == "__main__":
      str = input("Enter String ::>")
d=2
rotate(str,d)
Enter String ::> pythonprogram
Left Rotation: thonprogrampy
Right Rotation: ampythonprogr