code-rag-bench/online-tutorials huggingface dataset:
Garbage Collection in Python

Python memory management is straight forward. You don’t need to worry about memory management, as memory allocation and deallocation is automatic. one of the mechanisms of memory management is garbage collection. Let’s understand different aspects of garbage collection,
It is the process by which shared computer memory is cleaned which is currently being put to use by a running program when that program no longer needs that memory. With garbage collection, that freed memory can be used by another program.
There are two methods used by python for memory management −
Reference counting
Garbage collection
Python’s garbage collection is automatic but in some programming languages, you have to clean objects yourself. In python, if you want you can delete objects manually.
>>> x = 9
>>> print(x)
9
>>> del x
>>> print(x)
Traceback (most recent call last):
   File "<pyshell#3>", line 1, in <module>
      print(x)
NameError: name 'x' is not defined
Above we simply define one variable(x) and use it. During runtime, we delete the object(because everything in python is an object) and try to output it.
In the first two lines of the above program, object x is known. However, after the deletion of the object(x), we cannot print it anymore.
So from above, we can see that garbage collection is fully automated and we don’t need to worry about it. Let’s understand the above concept with another example. Every object in python like in the above code, object x has a reference count and a pointer to a type.
The reference count changes value depends on how we are using it, for example, if we assign the object x to another object y, its reference count increases to 2.
>>> some_list = [1, 2 ,3, 4, 5, 6, 7, 8, 9]
>>> #Reference count of some_list = 1
>>> other_list = some_list
>>> #Reference count = 2
>>> #This will also increases if we pass the object as an assignment
>>> list_total = sum(some_list)
>>> # If we put the object in a list, reference count will also increase
>>> list_of_list = [some_list, some_list, some_list]
>>>
>>> #Let's check the reference count of object "some_list"
>>> import sys
>>> sys.getrefcount(some_list)
6
Above is one good example to understand reference counting of memory management in python. We create one object “some_list” (reference count = 1), we assign it to another object (ref. count = 2), we set the object as an argument(ref. count =3) and later we put the object into a list where occurrence of object is three times (ref. count =6). Later when we try to get the reference count of object “some_list”, we get 6.
>>> import sys
>>> sys.getrefcount(some_list)
6
>>>
>>> del list_of_list
>>> sys.getrefcount(some_list)
3
>>> del some_list
>>> sys.getrefcount(some_list)
Traceback (most recent call last):
   File "<pyshell#17>", line 1, in <module>
      sys.getrefcount(some_list)
NameError: name 'some_list' is not defined
Scala | Lazy Evaluation - GeeksforGeeks

03 Mar, 2022
Lazy evaluation or call-by-need is a evaluation strategy where an expression isn’t evaluated until its first use i.e to postpone the evaluation till its demanded. Functional programming languages like Haskell use this strategy extensively. C, C++ are called strict languages who evaluate the expression as soon as it’s declared. Then there are languages like Scala who are strict by default but can be lazy if specified explicitly i.e. of mixed type. 
Let’s see an example in Scala: 
Without lazy:  
val geeks = List(1, 2, 3, 4, 5)

val output = geeks.map(l=> l*2)

println(output)
 
The value of output is calculated as soon as the operation is applied on it. 
With lazy:  
val geeks = List(1, 2, 3, 4, 5)

lazy val output2 = geeks.map(l=> l*5)

println(output2)
 
The value isn’t calculated till we use output2 that’s till println(output2). 
 
In the example what if we never use the output value? We wasted our map operation (CPU computations) which can be very costly when we write more complex and bigger code. Here lazy evaluation helps us in optimizing the process by evaluating the expression only when it’s needed and avoiding unnecessary overhead. 
Pros:  
Optimizes the computation process. Spark a big data computation engine uses this technique at it’s core.
Lazy evaluation can help us to resolve circular dependencies.
Gives access to infinite data structure.
Allows modularity of code into parts.
The programmer lose control over the sequence their code is executed as some expressions are evaluated and others aren’t depending on the need.
Cons:  
Finding bugs can be tricky as programmer has no control over program execution.
Can increase space complexity as all the instructions(operations) have to stored.
Harder to code in contrast with conventional approach.
 
ssamsomu
Scala
Scala-Basics
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala List filter() method with example
Type Casting in Scala
Scala Map
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List contains() method with example
Operators in Scala
Inheritance in Scala
Matplotlib.axes.Axes.add_artist() in Python - GeeksforGeeks

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.add_artist() function in axes module of matplotlib library is used to add an Artist to the axes, and return the artist.
Syntax: Axes.add_artist(self, a)
Parameters: This method accepts the following parameters.
a: This parameter is the legend which is produced by legend() function .
Return value: This method returns the artist.
Below examples illustrate the matplotlib.axes.Axes.add_artist() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npnp.random.seed(19680801)import matplotlib.pyplot as plt  volume = np.random.rayleigh(27, size = 40)amount = np.random.poisson(10, size = 40)ranking = np.random.normal(size = 40)price = np.random.uniform(1, 10, size = 40)  fig, ax = plt.subplots()  scatter = ax.scatter(volume * 2, amount * 3,                     c = ranking * 3,                      s = 0.3*(price * 3)**2,                     vmin =-4, vmax = 4,                     cmap ="Spectral")  legend1 = ax.legend(*scatter.legend_elements(num = 5),                    loc ="upper left",                     title ="Ranking")  ax.add_artist(legend1)  kw = dict(prop ="sizes", num = 5,          color = scatter.cmap(0.7),          fmt =" {x:.2f}",          func = lambda s: np.sqrt(s/.3)/3)  legend2 = ax.legend(*scatter.legend_elements(**kw),                    loc ="lower right",                    title ="Size")  fig.suptitle('matplotlib.axes.Axes.add_artist() \function Example\n\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Ellipse  NUM = 200  ells = [Ellipse(xy = np.random.rand(2) * 10,                width = np.random.rand(),                height = np.random.rand(),                angle = np.random.rand() * 360)        for i in range(NUM)]  fig, ax = plt.subplots(subplot_kw ={'aspect': 'equal'})  for e in ells:    ax.add_artist(e)    e.set_clip_box(ax.bbox)    e.set_alpha(np.random.rand())    e.set_facecolor(np.random.rand(4))  ax.set_xlim(3, 7)ax.set_ylim(3, 7)    fig.suptitle('matplotlib.axes.Axes.add_artist() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Java Program to enable cell selection in a JTable

To enable cell selection, use the setCellSelectionEnabled() method and set it to TRUE −
table.setCellSelectionEnabled(true);
The above sets whether this table allows both a column selection and arow selection to exist simultaneously.
The following is an example to enable cell selection in a JTable −
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.orange);
      table.setCellSelectionEnabled(true);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
The output is as follows. Here, we have selected a single selection. We can select a cell now since setCellSelectionEnabled() is set TRUE above −
Not showing a placeholder for input type=“date” field with HTML5. How to solve it?

To show it, use the following −
<input placeholder = "Date" class = "textbox-n" type = "text" onfocus = "(this.type = 'date')"  id = "date">
You can also go for CSS −
input[type="date"]::before{
   color: #ffffff;
   content: attr(placeholder) ": ";
}
input[type="date"]:focus::before {
   content: "" !important;
}
How can we create a LOG filter for Logging purposes in C# ASP.NET WebAPI?

Action filters are used to add extra logic before or after action methods execution.
The OnActionExecuting and OnActionExecuted methods are used to add our logic
before and after an action method is executed.
Let us create create a LogAttribute that implemets ActionFilterAttribute which logs
some information before and after action method execution.
LogAttribute −
using System;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers{
   public class LogAttribute : ActionFilterAttribute {
      public override void OnActionExecuting(HttpActionContext actionContext){
         Debug.WriteLine(string.Format("Action Method {0} executing at {1}",
            actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
            "Web API Logs");
      }
      public override void OnActionExecuted(HttpActionExecutedContext
      actionExecutedContext){
         Debug.WriteLine(string.Format("Action Method {0} executed at {1}",
         actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
         DateTime.Now.ToShortDateString()), "Web API Logs");
      }
   }
}
Controller Action −
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [Log]
      public IHttpActionResult Get(){
         //Some logic
         return Ok();
      }
   }
}
Since we have used the Log attribute which has the OnActionExecuting and
OnActionExecuted methods implements, the log information will be added to the
debug console.
Java Program to replace a word with asterisks in a sentence

To replace a word with asterisks in a sentence, the Java program is as follows −
 Live Demo
public class Demo{
   static String replace_word(String sentence, String pattern){
      String[] word_list = sentence.split("\\s+");
      String my_result = "";
      String asterisk_val = "";
      for (int i = 0; i < pattern.length(); i++)
      asterisk_val += '*';
      int my_index = 0;
      for (String i : word_list){
         if (i.compareTo(pattern) == 0)
            word_list[my_index] = asterisk_val;
         my_index++;
      }
      for (String i : word_list)
         my_result += i + ' ';
      return my_result;
   }
   public static void main(String[] args){
      String sentence = "This is a sample only, the sky is blue, water is transparent ";
      String pattern = "sample";
      System.out.println(replace_word(sentence, pattern));
   }
}
This is a ****** only, the sky is blue, water is transparent
A class named Demo contains a function named ‘replace_word’ that takes the sentence and the pattern as parameters. A sentence is split and stored in a string array. An empty string is defined, and the pattern is iterated over, based on its length.
An asterisk value is defined as ‘*’ and for every character in the sentence, the character is compared
to the pattern and a specific occurrence is replaced with the asterisk symbol. The final string is
displayed on the console.
Compare Version Numbers in Python

Suppose we have to compare two version numbers version1 and version2. If the version1 > version2 then return 1; otherwise when version1 < version2 return -1; otherwise return 0. We can assume that the version strings are non-empty and contain only digits and the dot (.) characters. The dot character does not represent a decimal point and is used to separate number sequences. So for example, 2.5 is not "two and a half" or "halfway to version three", it is the fifth second-level revision of the second first-level revision.
We can assume the default revision number for each level of a version number to be 0. For example, the version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.
So if the input is like version1 = “1.0.1” and version2 = “1”, then it will return +1.
To solve this, we will follow these steps −
version1_arr = an array of numbers separated by dot for version1
version1_arr = an array of numbers separated by dot for version1
version2_arr = an array of numbers separated by dot for version2
version2_arr = an array of numbers separated by dot for version2
for i in range 0 to max of size of version1_arr and size of version2_arr −v1 := version1_arr[i] if i < size of version1_arr, otherwise 0v2 := version2_arr[i] if i < size of version2_arr, otherwise 0if v1 > v2, then return 1, otherwise when v1 < v2, return -1
for i in range 0 to max of size of version1_arr and size of version2_arr −
v1 := version1_arr[i] if i < size of version1_arr, otherwise 0
v1 := version1_arr[i] if i < size of version1_arr, otherwise 0
v2 := version2_arr[i] if i < size of version2_arr, otherwise 0
v2 := version2_arr[i] if i < size of version2_arr, otherwise 0
if v1 > v2, then return 1, otherwise when v1 < v2, return -1
if v1 > v2, then return 1, otherwise when v1 < v2, return -1
return 0
return 0
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def compareVersion(self, version1, version2):
      versions1 = [int(v) for v in version1.split(".")]
      versions2 = [int(v) for v in version2.split(".")]
      for i in range(max(len(versions1),len(versions2))):
         v1 = versions1[i] if i < len(versions1) else 0
         v2 = versions2[i] if i < len(versions2) else 0
         if v1 > v2:
            return 1
         elif v1 <v2:
            return -1
      return 0
ob1 = Solution()
print(ob1.compareVersion("1.0.1","1.0"))
"1.0.1"
"1.0"
1
Count values greater and less than a specific number and display count in separate MySQL columns?

For this, you can use COUNT() along with CASE STATEMENT. Let us first create a table −
mysql> create table DemoTable
(
   Score int
);
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.77 sec)
mysql> insert into DemoTable values(48);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(59);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(33);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(38);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(35);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Score |
+-------+
|    40 |
|    48 |
|    59 |
|    33 |
|    38 |
|    89 |
|    35 |
+-------+
7 rows in set (0.00 sec)
Following is the query to count values greater and less than a specific number and display count in separate columns −
mysql> select count( case when Score > 45 then 1 end) as CountOfValueGreaterThan45,
   count( case when Score <= 45 then 1 end) as CountOfValueLessThanOrEqualTo45
   from DemoTable;
This will produce the following output −
+---------------------------+---------------------------------+
| CountOfValueGreaterThan45 | CountOfValueLessThanOrEqualTo45 |
+---------------------------+---------------------------------+
|                         3 |                               4 |
+---------------------------+---------------------------------+
1 row in set (0.00 sec)
How to delete text from document using HTML ? - GeeksforGeeks

11 Jun, 2020
In this article, we delete text from an HTML document by using the <del> tag in the document. This tag stands for delete and is used to mark a portion of text which has been deleted from the document.
Syntax:
<del> Contents... </del>
Example: In the following example, deletion of a text from a document is demonstrated.
<!DOCTYPE html><html>  <head>    <title>        How to delete text from a         document using HTML?    </title>      <style>        del {            color: red;        }          ins {            color: green;        }          h1 {            color: green;        }          body {            text-align: center;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <b>        HTML5 | How to delete         text from a document     </b>      <p>        GeeksforGeeks is a         <del>mathematical</del>        <ins>computer</ins>         science portal    </p></body>  </html>
Output: 
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
JavaScript | RegExp test() Method - GeeksforGeeks

12 Apr, 2021
The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false.Syntax:  
RegExpObject.test(str)
Where str is the string to be searched. This is required field.Example 1: This example searches for the string “computer” in the original string.  
html
<!DOCTYPE html><html> <head>    <title>        JavaScript RegExp test() Method    </title></head> <body style="text-align:center">         <h1 style="color:green">        GeeksforGeeks    </h1>         <h2>test() Method</h2>          <p>        String: GeeksforGeeks is the        computer science portal for geeks.    </p>          <button onclick="geek()">        Click it!    </button>         <p id="app"></p>          <script>        function geek() {            var str="GeeksforGeeks is the computer science"                   + " portal for geeks.";            var regex = new RegExp("computer", );            var rex = regex.test(str);                         document.getElementById("app").innerHTML                    = " Match " + " found: " + "<b>"                    + rex + "</b>";        }    </script></body> </html>                   
Output: Before clicking the button:  
After clicking the button:  
Example 2: This example searches for the string “GEEK” in the original string.  
html
<!DOCTYPE html><html> <head>    <title>        JavaScript RegExp test() Method    </title></head> <body style="text-align:center">         <h1 style="color:green">        GeeksforGeeks    </h1>         <h2>test() Method</h2>          <p>        String: GeeksforGeeks is the        computer science portal for geeks.    </p>          <button onclick="geek()">        Click it!    </button>         <p id="app"></p>          <script>        function geek() {            var str="GeeksforGeeks is the computer science"                    + " portal for geeks.";            var regex = new RegExp("GEEK", );            var rex = regex.test(str);                         document.getElementById("app").innerHTML                    = " Match " + " found: "                    + "<b>" + rex + "</b>";        }    </script></body> </html>                   
Output: Before clicking the button:  
After clicking the button:  
Supported Browsers: The browsers supported by RegExp test() Method are listed below:  
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
 
simranarora5sos
JavaScript-RegExp
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Create a list from rows in Pandas DataFrame | Set 2 - GeeksforGeeks

29 Jan, 2019
In an earlier post, we had discussed some approaches to extract the rows of the dataframe as a Python’s list. In this post, we will see some more methods to achieve that goal.
Note : For link to the CSV file used in the code, click here.
Solution #1: In order to access the data of each row of the Pandas dataframe, we can use DataFrame.iloc attribute and then we can append the data of each row to the end of the list.
# importing pandas as pdimport pandas as pd  # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                    'Cost':[10000, 5000, 15000, 2000]})  # Print the dataframeprint(df)
Output :
Now we will use the DataFrame.iloc attribute to access the values of each row in the dataframe and then we will construct a list out of it.
# Create an empty listRow_list =[]  # Iterate over each rowfor i in range((df.shape[0])):      # Using iloc to access the values of     # the current row denoted by "i"    Row_list.append(list(df.iloc[i, :]))  # Print the listprint(Row_list)
Output :As we can see in the output, we have successfully extracted each row of the given dataframe into a list. Just like any other Python’s list we can perform any list operation on the extracted list.
# Find the length of the newly # created listprint(len(Row_list))  # Print the first 3 elementsprint(Row_list[:3])
Output : Solution #2: In order to access the data of each row of the Pandas dataframe we can use DataFrame.iat attribute and then we can append the data of each row to the end of the list.
# importing pandas as pdimport pandas as pd  # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                    'Cost':[10000, 5000, 15000, 2000]})  # Create an empty listRow_list =[]  # Iterate over each rowfor i in range((df.shape[0])):    # Create a list to store the data    # of the current row    cur_row =[]          # iterate over all the columns    for j in range(df.shape[1]):                  # append the data of each        # column to the list        cur_row.append(df.iat[i, j])              # append the current row to the list    Row_list.append(cur_row)  # Print the listprint(Row_list)
Output :
# Find the length of the newly # created listprint(len(Row_list))  # Print the first 3 elementsprint(Row_list[:3])
Output :
pandas-dataframe-program
Python pandas-dataFrame
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 ?
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()
Python - Copy contents of one file to another file - GeeksforGeeks

22 Nov, 2021
Given two text files, the task is to write a Python program to copy contents of the first file into the second file.
The text files which are going to be used are second.txt and first.txt:
Method #1: Using File handling to read and append
We will open first.txt in ‘r’ mode and will read the contents of first.txt. After that, we will open second.txt in ‘a’ mode and will append the content of first.txt into second.txt.
Example:
Python3
# open both fileswith open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:          # read content from first file    for line in firstfile:                            # append content to second file             secondfile.write(line)
Output:
Method #2: Using File handling to read and write
We will open first.txt in ‘r’ mode and will read the contents of first.txt. After that, we will open second.txt in ‘w’ mode and will write the content of first.txt into second.txt.
Example:
Python3
# open both fileswith open('first.txt','r') as firstfile, open('second.txt','w') as secondfile:          # read content from first file    for line in firstfile:                            # write content to second file             secondfile.write(line)
Output:
Method #3: Using shutil.copy() module
The shutil.copy() method in Python is used to copy the content of the source file to destination file or directory. 
Example:
Python3
# import moduleimport shutil  # use copyfile()shutil.copyfile('first.txt','second.txt')
Output:
Python file-handling-programs
python-file-handling
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Array sum in C++ STL - GeeksforGeeks

28 Oct, 2017
In C++, we can quickly find array sum using accumulate()
// C++ program to demonstrate working of accumulate()#include <iostream> #include <numeric>     using namespace std;   // User defined function that returns sum of// arr[] using accumulate() library function.int arraySum(int a[], int n) {    int initial_sum  = 0;     return accumulate(a, a+n, initial_sum);}   int main() {    int a[] = {5 , 10 , 15} ;    int n = sizeof(a)/sizeof(a[0]);    cout << arraySum(a, n);    return 0;}
Output:
30

Sum of vector
// C++ program to demonstrate working of accumulate()#include <iostream> #include <vector> #include <numeric>     using namespace std;   // User defined function that returns sum of// arr[] using accumulate() library function.int arraySum(vector<int> &v) {    int initial_sum  = 0;     return accumulate(v.begin(), v.end(), initial_sum);}   int main() {    vector<int> v{5 , 10 , 15} ;    cout << arraySum(v);    return 0;}
Output:
30

We can also use a custom function in accumulate. Refer numeric header in C++ STL | Set 1 (accumulate() and partial_sum()) for details.
This article is contributed by kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
STL
Arrays
C++
Arrays
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
C++ Classes and Objects
C program to check if a given year is leap year using Conditional operator - GeeksforGeeks

16 Jan, 2020
Given an integer which represents the year, the task is to check if this is a leap year, with the help of Ternary Operator.
A year is a leap year if the following conditions are satisfied:
Year is multiple of 400.Year is multiple of 4 and not multiple of 100.
Year is multiple of 400.
Year is multiple of 4 and not multiple of 100.
Following is pseudo code
if year is divisible by 400 then is_leap_year
else if year is divisible by 100 then not_leap_year
else if year is divisible by 4 then is_leap_year
else not_leap_year

Below is the implementation of the above approach:
// C program to check if a given// year is a leap year or not  #include <stdbool.h>#include <stdio.h>  bool checkYear(int n){      return (n % 400 == 0)               ? true               : (n % 4 == 0)                     ? (n % 100 != 0)                     : false                           ? true                           : false;}  // Driver codeint main(){    int year = 2000;      checkYear(year)        ? printf("Leap Year")        : printf("Not a Leap Year");      return 0;}
Leap Year

C Programs
School Programming
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Exit codes in C/C++ with Examples
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Python | Get specific keys' values - GeeksforGeeks

24 Oct, 2019
Sometimes, we require all the values, but many times, we have specified keys of whose value list we require. This is quite common problem for web development. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionThis task can be performed using list comprehension adopted as the shorter way to perform the longer task of checking using loop. This offers a one liner approach to solve this problem.
# Python3 code to demonstrate working of# Get specific keys' values# Using list comprehension  # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}  # initializing keysfilt_keys = ['gfg', 'best']  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Extract specific value list from dictionary# Using list comprehensionres = [test_dict[key] for key in filt_keys]  # printing resultprint("Filtered value list is : " +  str(res))
The original dictionary is : {'is': 2, 'best': 3, 'gfg': 1}
Filtered value list is : [1, 3]

 
Method #2 : Using map() + get()The combination of above functions can offer a more compact solution for this task. The map function can be used to extend the logic to whole dictionary and get function is used to fetch key’s value.
# Python3 code to demonstrate working of# Get specific keys' values# Using map() + get()  # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}  # initializing keysfilt_keys = ['gfg', 'best']  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Extract specific value list from dictionary# Using map() + get()res = list(map(test_dict.get, filt_keys))  # printing resultprint("Filtered value list is : " +  str(res))
The original dictionary is : {'is': 2, 'best': 3, 'gfg': 1}
Filtered value list is : [1, 3]

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
BufferedReader readLine() method in Java with Examples - GeeksforGeeks

28 May, 2020
The readLine() method of BufferedReader class in Java is used to read one line text at a time. The end of a line is to be understood by ‘\n’ or ‘\r’ or EOF.
Syntax:
public String readLine() 
          throws IOException

Parameters: This method does not accept any parameter.
Return value: This method returns the String that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL.
Exceptions: This method throws IOException if an I/O error occurs.
Below programs illustrate readLine() method in BufferedReader class in IO package:
Program 1: Assume the existence of the file “c:/demo.txt”.
// Java program to illustrate// BufferedReader readLine() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {          // Read the stream 'demo.txt'        // containing text        // "GEEKS"        // "FOR"        // "GEEKS"        FileReader fileReader            = new FileReader(                "c:/demo.txt");          // Convert fileReader to        // bufferedReader        BufferedReader buffReader            = new BufferedReader(                fileReader);          while (buffReader.ready()) {            System.out.println(                buffReader.readLine());        }    }}
Program 2: Assume the existence of the file “c:/demo.txt”.
// Java program to illustrate// BufferedReader readLine() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {          // Read the stream 'demo.txt'        // containing text        // "GEEKSFORGEEKS"        // "geeksforgeeks"        FileReader fileReader            = new FileReader(                "c:/demo.txt");          // Convert fileReader to        // bufferedReader        BufferedReader buffReader            = new BufferedReader(                fileReader);          while (buffReader.ready()) {            System.out.println(                buffReader.readLine());        }    }}
References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#readLine()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
How do I get the width and height of a Tkinter window?

Tkinter initially creates an instance of a window which is a container that contains all the widgets and the elements. If we want to resize the window, we can use the geometry method by defining the value of width and height.
In order to get the width and height of the tkinter window, we can use winfo_width() and winfo_height() helper methods that help to grab the current width and height of the tkinter window.
# Import tkinter library
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the Geometry
win.geometry("750x250")
def print_width():
   print("The width of Tkinter window:", win.winfo_width())
   print("The height of Tkinter window:", win.winfo_height())
# Create a Label
Label(win, text="Click the below Button to Print the Height and width of the Screen", font=('Helvetica 10 bold')).pack(pady=20)
# Create a Button for print function
Button(win, text="Click", command=print_width).pack(pady=10)
win.mainloop()
Running the above code will display a window that contains a button.
If you click the button, it will print the current width and height of the tkinter window on the console.
The width of Tkinter window: 750
The height of Tkinter window: 250
Finding longest substring between two same characters JavaScript

We are required to write a JavaScript function that takes in a string. The function should find and return the length of the longest substring that is sandwiched between two same letters.
For example − 
If the input string is −
const str = 'avbghvh';
Then the output should be −
const output = 3;
because the desired longest substring is 'bgh' between two v's.
const str = 'avbghvh';
const longestSub = (str = '') => {
   const map = new Map();
   let max = -1;
   for(let i = 0; i < str.length; i++){
      if(map.has(str.charAt(i))){
         max = Math.max(max, i - map.get(str.charAt(i)) - 1);
      }else{
         map.set(str.charAt(i), i);
      };
   };
   return max;
};
console.log(longestSub(str));
This will produce the following output −
3
Python – Append given number with every element of the list

26 Nov, 2020
Given a list and a number, write a Python program to append the number with every element of the list.
Examples:
input = [1,2,3,4,5]
key = 5 (number to be appended)
output = [1,5,2,5,3,5,4,5,5,5]
The following are ways to achieve this functionality:
Method 1: Using for loop
Python
input = [1, 2, 3, 4, 5]key = 7  result = []for ele in input:    result.append(ele)    result.append(key)  print(result)
Output:
[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]
Method 2: Using list comprehension and itertools.chain
Python
import itertools  input = [1, 2, 3, 4, 5]key = 7  result = list(itertools.chain(*[[ele, key] for ele in input]))  print(result)
Output:
[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]
Method 3: Using zip and for loop
Python
input = [1, 2, 3, 4, 5]key = 7  result = []for x, y in zip(input, [key]*len(input)):    result.extend([x, y])  print(result)
Output:
[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <table> border Attribute

31 Dec, 2021
The HTML <table> border Attribute is used to specify the border of a table. It sets the border around the table cells.
Syntax:
<table border="1|0">
Attribute Values:
1: It sets the border around the table cells.
0: It removes (not set) the border around the table cells.
Note: The
Example:
Output:
Supported Browsers: The browser supported by HTML <table> border Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | array_fill() function

09 Mar, 2018
The array_fill() is an inbuilt-function in PHP and is used to fill an array with values. This function basically creates an user-defined array with a given pre-filled value.
Syntax:
array_fill($start_index, $number_elements, $values)
Parameter:The array_fill() function takes three parameters and are described below:
$start_index: This parameter specifies the starting position of filling up the values into the array, the user wants to create. If $start_index is negative, the first index of the returned array will be $start_index and the following indices will start from zero. So it is better to assign a positive value to it. This is a mandatory parameter and must be supplied.$number_elements: This parameter refers to the number of elements, the user wants to enter into the array. The $number_elements should be positive (including 0, for ver 5.6.0) otherwise E_WARNING is thrown. This is also a mandatory parameter.$values : This parameter refers to the values we want to insert into the array. These values can be of any type.
$start_index: This parameter specifies the starting position of filling up the values into the array, the user wants to create. If $start_index is negative, the first index of the returned array will be $start_index and the following indices will start from zero. So it is better to assign a positive value to it. This is a mandatory parameter and must be supplied.
$number_elements: This parameter refers to the number of elements, the user wants to enter into the array. The $number_elements should be positive (including 0, for ver 5.6.0) otherwise E_WARNING is thrown. This is also a mandatory parameter.
$values : This parameter refers to the values we want to insert into the array. These values can be of any type.
Return Type: The array_fill() function returns a filled user-defined array, with values described by $value parameter.
Examples:
Input : $start_index = 2; $number_elements = 3;
        $values = "Geeks";
Output :
        Array
        (
          [2] => Geeks
          [3] => Geeks
          [4] => Geeks
        )

Input : $start_index = -10; $number_elements = 3;
        $values = 45;
Output :
        Array
        (
          [-10] => 45
          [0] => 45
          [1] => 45
        )

Below program illustrates the working of array_fill() function in PHP:
<?php  // PHP code to illustrate the working of array_fill()  function Fill($start_index, $number_elements, $values){    return(array_fill($start_index, $number_elements, $values));}  // Driver Code$start_index = 2;$number_elements = 5;$values = "Geeks";print_r(Fill($start_index, $number_elements, $values));?>
Output:
Array
(
    [2] => Geeks
    [3] => Geeks
    [4] => Geeks
    [5] => Geeks
    [6] => Geeks
)

Reference: http://php.net/manual/en/function.array-fill.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CHAR_BIT in C

27 May, 2022
CHAR_BIT : It is the number of bits in char. These days, almost all architectures use 8 bits per byte (But it is not the case always, some older machines used to have 7-bit byte). It can be found in Let us see an application of it. Suppose we wish to print byte by byte representation of an integer. 
Examples :
Input  : 4
Output : 00000000 00000000 00000000 00000100

Input  : 12
Output : 00000000 00000000 00000000 00001100 
CPP
// CPP program to print byte by byte presentation#include <bits/stdc++.h>using namespace std; // function in which number and initially 0 is passedvoid printInBinary(int num){    int n = CHAR_BIT*sizeof(num);    stack<bool> s;    for (int i=1; i<=n; i++)    {        s.push(num%2);        num = num/2;    }        for (int i=1; i<=n; i++)    {        cout << s.top();        s.pop();                 // Put a space after every byte.        if (i % CHAR_BIT == 0)        cout << " ";    }} int main(){    int num = 12;    printInBinary(num);    return 0;}
Output :
00000000 00000000 00000000 00001100 
Time Complexity : O(32)
Auxiliary Space : O(32)
This article is contributed by Apurva Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
simmytarika5
ranjanrohit840
Bit Magic
C Language
C++
Bit Magic
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML Course | First Web Page | Printing Hello World

09 Dec, 2021
Course Navigation  
So far, we already have learned about the structure of an HTML document, tags etc. Let us use this knowledge to create our first web page which will print the text “Hello World!” on the screen.Open your text editor, and type the below code in it and save it with the name “index.html”.
Note: HTML files are saved with the file extension .html
Code: index.html
HTML
<!DOCTYPE html> <html>    <head>        <title>            First Web Page        </title>    </head>     <body>        Hello World!    </body></html>
Output: On opening the file in a web browser, you will see the below output. 
Yes, it’s that easy to print anything on the Web Page. You don’t need to compile your HTML code to run it in an Web Page. As HTML is a scripting language, you can simply change your code and hit the refresh button and the changes will be reflected to your Web page immediately.
Make “Hello World!” Bigger: The text “Hello World!” seems to appear small. Let us make it look a bit bigger. We have seen usage of <h1/> tags in our previous articles. This is a heading tag in HTML which is used to represent headings in a Web Page.
Heading Tags: There are six levels of headings defined by HTML. These six heading elements are h1, h2, h3, h4, h5, and h6; with h1 being the highest level and h6 the least.Let us use these six different Heading tags separately to print “Hello World!” and see the difference. Modify your code in index.html with the below code: 
Code: index.html
HTML
<!DOCTYPE html> <html>    <head>        <title>            First Web Page        </title>    </head>     <body>        <h1>Hello World!</h1>        <h2>Hello World!</h2>        <h3>Hello World!</h3>        <h4>Hello World!</h4>        <h5>Hello World!</h5>        <h6>Hello World!</h6>    </body></html>
Output: On refreshing the web page you will see the output will change to this 
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
To learn more about Heading Tags, Please refer: HTML | Heading. 
 
ghoshsuman0129
ysachin2314
surinderdawra388
HTML-Basics
HTML-course-basic
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.