code-rag-bench/online-tutorials huggingface dataset:
Iterate associative array using foreach loop in PHP

24 May, 2019
Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays in the foreach loop. Both arrays can combine into a single array using a foreach loop.
Array: Arrays in PHP is a type of data structure that allows to storing multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed by using their index or key.
Example:
Input : $sides = array('Up', 'Down', 'Left', 'Right')
        $directions = array('North', 'South', 'West', 'East')

Output :
Up => North
Down => South
Left => West
Right => East

Example 1: This example uses foreach loop to display the elements of associative array.
<?php  // Declare an associative array$aso_arr = array(    "Up"=>"North",     "Down"=>"South",     "Left"=>"West",     "Right"=>"East");  // Use foreach loop to traverse each// elements of array and display its// key and value foreach($aso_arr as $side=>$direc) {    echo $side . " => " . $direc . "\n"; }  ?>
Up => North
Down => South
Left => West
Right => East

Example 2: This example uses array to display its index with value.
<?php  // Declare an array$sides = array("Up", "Down", "Left", "Right");  // Use foreach loop to display the// elements of arrayforeach($sides as $index => $value) {    echo "sides[" . $index . "] => " . $value . " \n";}  ?>
sides[0] => Up 
sides[1] => Down 
sides[2] => Left 
sides[3] => Right

Note: Every entry of the indexed array is similar to an associative array in which key is the index number.For example:
$sides = array("00"=>"Up", "01"=>"Down", "02"=>"Left", "03"=>"Right");
$directions = array("00"=>"North", "01"=>"South", "02"=>"West", "03"=>"East");
Since the index are common in all indexed arrays so it can use these indexes to access the value in other arrays.
Example 3:
<?php   // Declare and initialize array$sides = array("Up", "Down", "Left", "Right");$directions = array("North", "South", "West", "East");  // Use foreach loop to display array elementsforeach( $sides as $index => $side ) {    echo $side . " => " . $directions[$index] . " \n";}  ?>
Up => North 
Down => South 
Left => West 
Right => East

Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How to fetch data from localserver database and display on HTML table using PHP ?
Reduce Data Consumption on Windows OS

08 Jan, 2021
On a Windows machine, there is an option of “Data usages” settings to monitor your network consumption and avoid going over your data plan when using a limited internet connection. Windows introduced so many features like a built-in network traffic monitor for your system.
In this article, we will look into 6 ways to reduce your data usages on Windows 10.
Step 1: Open Window Settings
Step 2: Click on Network & Internet.
Step 3: Click on Data Usage
Step 4: Select the wireless or wired network adapter from the “Show settings” menu as per your requirement.
Step 5: Set the limit on the data usages by clicking the Set Limit button under “Data limit”.
Step 6: Select the limit type from Monthly, One time, and Unlimited. Then set the data limit and click on Save.
This will set your network adapter as metered and pause other activities like backup.
Restricting the usage of data by background applications, not in use currently can also reduce data consumption on a limited network. To do so follow the below steps:
Step 1: Open Window Settings
Step 2: Click on Network & Internet.
Step 3: Click on Data Usage.
Step 4: Under the Background data section you can set a limit on data usages by the Windows and store app features as shown below:
You can specifically restrict selected applications from using data in the background. To do so follow the below steps:
Step 1: Open Window Settings
Step 2: Click on Privacy.
Step 3: Click on App Permissions
Step 4: Select the apps you want not to run  in the background from the “Background apps” section as shown below:
You can disable the synchronization of your machine with the cloud. To do so follow the below steps:
Step 1: Open Window Settings
Step 2: Click on Accounts.
Step 3: Click on Sync your settings.
Step 4: Select off under “sync settings” as shown below:
You can turn off the Microsoft Store Update by following the below steps: t
Step 1: Open Microsoft Store.
Step 2: Click on Accounts.
Step 3: Set off the button under “App updates” as shown below:
Step 4: Select off under “sync settings” as shown below:
This also consumes a large amount of data. To turn off Windows automatic update follow the below steps:
Step 1: Open Window Settings.
Step 2: Click on Update & security.
Step 3: Click on Windows update.
Step 4: Click on Advance options.
Step 5: In the “Update options” select the button under“Pause updates” and set the duration for which the updates will be paused as shown below:
Technical Scripter 2020
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
How to setup cron jobs in Ubuntu
How to Add External JAR File to an IntelliJ IDEA Project?
Top Programming Languages for Android App Development
'dd' command in Linux
How to Delete Temporary Files in Windows 10?
How to join two arrays in JavaScript?

Following is the code to join two arrays together in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Join two arrays in JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to join the above two arrays together.</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 2, 3, 4];
   let arr1 = ["A", "B", "C", "D"];
   sampleEle.innerHTML = "arr = " + arr + " " + "arr1 = " + arr1;
   let mergedArr = arr.concat(arr1);
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "Merged array = " + mergedArr;
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
AngularJS | ng-minlength Directive - GeeksforGeeks

26 Mar, 2019
The ng-minlength Directive in AngularJS is used to set the minimum length for an input field i.e it adds the restriction for an input field. It is different from minlength attribute in HTML because the former prevent users from entering less than the specified limit whereas the later doesn’t do that. It makes the form invalid if the entered input is less than the specified limit.
Syntax:
<element ng-minlength="expression"> content ... </element> 
Where expression is a number denoting the minimum limit below which the input is invalid.
Example: This example uses ng-minlength Directive to set the minimum length of string.
<!DOCTYPE html><html>      <head>    <title>ng-minlength Directive</title>      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script></head>   <body style="text-align:center">          <h1 style="color:green">GeeksforGeeks</h1>          <h2>ng-minlength Directive</h2>          <div ng-app="app" ng-controller="geek">        <form name="minlength" novalidate ng-submit                    ="minlength.$valid &&check()">                      <pre>Minimum 5 characters required</pre>                          Input: <input type="text" name="code" ng-model="txtpin"                    ng-minlength="5" required />                          <br><br>                          <button type="submit">Click it</button>                          <br><br>                          <span>{{msg}}</span>        </form>    </div>          <script>        var app = angular.module('app', []);        app.controller('geek', function ($scope) {            $scope.check = function () {                $scope.msg = "Input is valid";            };        });    </script></body>  </html>
Output:Before clicking the button:After clicking the button:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Make a font italic with CSS

To make a font italic, use the font-style property. You can try to run the following code to learn how to work with the font-style property:
<html>
   <head>
   </head>
   <body>
      <p style = "font-style:italic;">
         This text is in italic style
      </p>
   </body>
</html>
KeyNotFoundException in C#

The KeyNotFoundException is thrown when a key you are finding is not available in the Dictionary
collection.
Let us see an example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      try {
         var dict = new Dictionary<string, string>() {
            {"TV", "Electronics"},
            {"Laptop", "Computers"},
         };
         Console.WriteLine(dict["Pen Drive"]);
      }
      catch (Exception e) {
         Console.WriteLine(e);
      }
   }
}
The following is the output. The error KeyNotFoundException is visible since the key is not in the
Dictionary −
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) [0x0001e] in
<902ab9e386384bec9c07fa19aa938869>:0
Set the opacity for the background color with CSS

To set the opacity for the background color, use the opacity property with RGBA color values.
You can try to run the following code to implement the opacity property:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            background: rgb(40, 135, 70);
            padding: 20px;
         }
         div.first {
            background: rgba(40, 135, 70, 0.2);
         }
         div.second {
            background: rgba(40, 135, 70, 0.6);
         }
      </style>
   </head>
   <body>
      <p>RGBA color values</p>
      <div class = "first"><p>20% opacity</p></div>
      <div class = "second"><p>60% opacity</p></div>
      <div><p>Default Opacity</p></div>
   </body>
</html>
Get the property of the difference between two objects in JavaScript

Let’s say, we are given two objects that have similar key value pairs with one or key having
different values in both objects. Our job is to write a function that takes in the two objects as
argument and returns the very first key it finds having different values. If all the keys have exact
same values, it should return -1.
Here are the sample objects −
const obj1 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 190000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
const obj2 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 19000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
We will take in the two objects, iterate over the first one using forEach() loop, checking for
equality in both objects, if the values at any point don’t match we will update a flag, exit out of
the loop and return the specific key. If we iterate through the whole loop, it means that
everything matched, in that case we will return -1.
The full code for this will be −
const obj1 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 190000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
const obj2 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 19000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
const difference = (obj1, obj2) => {
   let keyFound = false;
   Object.keys(obj1).forEach(key => {
      if(obj1[key] !== obj2[key]){
         return keyFound = key;
      }
   });
   return keyFound || -1;
};
console.log(difference(obj1, obj2));
The output in the console will be −
salary
Extract hyperlinks from PDF in Python

Python has a large set of libraries for handling different types of operations. To extract the data and meta-information from a PDF, we use the PyPdf2 package. It is easy to use and has many different operations or toolkits such as Extracting the data from the PDF, Searching Keyword in the Document, Extracting Meta Information such as finding Hyperlinks, URL and other information. Using the PyPDF2 package, we will extract the hyperlink from a pdf document.
We will follow these steps to extract the hyperlinks from a PDF,
Install PyPDF2 in the local machine by typing pip install PyPDF2 in the command shell.
Install PyPDF2 in the local machine by typing pip install PyPDF2 in the command shell.
Import PyPDF2.
Import PyPDF2.
Open the file in Binary mode and it recognizes the pattern of URL in the file.
Open the file in Binary mode and it recognizes the pattern of URL in the file.
Define a function to extract the link for a particular page.
Define a function to extract the link for a particular page.
Iterate over all the pages and extract the text using extractText() function.
Iterate over all the pages and extract the text using extractText() function.
To extract the hyperlinks from the PDF we generally use Pattern Matching Concept in Python. Now import re to find the pattern using regular expression.
To extract the hyperlinks from the PDF we generally use Pattern Matching Concept in Python. Now import re to find the pattern using regular expression.
Find the pattern that matches with http:// or https:// using findall(regex, string).
Find the pattern that matches with http:// or https:// using findall(regex, string).
If any URL found return the URL and print it on the screen.
If any URL found return the URL and print it on the screen.
# Import necessary packages
import PyPDF2
import re
# Open The File in the Command
file = open("newfile.pdf", 'rb')
readPDF = PyPDF2.PdfFileReader(file)
def find_url(string):
   #Find all the String that matches with the pattern
   regex = r"(https?://\S+)"
   url = re.findall(regex,string)
   for url in url:
      return url
# Iterating over all the pages of File
for page_no in range(readPDF.numPages):
   page=readPDF.getPage(page_no)
   #Extract the text from the page
   text = page.extractText()
   # Print all URL
   print(find_url(text))
# CLost the file
file.close()
Running the above code will print all the hyperlinks available in the given PDF document file.
What are the differences between PHP constants and variables ? - GeeksforGeeks

21 Oct, 2021
PHP Constants: PHP Constants are the identifiers that remain the same. Usually, it does not change during the execution of the script. They are case-sensitive. By default, constant identifiers are always uppercase. Usually, a Constant name starts with an underscore or a letter which is followed by a number of letters and numbers. They are no need to write a constant with the $ sign. The constant() function is used to return the value of a constant.
Example:
PHP
<?php   define("Hello", "Welcome to geeksforgeeks.com!");   echo Hello;?>
Output:
Welcome to geeksforgeeks.com!
PHP Variables: A PHP variable is a name given to a memory address that holds data. The basic method to declare a PHP variable is by using a $ sign which is followed by the variable name. A variable helps the PHP code to store information in the middle of the program. If we use a variable before it is assigned then it already has a default value stored in it. Some of the data types that we can use to construct a variable are integers, doubles, and boolean.
 
Example:
PHP
<?php   $txt = "Hello from geeksforgeeks!";   $x = 5;   $y = 10.5;   echo $txt;   echo "<br>";   echo $x;   echo "<br>";   echo $y;?>
Output:
Hello from geeksforgeeks!
5
10.5
Difference between PHP Constants and PHP Variables
The data type of PHP constant cannot be changed during the
execution of the script.
The data type of the PHP variable can be changed during the
execution of the script.
We can not define a constant using any simple assignment operator
rather it can only be defined using define().
PHP-Questions
Picked
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
Types of Restoration Filters - GeeksforGeeks

06 Dec, 2019
Restoration Filters are the type of filters that are used for operation of noisy image and estimating the clean and original image. It may consists of processes that are used for blurring or the reverse processes that are used for inverse of blur. Filter used in restoration is different from the filter used in enhancement process.
Types of Restoration Filters:There are three types of Restoration Filters: Inverse Filter, Pseudo Inverse Filter, and Wiener Filter. These are explained as following below.
1. Inverse Filter:Inverse Filtering is the process of receiving the input of a system from its output. It is the simplest approach to restore the original image once the degradation function is known.It can be define as:
H'(u, v) = 1 / H(u, v) 

Let,
F'(u, v) -> Fourier transform of the restored image
G(u, v) -> Fourier transform of the degraded image
H(u, v) -> Estimated or derived or known degradation function
then F'(u, v) = G(u, v)/H(u, v)
where, G(u, v) = F(u, v).H(u, v) + N(u, v)
and F'(u, v) = f(u, v) - N(u, v)/H(u, v) 
Note: Inverse filtering is not regularly used in its original form.
2. Pseudo Inverse Filter:Pseudo inverse filter is the modified version of the inverse filter and stabilized inverse filter. Pseudo inverse filtering gives more better result than inverse filtering but both inverse and pseudo inverse are sensitive to noise.Pseudo inverse filtering is defined as:
H'(u, v) = 1/H(u, v), H(u, v)!=0
H'(u, v) = 0, otherwise
3. Wiener Filter:(Minimum Mean Square Error Filter). Wiener filter executes and optimal trade off between filtering and noise smoothing. IT removes the addition noise and inputs in the blurring simultaneously. Weiner filter is real and even.It minimizes the overall mean square error by:
e^2 = F{(f-f')^2}
where, f -> original image
f' -> restored image
E{.} -> mean value of arguments

H(u, v) = H'(u, v)/(|H(u, v)|^2 + (Sn(u, v)/Sf(u, v))
where H(u, v) -> Transform of degradation function
Sn(u, v) -> Power spectrum of the noise
Sf(u, v) -> Power spectrum of the undergraded original image 
No blur only additive noise:
H(u, v)=1
W(u, v) = 1 / (1 + Sn(u, v)/Sf(u, v))
W(u, v) = SNR/(1 + SNR)
where, SNR = Sf(u, v)/Sn(u, v) 
No noise only blur:
Sn(u, v)=0
W(u, v) = 1/H(u, v) 
Drawbacks of Restoration Filters:
Not effective when images are restored fro the human eye.
Cannot handle the common cause of non-stationary signals and noise.
Cannot handle spatially variant blurring point spread function.
computer-graphics
Image-Processing
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
fgets() and gets() in C language
Association Rule
Recursive Functions
Java Math min() method with Examples
Activation Functions
Software Engineering | Prototyping Model
OOPs | Object Oriented Design
Characteristics of Internet of Things
Matrix Diagonalization - GeeksforGeeks

27 Apr, 2022
Prerequisite: Eigenvalues  and eigenvectors
Let A and B be two matrices of order n. B can be considered similar to A if there exists an invertible matrix P such that B=P^{-1} A P  This is known as Matrix Similarity Transformation.
Diagonalization of a matrix is defined as the process of reducing any matrix A into its diagonal form D. As per the similarity transformation, if the matrix A is related to D, then
 and the matrix A is reduced to the diagonal matrix D through another matrix P. Where P is a modal matrix) 
Modal matrix: It is a (n x n) matrix that consists of eigen-vectors. It is generally used in the process of diagonalization and similarity transformation.
In simpler words, it is the process of taking a square matrix and converting it into a special type of matrix called a diagonal matrix.
Steps Involved:
Step 1: Initialize the diagonal matrix D as:
where λ1, λ2, λ3 -> eigen values
Step 2: Find the eigen values using the equation given below.
 
where, A -> given 3×3 square matrix. I -> identity matrix of size 3×3. λ -> eigen value.
Step 3: Compute the corresponding eigen vectors using the equation given below. where, λi -> eigen value. Xi -> corresponding eigen vector.
Step 4: Create the modal matrix P.
Here, all the eigenvectors till Xi have filled column-wise in matrix P. 
Step 5: Find P-1 and then use the equation given below to find diagonal matrix D.
Problem Statement: Assume a 3×3 square matrix A having the following values:
Find the diagonal matrix D of A using the diagonalization of the matrix. [ D = P-1AP ]
Solution:Step 1: Initializing D as:
Step 2: Find the eigen values. (or possible values of λ)
Step 3: Find the eigen vectors X1, X2, X3 corresponding to the eigen values λ = 1,2,3. 
Step 5: Creation of modal matrix P. (here, X1, X2, X3 are column vectors)
Step 6: Finding P-1 and then putting values in diagonalization of a matrix equation. [D = P-1AP]
 
We do Step 6 to find out which eigenvalue will replace λ1, λ2, and λ3 in the initial diagonal matrix created in Step 1. 
 
We know that 
On solving, we get  
Putting in the Diagonalization of Matrix equation, we get 
 
Matlab
% MATLAB Implementation for% Diagonalization of a Square Matrix:clear allclc      disp("MATLAB Implementation for Diagonalization of a Square Matrix | GeeksforGeeks")A = input("Enter a matrix A : ");[P , D] = eig(A);D1 = inv(P)*(A)*(P);disp("Diagonal form 'D' of Input Matrix 'A' is:")disp(D1)
 Output:
For the Matrix: 
 
 For the Matrix:  
 
simmytarika5
kothavvsaakash
ML-Statistics
Machine Learning
Mathematical
Mathematical
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Python VLC MediaListPlayer - Currently Playing - GeeksforGeeks

29 Aug, 2020
In this article we will see how we can check if the media is playing or not in the MediaListPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Media list player is used to play multiple media in a row for example playing a series, instead of taking single media it accepts media list. Its working is almost similar like the MediaPlayer object but it is capable of playing list of media. We can pause and resume the media list player any time with the help of set_pause method, and it can be start playing with the help of play method.
In order to do this we will use is_playing method with the MediaListPlayer object
Syntax : media_list_player.is_playing()
Argument : It takes no argument
Return : It returns bool
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating a media player objectmedia_player = vlc.MediaListPlayer()  # creating Instance class objectplayer = vlc.Instance()  # creating a new media list objectmedia_list = player.media_list_new()  # creating a new mediamedia = player.media_new("death_note.mkv")  # adding media to media listmedia_list.add_media(media)  # setting media list to the media playermedia_player.set_media_list(media_list)    # start playing videomedia_player.play()    # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)  # getting media player playing statevalue = media_player.is_playing()  # printing valueprint(value)
Output :
1

Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating a media player objectmedia_player = vlc.MediaListPlayer()  # creating Instance class objectplayer = vlc.Instance()  # creating a new media listmedia_list = player.media_list_new()  # creating a new mediamedia = player.media_new("1.mp4")  # adding media to media listmedia_list.add_media(media)  # setting media list to the media playermedia_player.set_media_list(media_list)    # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)  # getting media player playing statevalue = media_player.is_playing()  # printing valueprint(value)
Output :
1

Python vlc-mediaPlayer
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
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
How to reverse the order of given vector in R? - GeeksforGeeks

30 May, 2021
In this article, we will discuss how to reverse the order of elements in a vector in R Programming Language.
It can be done using the rev() function. It returns the reverse version of data objects.
Syntax: rev(x)
Parameter: x: Data object
Returns: Reverse of the data object passed
Example 1: Here we will create a vector and reverse it with rev() function.
R
# create vector with namesvec = c("sravan", "mohan", "sudheer",         "radha", "vani", "mohan")  print("Original vector-1:")print(vec)rv = rev(vec)  print("The said vector in reverse order:")print(rv)
Output:
[1] “Original vector-1:”
[1] “sravan”  “mohan”   “sudheer” “radha”   “vani”    “mohan”  
[1] “The said vector in reverse order:”
[1] “mohan”   “vani”    “radha”   “sudheer” “mohan”   “sravan”
Example 2: Here we will create multiple vectors and then reverse them.
R
# create vector with namesname = c("sravan", "mohan", "sudheer",         "radha", "vani", "mohan")  # create vector with subjectssubjects = c(".net", "Python", "java",              "dbms", "os", "dbms")  # create a vector with marksmarks = c(98, 97, 89, 90, 87, 90)  # create vector with heightheight = c(5.97, 6.11, 5.89,           5.45, 5.78, 6.0)  # create vector with weightweight = c(67, 65, 78,           65, 81, 76)  # pass these vectors to the vectordata = c(name, subjects, marks,         height, weight)# displayprint("Original vector-1:")print(data)rv = rev(data)  print("The said vector in reverse order:")print(rv)
Output:
[1] “Original vector-1:”
 [1] “sravan”  “mohan”   “sudheer” “radha”   “vani”    “mohan”   “.net”   
 [8] “Python”  “java”    “dbms”    “os”      “dbms”    “98”      “97”     
[15] “89”      “90”      “87”      “90”      “5.97”    “6.11”    “5.89”   
[22] “5.45”    “5.78”    “6”       “67”      “65”      “78”      “65”     
[29] “81”      “76”     
[1] “The said vector in reverse order:”
 [1] “76”      “81”      “65”      “78”      “65”      “67”      “6”      
 [8] “5.78”    “5.45”    “5.89”    “6.11”    “5.97”    “90”      “87”     
[15] “90”      “89”      “97”      “98”      “dbms”    “os”      “dbms”   
[22] “java”    “Python”  “.net”    “mohan”   “vani”    “radha”   “sudheer”
[29] “mohan”   “sravan” 
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
ZoneId getId() method in Java with Examples - GeeksforGeeks

10 May, 2019
The getId() method of the ZoneId class in Java is used to get the unique time-zone ID which uniquely defines this object.
Syntax:
public String getId(Object obj)

Parameters: This method accepts nothing.
Return value: This method returns the time-zone unique ID.
Below programs illustrate the getId() method:Program 1:
// Java program to demonstrate// ZoneId.getId() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create ZoneId object        ZoneId zoneId            = ZoneId.of("Europe/Paris");          // get and print Id        System.out.println("Id: "                           + zoneId.getId());    }}
Id: Europe/Paris

Program 2:
// Java program to demonstrate// ZoneId.getId() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create ZoneId object        ZoneId zoneId            = ZoneId.of("Asia/Calcutta");          // get and print Id        System.out.println("Id: "                           + zoneId.getId());    }}
Id: Asia/Calcutta

Reference:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#getId()
Kirti_Mangal
Java-Functions
Java-time package
Java-ZoneId
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
HTML - <plaintext> Tag

The HTML <plaintext> tag is used to render all text in the document exactly as it was typed in, including all tags and even the document tags.
This tag ignores all formatting for the rest of the document, displaying all text exactly as is. It cannot be stopped, it cannot be turned off. It is deprecated because it messes up the balance of the document tags.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML plaintext Tag</title>
   </head>

   <body>
   </body>
   
</html>
This tag is available in Netscape 4 and higher version only.

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to convert Image into base64 String in Android?

This example demonstrates how to do I in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
<TextView
   android:id="@+id/textView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_centerInParent="true"
   android:textSize="12sp"
   android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @SuppressLint("WrongThread")
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.instaimage);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
      byte[] imageBytes = byteArrayOutputStream.toByteArray();
      String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
      textView.setText(imageString);
   }
}

Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
File listRoots() method in Java with examples - GeeksforGeeks

28 Jan, 2019
The listRoots() method is a part of File class. The listRoots() function returns the root directories of all the available file System roots. It is guaranteed that the pathname of any file on the system will begin with any one of these roots.
Function Signature:
public static File[] listRoots()
Syntax:
File.listRoots()
Parameters: The function do not requires any parameters.
Return Value: The function returns File array, which contains all the file system roots .
Exception: This method do not throw any exceptions
Below programs will illustrate the use of listRoots() function:
Example 1: Try display all the root directories of the system
// Java program to demonstrate// the use of File.listRoots() method  import java.io.*;  public class GFG {      public static void main(String args[])    {        // roots of the path name        File root[] = File.listRoots();          // check if the root is null or not        if (root != null) {            System.out.print("Roots are: ");              // display the roots of the path name            for (int i = 0; i < root.length; i++) {                System.out.print(root[i].getPath() + " ");            }        }        else            System.out.println("There are no roots");    }}
Output:
Roots are: C:\ D:\ E:\ F:\ G:\ 
The programs might not run in an online IDE. please use an offline IDE and set the path of the file
Java-File Class
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Java Program to Convert String to String Array
Modulo or Remainder Operator in Java
SHA-1 Hash
Comparing two ArrayList In Java
How to Replace a Element in Java ArrayList?
JasmineJS - Exception Check

Apart from different computational matchers, Jasmine provides some useful matchers to check exception of the program. Let us modify our JavaScript with the following set of code.
var throwMeAnError = function() {   
   throw new Error(); 
};  

describe("Different Methods of Expect Block", function() {  
   var exp = 25; 

   it ("Hey this will throw an Error ", function() { 
      expect(throwMeAnError).toThrow(); 
   }); 
});
In the above example, we have created one method which deliberately throws an exception from that method and in the expect block we expect to catch the error. If everything goes well then this piece of code will yield the following output.
Now, for this test case to fail, we need to omit that throw statement in the function throwMeAnError. Following is the code which will yield a red screenshot as an output since the code does not satisfy our requirement.
var throwMeAnError = function() {   
   //throw new Error(); 
};   

describe("Different Methods of Expect Block",function() {  
   var exp = 25; 
   
   it("Hey this will throw an Error ", function() {  
      expect(throwMeAnError).toThrow();    
   }); 
});
As can be seen, we have commented that line from where our method was throwing the exception. Following is the output of the above code on successful execution of the SpecRunner.html.
Any is the special matcher that is used when we are not sure about the output. In the following example, we will learn how this works. Let us modify the customerMatcher.js with the following piece of code.
var addAny = function() {
   var sum = this.currentVal; 
	
   for (var i = 0; i < arguments.length; i++) { 
      sum += arguments[i]; 
   } 
	
   this.currentVal = sum;  
   return this.currentVal; 
} 

describe("Different Methods of Expect Block",function () { 
   
   it("Example of any()", function() { 
      expect(addAny(9,9)).toEqual(jasmine.any(Number)); 
   });
});
Here we have declared one function that will give us the summation of the numbers provided as arguments. In the expect block, we are expecting that the result can be anything but it should be a Number.
As both 9 and 9 after sum yield 18 is a number, this test will pass and it will generate the following green screenshot as an output.
Now let us change the code according to the following piece of code, where we are expecting a string type variable as an output of the function AddAny().
var addAny = function() { 
   var sum = this.currentVal; 
	
   for(var i = 0; i < arguments.length; i++) { 
      sum += arguments[i]; 
   } 
	
   this.currentVal = sum; 
   return this.currentVal; 
}  

describe("Different Methodsof Expect Block",function () { 
   it("Example of any()", function () { 
      expect(addAny(9,9)).toEqual(jasmine.any(String));    
   });
});
Following is the output of the above code.
 Print
 Add Notes
 Bookmark this page
p5.js map() Function - GeeksforGeeks

17 Feb, 2021
The map() function in p5.js is used to normalize a number having range from min1 to max1 in a range of min2 to max2.
Normalization is very helpful in p5.js if you are scaling your elements. Because as we know normalization takes care of all the proportions in scaling so, we get a completely balanced scaling.
Not just scaling but in any transformation operations normalization is very helpful.
Syntax:
map(value, start1, stop1, start2, stop2, [withinBounds])
Parameters: This function accepts six parameters as mentioned above and described below:
value: The value you want to normalize.
min1: Minimum value of the value’s current range.
max1: Maximum value of the value’s current range.
min2: Minimum value of the value’s target range.
max2: Maximum value of the value’s target range.
withinBounds (optional): This restricts the normalized value of value in range of [min2, max2].
Example 1: WithinBounds is false by default.
Javascript
function setup() {    noLoop();}  function draw() {      background(220);      // Assume value has range [0, 100]    let value = 50;      // We want to convert value     // in range of [0, 50]    let newValue = map(value, 0, 100, 0, 50);      console.log(newValue);}
Output:
25
Example 2: Notice how withinBounds constraints range of value
Javascript
function setup() {    noLoop();}  function draw() {      background(204);      // Value has a range[0, 100]    let value = 150;      // We are mapping it in range of [0, 50]    let newValue1 = map(value, 0, 100, 0, 50);      console.log(newValue1);      // Notice the last parameter is true    // we are mapping it in range of [0, 50]    let newValue2 = map(value, 0, 100, 0, 50, true);      console.log(newValue2);}
Output:
75
50
JavaScript-p5.js
Technical Scripter 2020
JavaScript
Technical Scripter
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?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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
Python program to print hello world - GeeksforGeeks

31 Aug, 2021
Prerequisite: Python Language Introduction, Python 3 basics
In this article, we will look into How to print “Hello World” in Python.
Here we will be using the python print() function for the same. The print() function in python is used to print python objects as strings as standard output.
The python print function has the following syntax:
Syntax: Print(“string”)
Where: String: This string will be “Hello world”
Implementation:
Python3
# python program to print "Hello World"print("Hello World")
Output:
Hello World
In this method we are going to print string using the sys module, sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. 
sys.std.write() : stdout is used to display output directly to the screen console.
Syntax: sys.stdout.write(“String”)
Code:
Python3
import sys  sys.stdout.write("Hello World")
Output:
Hello World
Picked
python-basics
Python
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Matplotlib.figure.Figure.set_constrained_layout() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_constrained_layout() method figure module of matplotlib library is used to set whether constrained_layout is used upon drawing.
Syntax: set_constrained_layout(self, constrained)
Parameters: This method accept the following parameters that are discussed below:
constrained: This parameter is the bool or dict or None.
Returns: This method returns the axes.
Below examples illustrate the matplotlib.figure.Figure.set_constrained_layout() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt     fig, ax = plt.subplots(constrained_layout = True)x = np.arange(0.02, 1, 0.02)  np.random.seed(19680801)y = np.random.randn(len(x)) ** 2  ax.loglog(x, y)  ax.set_xlabel('f [Hz]')ax.set_ylabel('PSD')ax.set_title('Random spectrum')      def forward(x):    return 1 / x      def inverse(x):    return 1 / x  fig.set_constrained_layout(True)  fig.suptitle("""matplotlib.figure.Figure.set_constrained_layout()function Example\n\n""", fontweight ="bold")      plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec     fig = plt.figure()gs = fig.add_gridspec(3, 3)ax = fig.add_subplot(gs[0, :])  ax.set_title('gs[0, :]')ax2 = fig.add_subplot(gs[1, :-1])ax2.set_title('gs[1, :-1]')  fig.set_constrained_layout(False)  fig.suptitle("""matplotlib.figure.Figure.set_constrained_layout()function Example\n\n""", fontweight ="bold")      plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()