code-rag-bench/online-tutorials huggingface dataset:
Create Password Protected Zip of a file using Python - GeeksforGeeks

24 Jan, 2021

ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together.
In this article, we will learn how to Create Password-Protected Zip of a file using Python. For this, we are using pyminizip module from python.
 The pyminizip module can be installed using the below command:
pip install pyminizip
For creating zip, we are using compress() method from pyminizip. So, we discuss first its syntax and arguments.
pyminizip.compress(“/srcfile/path.txt”, “file_path_prefix”, “/distfile/path.zip”, “password”, int(compress_level))
Arguments:
src file path (string)
src file prefix path (string) or None (path to prepend to file)
dst file path (string)
password (string) or None (to create no-password zip)
compress_level(int) between 1 to 9, 1 (more fast) <—> 9 (more compress) or 0 (default) 
Return value: Always returns None
Input file:
Program:
Python3
 

 
 










# importing module 
import pyminizip 
  
# input file path 
inpt = "./Text.txt"
  
# prefix path 
pre = None
  
# output zip file path 
oupt = "./output.zip"
  
# set password value 
password = "GFG"
  
# compress level 
com_lvl = 5
  
# compressing file 
pyminizip.compress(inpt, None, oupt, 
                   password, com_lvl) 






Output:

python-utility


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates
Count the number of times a letter appears in a text file in Python - GeeksforGeeks

05 Jan, 2022
In this article, we will be learning different approaches to count the number of times a letter appears in a text file in Python. Below is the content of the text file gfg.txt that we are going to use in the below programs:
Now we will discuss various approaches to get the frequency of a letter in a text file.
Method 1: Using the in-built count() method.
Approach:
Read the file.
Store the content of the file in a variable.
Use the count() method with the argument as a letter whose frequency is required.
Display the count of the letter.
Implementation:
Python3
# Program to get letter count in a text file # explicit function to return the letter countdef letterFrequency(fileName, letter):    # open file in read mode    file = open(fileName, 'r')     # store content of the file in a variable    text = file.read()     # using count()    return text.count(letter)  # call the function and display the letter countprint(letterFrequency('gfg.txt', 'g'))
Output:
Method 2: Iterate through the file content in order to compare each character with the given letter.
Approach:
Read the file.
Store the content of the file in a variable.
Assign a counter count variable with 0.
Iterate through each character, if the character is found to be the given letter then increment the counter.
Display the count of the letter.
Implementation:
Python3
# Program to get letter count in a text file # explicit function to return the letter countdef letterFrequency(fileName, letter):    # open file in read mode    file = open(fileName, "r")     # store content of the file in a variable    text = file.read()     # declare count variable    count = 0     # iterate through each character    for char in text:         # compare each character with        # the given letter        if char == letter:            count += 1     # return letter count    return count  # call function and display the letter countprint(letterFrequency('gfg.txt', 'g'))
Output:
as5853535
gulshankumarar231
Picked
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to change the <input> type? - GeeksforGeeks

18 Apr, 2021
The purpose of this article is to change the HTML <input> type. Javascript provides document.getElementById().type option to change the type of input field.
Syntax:
The selected input type will change to text.document.getElementById("id_of_tag_to_be_changed").type="text"; 
document.getElementById("id_of_tag_to_be_changed").type="text"; 
The selected input type will change to a button.document.getElementById("id_of_tag_to_be_changed").type="button";
document.getElementById("id_of_tag_to_be_changed").type="button";
The selected input type will change to a date.document.getElementById("id_of_tag_to_be_changed").type="date"; 
document.getElementById("id_of_tag_to_be_changed").type="date"; 
Example:
HTML
<!DOCTYPE html><html>  <body>    <p>      Please click on Button2 to see the type       of Button1 change from button to text    </p>      <input      id="inputfield1"      type="button"      value="Input1"      onclick="alert('I am Input1 click on Input2 to see me change my type')"/>    <input      id="inputfield2"      type="button"      value="Input2"      onclick="typeChanger()"/>  </body>  <script>    function typeChanger() {      alert("The type of Input1 will now change from button to text");      document.getElementById("inputfield1").type = "text";    }  </script></html>
Output:
Input to text
Note: Some Old Browsers do not allow a dynamic change in the type of input fields.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
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?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Check if list contains all unique elements in Python

A list in python can contain elements all of which may or may not be unique. But for a scenario when we need unique elements like marking the attendance for different roll numbers of a class. Below is the approaches with can use.
A python set is a collection which is unordered, unindexed and also contains unique elements. So we will compare the length of the set created from the list with the length of the list itself. They will be equal only if there are unique elements in the list.
 Live Demo
# Given List
Alist = ['Mon','Tue','Wed']
print("The given list : ",Alist)

# Compare length for unique elements
if(len(set(Alist)) == len(Alist)):

   print("All elements are unique.")
else:
   print("All elements are not unique.")
Running the above code gives us the following result −
The given list : ['Mon', 'Tue', 'Wed']
All elements are unique.
Running the same program again without having unique elements.
 Live Demo
# Given List
Alist = ['Mon','Tue','Wed','Mon']
print("The given list : ",Alist)

# Compare length for unique elements
if(len(set(Alist)) == len(Alist)):

   print("All elements are unique.")
else:
   print("All elements are not unique.")
Running the above code gives us the following result −
The given list : ['Mon', 'Tue', 'Wed', 'Mon']
All elements are not unique.
We can also use the in-built count() which will count the frequency of each element in the list. If the count is greater than 1 then we have duplicates in the list.
 Live Demo
# Given List
list1 = ['Mon','Tue','Wed','Mon']
list2 = ['Mon','Tue','Wed']


def dupcheck(x):
   for elem in x:
      if x.count(elem) > 1:
         return True
      return False

if dupcheck(list1):
   print("The given list : ", list1)
   print("There are duplicates.")
else:
   print("The given list : ", list1)
   print("No duplicates.")

if dupcheck(list2):
   print("The given list : ", list2)
   print("There are duplicates.")
else:
   print("The given list : ", list2)
   print("No duplicates.")
Running the above code gives us the following result −
The given list : ['Mon', 'Tue', 'Wed', 'Mon']
There are duplicates.
The given list : ['Mon', 'Tue', 'Wed']
No duplicates.
Difference between window.location.href, window.location.replace and window.location.assign in JavaScript?

The window object includes the location object in JavaScript. It includes the following properties −
It returns the URL of the current page.
<!DOCTYPE html>
<html>
   <body>
      <p>Click below to get the complete URL of the page.</p>
      <button onclick = "display()">URL</button>
      <script>
         function display() {
            var res = location.href;
            document.write(res);
         }
      </script>
   </body>
</html>
It is used to replace the current document.
<!DOCTYPE html>
<html>
   <body>
      <button onclick = "display()">Replace current document</button>
      <script>
         function display() {
            location.replace("https://www.qries.com")
         }
      </script>
   </body>
</html>
If you want to load a new document, use JavaScript assign.
<!DOCTYPE html>
<html>
   <body>
      <button onclick = "display()">Open new document</button>
      <script>
         function display() {
            location.assign("https://www.qries.com")
         }
      </script>
   </body>
</html>
Difference between RGB vs RGBA color format - GeeksforGeeks

07 Apr, 2021
In this article, we will discuss the differences between RGB and RGBA color schemes in detail. We will also see how these schemes can be used in CSS.
RGB Color Scheme: It is a three-channel format containing data for red, green, and blue colors. In CSS, the RGB color format can be specified using:
rgb(red, green, blue)
Each parameter in rgb() function defines the intensity of colors in a range of 0 to 255. The value 0 defines no color of that type being used while 255 defines the highest value of that color being used.
RGBA Color Scheme: The RGBA color format is an extension of the RGB scheme with an added alpha channel that specifies the opacity of the color. In CSS, the RGBA color format can be specified using:
rgba(red, green, blue, alpha)
The alpha value is declared as a decimal number from 0 to 1, where 0 is fully transparent and 1 is fully opaque.
The below example demonstrates the difference between these two color schemes.
Example:
HTML
<html><head>  <style>    div {      height: 75px;      width: 500px;      padding: 10px;      font-size: 1.5rem;    }      #div1 {      background-color: rgb(255, 0, 0);    }      #div2 {      background-color: rgb(0, 192, 192);    }      #div3 {      background-color: rgb(255, 0, 0, 0.1);    }      #div4 {      background-color: rgb(0, 192, 192, 0.6);    }  </style></head><body>  <h1 style="color: green">    GeeksforGeeks  </h1>  <h3>    Difference between RGB and     RGBA color scheme  </h3>    <p>An RGB color value is specified    with the rgb() function:    rgb(red, green, blue)  </p>      <p>An RGBA color value is specified     with the rgba() function:    rgba(red,green,blue,opacity)  </p>      <div id="div1">Red with rgb()</div>  <div id="div2">Color with rgb()</div>    <div id="div3">    Red with rgba()     and alpha  </div>  <div id="div4">    Color with rgba()    and alpha  </div></body></html>
Output:
Key Differences between RGB Color Format and RGBA Color Format:
CSS-Basics
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Null List in C#

A null list exists in C#. To check whether a list is null or not, check them against the null literal.
Set a null like this −
List<string> myList = null;
Now, to check for null, use the equality operator −
myList == null;
The following is an example −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
   public static void Main() {
      List<string> myList = null;
      // checking for null
      Console.WriteLine(myList == null);
   }
}
True
Getting inverse cosine and inverse hyperbolic cosine in Julia - acos(), acosh() and acosd() Methods - GeeksforGeeks

26 Mar, 2020
The acos() is an inbuilt function in julia which is used to calculate inverse cosine of the specified value and output is in radians.
Syntax: acos(x)
Parameters:
x: Specified values.
Returns: It returns the calculated inverse cosine of the specified value and output is in radians.
Example:
# Julia program to illustrate # the use of acos() method  # Getting inverse cosine of the specified# values and output is in radians.println(acos(0))println(acos(-0.444))println(acos(0.7774))println(acos(1))
Output:
1.5707963267948966
2.0308542405657466
0.6802746363624282
0.0
The acosh() is an inbuilt function in julia which is used to calculate inverse hyperbolic cosine of the specified value.
Syntax: acosh(x)
Parameters:
x: Specified values.
Returns: It returns the calculated inverse hyperbolic cosine of the specified value.
Example:
# Julia program to illustrate # the use of acosh() method  # Getting inverse hyperbolic cosine of the# specified values.println(acosh(2))println(acosh(10))println(acosh(74))println(acosh(45))
Output:
1.3169578969248166
2.993222846126381
4.997166616875528
4.499686190671499
The acosd() is an inbuilt function in julia which is used to calculate inverse cosine of the specified value and output is in degrees.
Syntax: acosd(x)
Parameters:
x: Specified values.
Returns: It returns the calculated inverse cosine of the specified value and output is in degrees.
Example:
# Julia program to illustrate # the use of acosd() method  # Getting inverse cosine of the specified# values and output is in degrees.println(acosd(0))println(acosd(-0.444))println(acosd(0.7774))println(acosd(1))
Output:
90.0
116.35937679066326
38.976865573363945
0.0
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get array dimensions and size of a dimension in Julia - size() Method
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Get number of elements of array in Julia - length() Method
Exception handling in Julia
Getting the maximum value from a list in Julia - max() Method
Working with Excel Files in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Getting the absolute value of a number in Julia - abs() Method
Working with Date and Time in Julia
JSF - h:setPropertyActionListener

The h:setPropertyActionListener tag adds an action listener to a component that sets a bean property to a given value.
<h:commandButton id = "submit" action = "result" value = "Show Message">  
   <f:setPropertyActionListener target = "#{userData.data}"  
      value = "JSF 2.0 User" /> 
</h:commandButton> 
Let us create a test JSF application to test the above tag.
package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;
   public String data = "1";

   public String getData() {
      return data;
   }

   public void setData(String data) {
      this.data = data;
   }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
   <head>
      <title>JSF Tutorial!</title>
   </head>
   
   <body>
      <h2>f:attribute example</h2>
      <hr />
      
      <h:form>
         <h:commandButton id = "submit" action = "result" value = "Show Message"> 
            <f:setPropertyActionListener 
            target = "#{userData.data}" value = "JSF 2.0 User" />
         </h:commandButton>
      </h:form>
   
   </body>
</html>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:f = "http://java.sun.com/jsf/core"    
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:ui = "http://java.sun.com/jsf/facelets">
   
   <head>
      <title>JSF Tutorial!</title>
   </head>
   
   <h:body>
      <h2>Result</h2>
      <hr />
      #{userData.data}
   </h:body>
</html>  
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Press Show Message button and you'll see the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
Hadoop - copyFromLocal Command - GeeksforGeeks

27 Dec, 2021
Hadoop copyFromLocal command is used to copy the file from your local file system to the HDFS(Hadoop Distributed File System). copyFromLocal command has an optional switch –f which is used to replace the already existing file in the system, means it can be used to update that file. -f switch is similar to first delete a file and then copying it. If the file is already present in the folder then copy it into the same folder will automatically throw an error. 
Syntax to copy a file from your local file system to HDFS is given below: 
 
hdfs dfs -copyFromLocal /path 1 /path 2 .... /path n /destination
The copyFromLocal local command is similar to the -put command used in HDFS. we can also use hadoop fs as a synonym for hdfs dfs. The command can take multiple arguments where all the paths provided are of the source from where we want to copy the file except the last one which is the destination, where the file is copied. Make sure that the destination should be a directory. 
Our objective is to copy the file from our local file system to HDFS. In my case, I want to copy the file name Salaries.csv which is present at /home/dikshant/Documents/hadoop_file directory. 
 
 
Let’s see the current view of my Root directory in HDFS.  
Step 1: Make a directory in HDFS where you want to copy this file with the below command. 
 
hdfs dfs -mkdir /Hadoop_File
 
 
Step 2: Use copyFromLocal command as shown below to copy it to HDFS /Hadoop_File directory. 
 
hdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/Salaries.csv /Hadoop_File
 
Step 3: Check whether the file is copied successfully or not by moving to its directory location with below command. 
 
hdfs dfs -ls /Hadoop_File
 
 
 
From below Image, you can observe that copyFromLocal command itself does not copy the same name file at the same location. it says that the file already exists. 
 
To update the content of the file or to Overwrite it, you should use -f switch as shown below. 
 
hdfs dfs -copyFromLocal -f /home/dikshant/Documents/hadoop_file/Salaries.csv /Hadoop_File
 
Now you can easily observe that using copyFromLocal with -f switch does not produce any error or it will easily update or modify your file in HDFS. 
varshagumber28
Hadoop
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Hadoop and Spark
Anatomy of File Read and Write in HDFS
Introduction to Apache Pig
Hadoop MapReduce - Data Flow
What is Big Data?
Architecture of HBase
Hadoop - Pros and Cons
Hive - Alter Table
Architecture and Working of Hive
Applications of Big Data
Getting the maximum value from a list in Julia - max() Method - GeeksforGeeks

21 Apr, 2020
The max() is an inbuilt function in julia which is used to return the maximum value of the parameters.
Syntax: max(x, y, ...)
Parameters:
x: Specified 1st value.
y: Specified 2nd value and so on.
Returns: It returns the maximum value of the parameters.
Example 1:
# Julia program to illustrate # the use of max() method  # Getting the maximum value of the parameters.println(max(1, 2, 3, 4))println(max(1, 3, 5))println(max(2, 4, 6))
Output:
4
5
6

Example 2:
# Julia program to illustrate # the use of max() method  # Getting the maximum value of the parameters.println(max(0.6, 0.7, 0.2))println(max(2.5, 3.5, 0.3, 1.7))
Output:
0.7
3.5

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Working with CSV Files in Julia
Python - Find first element by second in tuple List - GeeksforGeeks

09 May, 2022
Sometimes, while working with Python records, we can have a problem in which we need to find the first element of tuple from the given second element. This kind of problem can occur in domains such as web development. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(4, 5), (5, 6), (1, 3), (6, 6)] K = 6 Output : [5, 6] Input : test_list = [(4, 5), (5, 7), (1, 3), (6, 8)] K = 6 Output : []
Method #1 : Using list comprehension This is one of the ways in which this task can be performed. In this, we iterate for each tuple, and if we find key matching to value, we store in result list. 
Python3
# Python3 code to demonstrate working of# Find first element by second in tuple List# Using list comprehension # initializing listtest_list = [(4, 5), (5, 6), (1, 3), (6, 9)] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 6 # Find first element by second in tuple List# Using list comprehensionres = [x for (x, y) in test_list if y == K] # printing resultprint("The key from value : " + str(res))
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The key from value : [5]
  Method #2 : Using next() + generator expression This is yet another way in which this task can be solved. In here, the next() is used to get the successive elements and generator expression is used to check for the logic. 
Python3
# Python3 code to demonstrate working of# Find first element by second in tuple List# Using next() + generator expression # initializing listtest_list = [(4, 5), (5, 6), (1, 3), (6, 9)] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 6 # Find first element by second in tuple List# Using next() + generator expressionres = next((x for x, y in test_list if y == K), None) # printing resultprint("The key from value : " + str(res))
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The key from value : 5
singghakshay
sumitgumber28
Python List-of-Tuples
Python list-programs
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
response.json() - Python requests - GeeksforGeeks

22 Nov, 2021
response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.json() out of a response object. It is one of the most used methods in the requests module. 
To illustrate the use of response.json(), let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC. 
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac 
Example code:
Python3
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print json contentprint(response.json())
Example Implementation:
Save the above file as request.py and run using 
Python request.py
Output:
 
Check the json content at the terminal output. It returns a Python dictionary.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. 
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
vw23kz0zj19z181y27qygo2n5135r7k77r78h55l
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications
Python | Pandas Index.where - GeeksforGeeks

20 Feb, 2019
Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects.
Pandas Index.where function return an Index of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other.
Syntax: Index.where(cond, other=None)
Parameter :cond : boolean array-like with the same length as selfother : scalar, or array-like
Returns : Index
Example #1: Use Index.where function to return an Index, in which we select the value from the other Index if value of this Index is not smaller than 100.
# importing pandas as pdimport pandas as pd  # Creating the first indexidx1 = pd.Index([900, 45, 21, 145, 38, 422])  # Creating the second indexidx2 = pd.Index([1100, 1200, 1300, 1400, 1500, 1600])  # Print the first indexprint(idx1)  # Print the second indexprint(idx2)
Output :
Now we will use Index.where function to return an Index, in which we select the value from the other Index if value of this Index is not smaller than 100.
# return the new index based on the conditionresult = idx1.where(idx1 < 100, idx2)  # Print the resultprint(result)
Output :As we can see in the output, the Index.where function has successfully returned an Index object satisfying the passed condition. Example #2 : Use Index.where function to return an Index, which satisfy the passed condition.
# importing pandas as pdimport pandas as pd  # Creating the first indexidx1 = pd.Index([900, 45, 21, 145, 38, 422])  # Creating the second indexidx2 = pd.Index([1100, 1200, 1300, 1400, 1500, 1600])  # Print the first indexprint(idx1)  # Print the second indexprint(idx2)
Output :
Now we will use Index.where function to return an Index, in which we select the value from the other Index if value of other Index minus 1200 is not smaller than idx1.
# return the new index based on the conditionresult = idx1.where((idx2 - 1200) < idx1, idx2)  # Print the resultprint(result)
Output :As we can see in the output, the Index.where function has successfully returned an Index object satisfying the passed condition.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
C# Program to Find Sum of Digits of a Number Using Recursion - GeeksforGeeks

22 Apr, 2022
Given a number, we need to find the sum of digits in the number using recursion. In C#, recursion is a process in which a function calls itself directly or indirectly and the corresponding function is known as a recursive function. It is used to solve problems easily like in this article using recursion we will find the sum of digits of a number.
Example
Input: 456
Output: 15

Input: 123
Output: 6
Approach:
To find the sum of digits of a number using recursion follow the following approach:
We call the SumOfDigits function with the argument n.
In function, the last digit is retrieved by n % 10.
The function is recursively called with argument as n / 10.[i.e. n % 10 + SumOfDigit(n / 10)]
The function is called recursively until the n > 0.
Example 1:
C#
// C# program to find the sum of digits of a number// using recursionusing System; class GFG{     // Method to check sum of digit using recursionstatic int SumOfDigit(int n){         // If the n value is zero then we    // return sum as 0.    if (n == 0)        return 0;             // Last digit + recursively calling n/10    return(n % 10 + SumOfDigit(n / 10));} // Driver codepublic static void Main(){    int n = 123;    int ans = SumOfDigit(n);         Console.Write("Sum = " + ans);}}
Sum = 6
Example 2:
C#
// C# program to find the sum of digits of a number// using recursion// Here, we take input from userusing System; class GFG{     // Method to check sum of digit using recursionstatic int SumOfDigit(int n){         // If the n value is zero then we return sum as 0.    if (n == 0)        return 0;             // Last digit + recursively calling n/10    return (n % 10 + SumOfDigit(n / 10));} // Driver codepublic static void Main(){    int number, res;         // Taking input from user    Console.WriteLine("Hi! Enter the Number: ");    number = int.Parse(Console.ReadLine());    res = SumOfDigit(number);         // Displaying the output    Console.WriteLine("Sum of Digits is {0}", res);    Console.ReadLine();}}
Output:
Hi! Enter the Number:
12345
The Sum of Digits is 15
sumitgumber28
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Efficient way to install and load R packages - GeeksforGeeks

09 May, 2021
The most common method of installing and loading packages is using the install.packages() and library() function respectively. Let us see a brief about these functions –
Install.packages() is used to install a required package in the R programming language.
Syntax:
install.packages(“package_name”)
library() is used to load a specific package in R programming language
Syntax:
library(package_name) 
In the case where multiple packages have to installed and loaded these commands have to be specified repetitively. Thus making the approach inefficient.
Example:
R
install.packages("ggplot2")install.packages("dpylr")install.packages("readxl")  library(ggplot2)library(dpylr)library(readxl)
Given below are ways by which this can be avoided.
The most efficient way to install the R packages is by installing multiple packages at a time using. For installing multiple packages we need to use install.packages( ) function again but this time we can pass the packages to be installed as a vector or a  list with each package separated by comma(,).
Syntax :  
install.packages ( c(“package 1′′ ,”package 2”, . . . . , “package n”) )
install.packages(“package1′′,”package2”, . . . . , “package n”)
Example : 
R
install.packages(c("ggplot2","dpylr","readxl"))  install.packages("ggplot2","dpylr","readxl")
Similarly, package can be loaded efficiently by one of the following ways.
Method 1: Using library()
In this, the packages to be loaded are passed to the function but as a list with each package separated by a comma (,).
Syntax:
library(“package1”, “package2′′,  . . . . ,”package n”)
Example:
R
library("ggplot2","dpylr")
Method 2: Using pacman
For efficient package loading, we need to install another package called pacman. To load multiple packages using pacman we use a function called p_load( ).
Syntax : 
pacman::p_load( package 1 , . . . . , package n)
Example :
R
pacman::p_load(dplyr,ggplot2,readxl)
Picked
R-Packages
R Language
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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
Spring Boot - Runners

Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the application has started. This chapter talks about them in detail.
Application Runner is an interface used to execute the code after the Spring Boot application started. The example given below shows how to implement the Application Runner interface on the main class file.
package com.tutorialspoint.demo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Override
   public void run(ApplicationArguments arg0) throws Exception {
      System.out.println("Hello World from Application Runner");
   }
}
Now, if you observe the console window below Hello World from Application Runner, the println statement is executed after the Tomcat started. Is the following screenshot relevant?
Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started. The example given below shows how to implement the Command Line Runner interface on the main class file.
package com.tutorialspoint.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Override
   public void run(String... arg0) throws Exception {
      System.out.println("Hello world from Command Line Runner");
   }
}
Look at the console window below “Hello world from Command Line Runner” println statement is executed after the Tomcat started.

    102 Lectures 
     8 hours 

 Karthikeya T

    39 Lectures 
     5 hours 

 Chaand Sheikh

    73 Lectures 
     5.5 hours 

 Senol Atac

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac

    69 Lectures 
     5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
What is Box Model in CSS?

Every element in an HTML document is rendered as a rectangular box by the browser. The width, height, padding and margin determine the space allocated in an around the element. The following diagram illustrates the box model concept −
Source: w3.org
Content 
This includes the actual data in the form of text, image or other media content. The width and height properties modify the dimensions of this box.
Padding 
The space between the outer edge of the content and its border refers to padding. This box can be resized by the padding property. Edge-specific properties like padding-left, padding-bottom, etc. help in achieving custom spacing.
Border
The distance between the outer edge of the padding and the inner edge of the margin defines the border of an element. By default, its width is set to 0. The border property is used to define an element’s border. Individual edges can also be styled.
Margin 
The space between an element’s box and its surrounding elements’ box is defined as margin. This is analogous to the page margin which is defined as the space between the edge of a page and its content. It is transparent in color, simulating properties of padding, except that it clears area outside the element’s border. Like padding, the individual edges can be defined to have a custom margin.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body * {
   outline: solid;
}
#demo {
   margin: auto;
   width: 50%;
   padding: 1em;
   border: 1px outset;
   display: flex;
   box-shadow: inset 0 0 15px mediumvioletred;
   box-sizing: border-box;
}
#demo div {
   padding: 2em;
   box-shadow: inset 0 0 9px orange;
}
</style>
</head>
<body>
<div id="demo">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body * {
   outline: thin dotted;
}
#demo {
   margin: auto;
   width: 120px;
   height: 120px;
   padding: 1em;
   border: 1px outset;
   display: flex;
   box-shadow: inset 0 0 15px indianred;
}
#demo div {
   width: 40px;
   height: 40px;
}
div:nth-child(odd) {
   border: inset lightgreen;
   border-bottom-right-radius: 100px;
   border-bottom-left-radius: 100px;
}
div:nth-child(even) {
   border: inset lightblue;
   padding: 0.5em;
}
</style>
</head>
<body>
<div id="demo">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
This gives the following output −
Construct String from Binary Tree in Python

Suppose we have a binary tree we have to make a string consists of parenthesis and integers
from a binary tree with the preorder traversing way. A null node will be represented by empty
parenthesis pair "()". And we need to omit all the empty parenthesis pairs that don't affect the
one-to-one mapping relationship between the string and the original binary tree.
So, if the input is like
then the output will be 5(6()(8))(7)
To solve this, we will follow these steps −
ans := blank string
Define a function pot(). This will take node, s
if is null, thenreturn blank string
return blank string
if if left or right of node is null, thenreturn node.data
return node.data
ss := node.data
if node.left is not null, thenss := ss concatenate '(' concatenate pot(node.left, blank string) concatenate ')'
ss := ss concatenate '(' concatenate pot(node.left, blank string) concatenate ')'
otherwise,ss := ss concatenate '()'
ss := ss concatenate '()'
if node.right is not null, thenss := ss concatenate '(' concatenate pot(node.right, blank string) concatenate ')'
ss := ss concatenate '(' concatenate pot(node.right, blank string) concatenate ')'
return ss
From the main method do the following −
return pot(t, blank string)
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
      que = []
      que.append(temp)
      while (len(que)):
         temp = que[0]
         que.pop(0)
         if (not temp.left):
            if data is not None:
               temp.left = TreeNode(data)
            else:
               temp.left = TreeNode(0)
            break
         else:
            que.append(temp.left)
         if (not temp.right):
            if data is not None:
               temp.right = TreeNode(data)
            else:
               temp.right = TreeNode(0)
            break
         else:
            que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution:
   def tree2str(self, t: TreeNode):
      ans = ''
      def pot(node, s):
         if node == None or node.data == 0:
            return ''
         if node.left == node.right == None:
            return str(node.data)
         ss = str(node.data)
         if node.left != None:
            ss = ss + '(' + pot(node.left, '') + ')'
         else:
            ss = ss + '()'
         if node.right != None:
            ss = ss + '(' + pot(node.right, '') + ')'
         return ss
      return pot(t, '')
ob = Solution()
root = make_tree([5,6,7,None,8])
print(ob.tree2str(root))
[5,6,7,None,8]
5(6()(8))(7)
java.time.Instant.parse() Method Example

The java.time.Instant.parse(CharSequence text) method obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z.
Following is the declaration for java.time.Instant.parse(CharSequence text) method.
public static Instant parse(CharSequence text)

text − the text to parse, not null.
an instant, not null.
DateTimeException − if the text cannot be parsed.
The following example shows the usage of java.time.Instant.parse(CharSequence text) method.
package com.tutorialspoint;

import java.time.Instant;

public class InstantDemo {
   public static void main(String[] args) {

      Instant instant = Instant.parse("2017-02-03T10:37:30.00Z");     
      System.out.println(instant);  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T10:37:30Z

 Print
 Add Notes
 Bookmark this page
Can main() be overloaded in C++?

In C++, we can use the function overloading. Now the question comes in our mind, that, can we overload the main() function also?
Let us see one program to get the idea.
#include <iostream>
using namespace std;
int main(int x) {
   cout << "Value of x: " << x << "\n";
   return 0;
}
int main(char *y) {
   cout << "Value of string y: " << y << "\n";
   return 0;
}
int main(int x, int y) {
   cout << "Value of x and y: " << x << ", " << y << "\n";
   return 0;
}
int main() {
   main(10);
   main("Hello");
   main(15, 25);
}
This will generate some errors. It will say there are some conflict in declaration of main() function
To overcome the main() function, we can use them as class member. The main is not a restricted keyword like C in C++.
#include <iostream>
using namespace std;
class my_class {
   public:
      int main(int x) {
         cout << "Value of x: " << x << "\n";
         return 0;
      }
      int main(char *y) {
         cout << "Value of string y: " << y << "\n";
         return 0;
      }
      int main(int x, int y) {
         cout << "Value of x and y: " << x << ", " << y << "\n";
         return 0;
      }      
};
int main() {
   my_class obj;
   obj.main(10);
   obj.main("Hello");
   obj.main(15, 25);
}
Value of x: 10
Value of string y: Hello
Value of x and y: 15, 25
Check if a key is present in every segment of size k in an array in C++

With respect of a given array arr1[] with size of array N,one another key X and a segment size K, the task is to determine that the key X present in every segment of size K in arr1[].
Input 
arr1[] = { 4, 6, 3, 5, 10, 4, 2, 8, 4, 12, 13, 4}
X = 4
K = 3
Output 
Yes
There are existence of 4 non-overlapping segments of size K in the array, {4, 6, 3}, {5, 10, 4}, {2, 8, 4} and {12, 13, 4}. 4 is present all segments.
Input 
arr1[] = { 22, 24, 57, 66, 35, 55, 77, 33, 24, 46, 22, 24, 26}
X = 24
K = 5
Output 
Yes
Input 
arr1[] = { 6, 9, 8, 13, 15, 4, 10}
X = 9
K = 2
Output 
No
In this case,the concept is simple, we consider every segment of size K and verify if X is present in the window or not. So we need to carefully tackle the last segment.
Following is the implementation of the above approach −
 Live Demo
// C++ code to determine the every segment size of
// array have a search key x
#include <bits/stdc++.h>
using namespace std;
bool findxinkindowSize1(int arr1[], int X, int K, int N){
   int i;
   for (i = 0; i < N; i = i + K) {
      // Search X in segment starting
      // from index i.
      int j;
      for (j = 0; j < K; j++)
         if (arr1[i + j] == X)
      break;
      // If loop didn't break
      if (j == K)
         return false;
   }
   // If N is a multiple of K
   if (i == N)
      return true;
   // Check in last segment if N
   // is not multiple of K.
   int j;
   for (j=i-K; j<N; j++)
      if (arr1[j] == X)
   break;
   if (j == N)
      return false;
   return true;
}
// main driver
int main(){
   int arr1[] = { 4, 6, 3, 5, 10, 4, 2, 8, 4, 12, 13, 4 };
   int X = 4, K = 3;
   int N = sizeof(arr1) / sizeof(arr1[0]);
   if (findxinkindowSize1(arr1, X, K, N))
      cout << "Yes" << endl;
   else
      cout << "No" << endl;
   return 0;
}
Yes