code-rag-bench/online-tutorials huggingface dataset:
How to Get Centered Content in Bootstrap ? - GeeksforGeeks

24 Apr, 2021
The task is to center content using bootstrap. The approach of this article is to get a Centered Content in Bootstrap by using a simple in-built class .text-center to center align all the inline elements like text, images, links, etc. under a block element i.e <div> or <p> element. 
Note: This solution only works in the Bootstrap 3 or 4 versions. 
Example: 
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">    <meta name="viewport"           content="width=device-width,                    initial-scale=1,                    shrink-to-fit=no">    <title>Text Centering in Bootstrap</title>    <link rel="stylesheet"           href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">    <script src="https://code.jquery.com/jquery-3.5.1.min.js"> </script>    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>    <style>        .bs-example {            margin: 20px;        }    </style></head>  <body>    <div class="bs-example">        <div class="container">            <div class="row">                <div class="col-lg-12 bg-light text-center">                    <h1>GeeksforGeeks</h1>                    <h2>How to Get Centered Content in Bootstrap? .                    </h2>                    <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"                          alt="GeeksforGeeks logo"                          height="200px">                </div>            </div>        </div>    </div></body>  </html>
Output:
Bootstrap-4
Bootstrap-Questions
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
Tailwind CSS vs Bootstrap
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Lodash _.defer() Method - GeeksforGeeks

29 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.defer() method in lodash is used to defer the calling of func parameter until the recent call stack is cleared. Moreover, any further arguments are provided to func parameter of this method when it is called.
Syntax:
_.defer(func, [args])
Parameters: This method accepts two parameters which are described below:
func: It is the function which is to be deferred.
[args]: It is the arguments with which the func is being called.
Return Value: This method returns the timer id.
Example 1:
Javascript
// Requiring lodash libraryconst _ = require('lodash');  // Calling defer() method with// its parameter_.defer(function(content) {  console.log(content);}, 'GeeksforGeeks!');  // Prints content after thisconsole.log('Content:');
Output:
Content:
GeeksforGeeks!
Example 2:
Javascript
// Requiring lodash libraryconst _ = require('lodash');  // Defining func parameterlet func = number => {  console.log(number);};  // Defining for loopfor(let i = 1; i <= 5; i++) {          // Calling defer() method    // with its parameter    _.defer(func, i);}  // Prints integer after thisconsole.log('Integers are as follows:');
Output:
Integers are as follows:
1
2
3
4
5
Reference: https://lodash.com/docs/4.17.15#defer
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Python Program for Iterative Quick Sort - GeeksforGeeks

30 Dec, 2020
# Python program for implementation of Quicksort   # This function is same in both iterative and recursivedef partition(arr,l,h):    i = ( l - 1 )    x = arr[h]      for j in range(l , h):        if   arr[j] <= x:              # increment index of smaller element            i = i+1            arr[i],arr[j] = arr[j],arr[i]      arr[i+1],arr[h] = arr[h],arr[i+1]    return (i+1)  # Function to do Quick sort# arr[] --> Array to be sorted,# l  --> Starting index,# h  --> Ending indexdef quickSortIterative(arr,l,h):      # Create an auxiliary stack    size = h - l + 1    stack = [0] * (size)      # initialize top of stack    top = -1      # push initial values of l and h to stack    top = top + 1    stack[top] = l    top = top + 1    stack[top] = h      # Keep popping from stack while is not empty    while top >= 0:          # Pop h and l        h = stack[top]        top = top - 1        l = stack[top]        top = top - 1          # Set pivot element at its correct position in        # sorted array        p = partition( arr, l, h )          # If there are elements on left side of pivot,        # then push left side to stack        if p-1 > l:            top = top + 1            stack[top] = l            top = top + 1            stack[top] = p - 1          # If there are elements on right side of pivot,        # then push right side to stack        if p+1 < h:            top = top + 1            stack[top] = p + 1            top = top + 1            stack[top] = h  # Driver code to test abovearr = [4, 3, 5, 2, 1, 3, 2, 3]n = len(arr)quickSortIterative(arr, 0, n-1)print ("Sorted array is:")for i in range(n):    print ("%d" %arr[i]),  # This code is contributed by Mohit Kumra
Output:
Sorted array is:
1 2 2 3 3 3 4 5

The above mentioned optimizations for recursive quick sort can also be applied to iterative version.
1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version.
2) To reduce the stack size, first push the indexes of smaller half.
3) Use insertion sort when the size reduces below a experimentally calculated threshold.Please refer complete article on Iterative Quick Sort for more details!
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python | Get the first key in dictionary
Python Program for Merge Sort
Python | Find most frequent element in a list
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python - Convert JSON to string
Python program to find smallest number in a list
How to create HTML list from JavaScript array ? - GeeksforGeeks

10 Mar, 2021
In this article, we will be creating an HTML list from a JavaScript array. This is needed sometimes when we fetch JSON from any source and displaying the data into the frontend and in many other cases also. 
Problem statement: Display the array [‘Ram’, ‘Shyam’, ‘Sita’, ‘Gita’ ] into an HTML list.
To achieve this, we will follow the steps below.
Step 1: Create the HTML skeleton.HTMLHTML<!DOCTYPE html><html>  <head> </head>  <body>    <center><h1>GeeksforGeeks</h1></center>    <ul id="myList"></ul>  </body></html>
Step 1: Create the HTML skeleton.
HTML
<!DOCTYPE html><html>  <head> </head>  <body>    <center><h1>GeeksforGeeks</h1></center>    <ul id="myList"></ul>  </body></html>
Step 2: Create a variable named list and get the element whose id is “myList”.JavascriptJavascriptlet list = document.getElementById("myList");
Step 2: Create a variable named list and get the element whose id is “myList”.
Javascript
let list = document.getElementById("myList");
Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.JavascriptJavascriptlet data = ['Ram', 'Shyam', 'Sita', 'Gita' ];  let list = document.getElementById("myList");  data.forEach((item)=>{  let li = document.createElement("li");  li.innerText = item;  list.appendChild(li);})
Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.
Javascript
let data = ['Ram', 'Shyam', 'Sita', 'Gita' ];  let list = document.getElementById("myList");  data.forEach((item)=>{  let li = document.createElement("li");  li.innerText = item;  list.appendChild(li);})
Complete code:
HTML
<!DOCTYPE html><html>  <head> </head>  <body>    <center><h1>GeeksforGeeks</h1></center>    <ul id="myList"></ul>    <script>      let data = ["Ram", "Shyam", "Sita", "Gita"];        let list = document.getElementById("myList");        data.forEach((item) => {        let li = document.createElement("li");        li.innerText = item;        list.appendChild(li);      });    </script>  </body></html>
Output:
HTML-Questions
javascript-array
HTML
JavaScript
Web Technologies
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 ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
How to maximize a plt.show() window using Python?

Using plt.get_current_fig_manager() and mng.full_screen_toggle() methods, we can maximise a plot.
Add a subplot to the current figure, where nrow = 1, ncols = 1 and index = 1.
Add a subplot to the current figure, where nrow = 1, ncols = 1 and index = 1.
Create a pie chart using list [1, 2, 3] and pie() method.
Create a pie chart using list [1, 2, 3] and pie() method.
Return the figure manager of the current figure, using get_current_fig_manager() method. The figure manager is a container for the actual backend-depended window that displays the figure on the screen.
Return the figure manager of the current figure, using get_current_fig_manager() method. The figure manager is a container for the actual backend-depended window that displays the figure on the screen.
Create an abstract base class to handle drawing/rendering operations using the full_screen_toggle() method.
Create an abstract base class to handle drawing/rendering operations using the full_screen_toggle() method.
Use plt.show() to show the figure.
Use plt.show() to show the figure.
import matplotlib.pyplot as plt

plt.subplot(1, 1, 1)
plt.pie([1, 2, 3])

mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
How to get the list of empty folders using PowerShell?

To get the list of empty folder on the windows OS using PowerShell, we can use the below method.
gci C:\Temp -Recurse | foreach {
   if( $_.psiscontainer -eq $true){
      if((gci $_.FullName) -eq $null){$_.FullName}
   }
}
The above command checks the C:\Temp folder and its subfolders and if the content is empty it returns the Folder full path. The PSISContainer property stands for the folder and GCI is the alias of the Get-ChildItem command. We can alternatively use the below command, instead of using the PSISContainer property.
gci C:\Temp -Recurse -Directory | foreach {
   if((gci $_.FullName) -eq $null){$_.FullName}
}
How to maximize the browser in Selenium?

We can maximize the browser in Selenium with the help of method maximize().
The present active window becomes maximized with this method.
Code implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class BrowserMax {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      // maximizing browser with maximize()
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.findElement(By.partialLinkText("Coding")).click();
      driver.close();
   }
}
Arithmetic Number in C++

The arithmetic number is a number which has the average of all positive divisors is an integer i.e. for a number n if the number of divisors can divide the sum of divisors then n is an arithmetic number.
Let’s take an example to understand the concept better,
Input : n = 6
Output : YES
Explanation :
Divisors are 1 , 2 , 3 , 6
Sum = 1+2+3+6 = 12
Number of divisors = 4
Sum of divisors / number of divisor = 12 / 4 = 3
Step 1 : Calculate the sum of divisors and store into sum variable.
Step 2 : Find the total number of divisors.
Step 3 : Check if the remainder when sum of divisors is divided by the total number of divisors is equal to 0.
Step 4 : If remainder is equal 0. Print YES. Else print NO.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n, bool prime[],bool primesquare[], int a[]);
int countDivisors(int n) ;
int sumofFactors(int n) ;
int main(){
   int n = 46;
   int divcount = countDivisors(n);
   int divsum = sumofFactors(n);
   if(divsum % divcount == 0 ){
      cout<<"YES";
   }
   else
      cout<<"NO";
return 0;
}
void SieveOfEratosthenes(int n, bool prime[],bool primesquare[], int a[]){
   for (int i = 2; i <= n; i++)
   prime[i] = true;
   for (int i = 0; i <= (n * n + 1); i++)
   primesquare[i] = false;
   prime[1] = false;
   for (int p = 2; p * p <= n; p++) {
      if (prime[p] == true) {
         for (int i = p * 2; i <= n; i += p)
         prime[i] = false;
      }
   }
   int j = 0;
   for (int p = 2; p <= n; p++) {
      if (prime[p]) {
         a[j] = p;
         primesquare[p * p] = true;
         j++;
      }
   }
}
int countDivisors(int n){
   if (n == 1)
   return 1;
   bool prime[n + 1], primesquare[n * n + 1];
   int a[n];
   SieveOfEratosthenes(n, prime, primesquare, a);
   int ans = 1;
   for (int i = 0;; i++) {
      if (a[i] * a[i] * a[i] > n)
         break;
      int cnt = 1;
      while (n % a[i] == 0){
         n = n / a[i];
         cnt = cnt + 1;
      }
      ans = ans * cnt;
   }
   if (prime[n])
      ans = ans * 2;
   else if (primesquare[n])
      ans = ans * 3;
   else if (n != 1)
      ans = ans * 4;
   return ans;
}
int sumofFactors(int n){
   int res = 1;
   for (int i = 2; i <= sqrt(n); i++) {
      int count = 0, curr_sum = 1;
      int curr_term = 1;
      while (n % i == 0) {
         count++;
         n = n / i;
         curr_term *= i;
         curr_sum += curr_term;
      }
      res *= curr_sum;
   }
   if (n >= 2)
   res *= (1 + n);
   return res;
}
YES
Timer in C++ using system calls

Here we will see how to design timer in C++ using a system call. We will not use any graphics or animations. Here timer means the stopwatch, that is up-counting the time. The used system calls are −
sleep(n) − This will help the program to sleep for n number of seconds
system() − This is used to execute the system command by passing command as an argument to this function.
 Live Demo
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int hrs = 0;
int mins = 0;
int sec = 0;
void showClk() {
   system("cls");
   cout << setfill(' ') << setw(55) << " TIMER \n";
   cout << setfill(' ') << setw(66) << " --------------------------------------\n";
   cout << setfill(' ') << setw(29);
   cout << "| " << setfill('0') << setw(2) << hrs << " Hours | ";
   cout << setfill('0') << setw(2) << mins << " Minutes | ";
   cout << setfill('0') << setw(2) << sec << " Seconds |" << endl;
   cout << setfill(' ') << setw(66) << " --------------------------------------\n";
}
void systemCallTimer() {
   while (true) {
      showClk();
      sleep(1);
      sec++;
      if (sec == 60) {
         mins++;
         if (mins == 60) {
            hrs++;
            mins = 0;
         }
         sec = 0;
      }
   }
}
int main() {
   systemCallTimer();
}
Check if a number is Palindrome in PL/SQLs

In this section we will see how to check whether a number is Palindrome or not using the PL/SQL. In PL/SQL code, some group of commands are arranged within a block of related declaration of statements.
A number is palindrome if the number, and the reverse of that number are same. Suppose a number 12321, this is palindrome, but 12345 is not a palindrome.
DECLARE
   n number;
   m number;
   temp number:=0;
   rem number;
BEGIN
   n :=12321;
   m :=n;
   while n>0
   loop
      rem := mod(n,10);
      temp := (temp*10)+rem;
      n := trunc(n/10);
   end loop;
   if m = temp
   then
      dbms_output.put_line('Palindrome');
   else
      dbms_output.put_line('Not Palindrome');
   end if;
END;
Palindrome
Line Separator in Java

Strings have no newlines. We can form them into two lines by concatenating a newline string. Use System lineSeparator to get a platform-dependent newline string.
The following is an example.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str = "one" + System.lineSeparator() + "two";
      System.out.println(str);
   }
}
one
two
Let us see another example. On Linux based system, the program will work correctly.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str = System.lineSeparator();
      System.out.println((int) str.charAt(0));
   }
}
10
Python | os.kill() method - GeeksforGeeks

03 Jul, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.kill() method in Python is used to send specified signal to the process with specified process id. Constants for the specific signals available on the host platform are defined in the signal module.
Syntax: os.kill(pid, sig)Parameters: pid: An integer value representing process id to which signal is to be sent. sig An integer representing signal number or the signal constant available on the host platform defined in the signal module to be sent.Return type: This method does not return any value.  
Code: Use of os.kill() method  
Python3
# Python program to explain os.kill() method # importing os and signal module import os, signal # Create a child process# using os.fork() methodpid = os.fork()  # pid greater than 0# indicates the parent processif pid :               print("\nIn parent process")     # send signal 'SIGSTOP'    # to the child process    # using os.kill() method    # 'SIGSTOP' signal will    # cause the process to stop    os.kill(pid, signal.SIGSTOP)          print("Signal sent, child stopped.")       info = os.waitpid(pid, os.WSTOPPED)    # waitpid() method returns a    # tuple whose first attribute    # represents child's pid    # and second attribute    # representing child's status indication      # os.WSTOPSIG() returns the signal number    # which caused the process to stop    stopSignal = os.WSTOPSIG(info[1])    print("Child stopped due to signal no:", stopSignal)    print("Signal name:", signal.Signals(stopSignal).name)          # send signal 'SIGCONT'    # to the child process    # using os.kill() method    # 'SIGCONT' signal will    # cause the process to continue    os.kill(pid, signal.SIGCONT)    print("\nSignal sent, child continued.")          else :         print("\nIn child process")    print("Process ID:", os.getpid())    print("Hello ! Geeks")    print("Exiting")
In child process

In parent process
Signal sent, child stopped.
Child stopped due to signal no: 19
Signal name: SIGSTOP

Signal sent, child continued.

Process ID: 5166
Hello! Geeks
Exiting
 
References: https://docs.python.org/3/library/os.html#os.kill 
rajeev0719singh
python-os-module
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Degree of an Array in C++

Suppose we have an array of non-negative integers called nums, the degree of this array is actually the maximum frequency of any one of its elements. We have to find the smallest possible length of a contiguous subarray of nums, that has the same degree as nums.
So, if the input is like [1,2,2,3,1], then the output will be 2, this is because the input array has a degree of 2 because both elements 1 and 2 appear twice. The subarrays that have the same degree − [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So
answer will be 2.
To solve this, we will follow these steps −
Define an array freq of size 50000 and fill this with 0
max_ := 0
for each n in nums(increase freq[n] by 1)max_ := maximum of max_ and freq[n]
(increase freq[n] by 1)
max_ := maximum of max_ and freq[n]
fill freq array with 0.
min_ := size of nums
for initialize i := 0, j := -1, size := size of nums, when j < size, do −if j >= 0 and freq[nums[j]] is same as max_, then −min_ := minimum of min_ and j - i + 1otherwise when j < size - 1, then −increase j by 1increase freq[nums[j]] by 1OtherwiseCome out from the loop
if j >= 0 and freq[nums[j]] is same as max_, then −min_ := minimum of min_ and j - i + 1
min_ := minimum of min_ and j - i + 1
otherwise when j < size - 1, then −increase j by 1increase freq[nums[j]] by 1
increase j by 1
increase freq[nums[j]] by 1
OtherwiseCome out from the loop
Come out from the loop
return min_
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findShortestSubArray(vector<int>& nums) {
      vector<int> freq(50000, 0);
      int max_ = 0;
      for (const int n : nums)
         max_ = max(max_, ++freq[n]);
      fill(freq.begin(), freq.end(), 0);
      int min_ = nums.size();
      for (int i = 0, j = -1, size = nums.size(); j < size;) {
         if (j >= 0 && freq[nums[j]] == max_)
            min_ = min(min_, j - i + 1), --freq[nums[i++]];
         else if (j < size - 1)
            ++freq[nums[++j]];
         else
         break;
      }
      return min_;
   }
};
main(){
   Solution ob;
   vector<int> v = {1, 2, 2, 3, 1};
   cout << (ob.findShortestSubArray(v));
}
{1, 2, 2, 3, 1}
2
How can we get the client's IP address in ASP.NET MVC C#?

Every machine on a network has a unique identifier. Just as you would address a letter
to send in the mail, computers use the unique identifier to send data to specific
computers on a network. Most networks today, including all computers on the
internet, use the TCP/IP protocol as the standard for how to communicate on the
network. In the TCP/IP protocol, the unique identifier for a computer is called its IP
address.
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public string Index(){
         string ipAddress = Request.UserHostAddress;
         return ipAddress;
      }
   }
}
If we want to fetch IP address outside the controller i.e. in a normal class, we can do
like below.
using System.Web;
namespace DemoMvcApplication.Helpers{
   public static class DemoHelperClass{
      public static string GetIPAddress(){
         string ipAddress = HttpContext.Current.Request.UserHostAddress;
         return ipAddress;
      }
   }
}
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public string Index(){
         string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
         return ipAddress;
      }
   }
}
Since we are running the application locally, the ip address for the localhost is ::1.
The name localhost normally resolves to the IPv4 loopback address 127.0.0.1, and to
the IPv6 loopback address ::1
Python | How to copy data from one excel sheet to another - GeeksforGeeks

03 Oct, 2019
In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python.
For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. It can be installed using the following command:
Sudo pip3 install openpyxl
For copying one excel file to another, we first open both the source and destination excel files. Then we calculate the total number of rows and columns in the source excel file and read a single cell value and store it in a variable and then write that value to the destination excel file at a cell position similar to that of the cell in source file. The destination file is saved.
Procedure –
1) Import openpyxl library as xl.2) Open the source excel file using the path in which it is located.
Note: The path should be a string and have double backslashes (\\) instead of single backslash (\). Eg: Path should be C:\\Users\\Desktop\\source.xlsx Instead of C:\Users\Admin\Desktop\source.xlsx
3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is ‘n-1’. For example, the index of worksheet 1 is 0.4) Open the destination excel file and the active worksheet in it.5) Calculate the total number of rows and columns in source excel file.6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable.7) Save the destination file.
# importing openpyxl moduleimport openpyxl as xl;  # opening the source excel filefilename ="C:\\Users\\Admin\\Desktop\\trading.xlsx"wb1 = xl.load_workbook(filename)ws1 = wb1.worksheets[0]  # opening the destination excel file filename1 ="C:\\Users\\Admin\\Desktop\\test.xlsx"wb2 = xl.load_workbook(filename1)ws2 = wb2.active  # calculate total number of rows and # columns in source excel filemr = ws1.max_rowmc = ws1.max_column  # copying the cell values from source # excel file to destination excel filefor i in range (1, mr + 1):    for j in range (1, mc + 1):        # reading cell value from source excel file        c = ws1.cell(row = i, column = j)          # writing the read value to destination excel file        ws2.cell(row = i, column = j).value = c.value  # saving the destination excel filewb2.save(str(filename1))
Source File:
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
Python - tensorflow.math.square() - GeeksforGeeks

16 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
square() is used to compute element wise square of x i.e x*x.
Syntax: tensorflow.math.square(x, name)
Parameters:
x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf  # Initializing the input tensora = tf.constant([ -5, -7, 2, 5, 7], dtype = tf.float64)  # Printing the input tensorprint('a: ', a)  # Calculating resultres = tf.math.square(a)  # Printing the resultprint('Result: ', res)
Output:
a:  tf.Tensor([-5. -7.  2.  5.  7.], shape=(5, ), dtype=float64)
Result:  tf.Tensor([25. 49.  4. 25. 49.], shape=(5, ), dtype=float64)




Example 2: Visualization
Python3
# import tensorflow as tfimport matplotlib.pyplot as plt  # Initializing the input tensora = tf.constant([ -7, -5, 2, 5, 7], dtype = tf.float64)  # Calculating tangentres = tf.math.square(a)  # Plotting the graphplt.plot(a, res, color ='green')plt.title('tensorflow.math.square')plt.xlabel('Input')plt.ylabel('Result')plt.show()
Output:
Python Tensorflow-math-functions
Python-Tensorflow
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 drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
How to query a key having space in its name with MongoDB?

To query a key having space in its name, you can use dot(.) notation.
Step 1: First, you need to create a set in which a key has space in its name. Following is the
query:
> myValues["Details"] = {}
{ }
> myValues["Details"]["Student Name"]="John";
John
> myValues["Details"]["StudentAge"]=26;
26
Step 2: Now you need to create a collection and store the above set as a document. Following
is the query
> db.keyHavingSpaceDemo.insertOne( myValues);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27e3b6304881c5ce84ba4")
}
Following is the query to display all documents from a collection with the help of find() method
> db.keyHavingSpaceDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca27e3b6304881c5ce84ba4"),
   "Details" : {
      "Student Name" : "John",
      "StudentAge" : 26
   }
}
Here is how you can query a key having space in its name i.e. “Student Name”. Following is the
query
> db.keyHavingSpaceDemo.find({ "Details.Student Name": "John"} ).pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca27e3b6304881c5ce84ba4"),
   "Details" : {
      "Student Name" : "John",
      "StudentAge" : 26
   }
}
C++ Program to Subtract Complex Number using Operator Overloading

Operator overloading can be done with most of the built-in operators in C++. The overloaded operators are functions with the keyword operator followed by the operator symbol that is defined. The overloaded operators have a return type and a parameter list like any function.
A program that subtracts complex numbers using operator overloading is as follows −
 Live Demo
#include<iostream>
using namespace std;
class ComplexNum {
   private:
   int real, imag;
   public:
   ComplexNum(int r = 0, int i =0) {
      real = r;
      imag = i;
   }
   ComplexNum operator - (ComplexNum const &obj1) {
      ComplexNum obj2;
      obj2.real = real - obj1.real;
      obj2.imag = imag - obj1.imag;
      return obj2;
   }
   void print() {
      if(imag>=0)
      cout << real << " + i" << imag <<endl;
      else
      cout << real << " + i(" << imag <<")"<<endl;
   }
};
int main() {
   ComplexNum comp1(15, -2), comp2(5, 10);
   cout<<"The two comple numbers are:"<<endl;
   comp1.print();
   comp2.print();
   cout<<"The result of the subtraction is: ";
   ComplexNum comp3 = comp1 - comp2;
   comp3.print();
}
The two comple numbers are:
15 + i(-2)
5 + i10
The result of the subtraction is: 10 + i(-12)
In the above program, the class ComplexNum is defined which has variables real and imag for the real and imaginary part of a complex number respectively. The constructor ComplexNum is used to initialize the values of real and imag. It also contains the default values as 0. This is shown in the following code snippet −
class ComplexNum {
   private:
   int real, imag;
   public:
   ComplexNum(int r = 0, int i =0) {
      real = r;
      imag = i;
   }
}
The function that is the overloaded operator contains the keyword operator followed by - as that is the operator being overloaded. The function subtracts the two complex numbers and the result is stored in the object obj2. Then this value is returned to the ComplexNum object comp3.
The following code snippet demonstrates this −
ComplexNum operator - (ComplexNum const &obj1) {
   ComplexNum obj2;
   obj2.real = real - obj1.real;
   obj2.imag = imag - obj1.imag;
   return obj2;
}
The print() function prints the real and imaginary part of the complex number. This is shown as follows.
void print() {
   if(imag>=0)
   cout << real << " + i" << imag <<endl;
   else
   cout << real << " + i(" << imag <<")"<<endl;
}
Lodash _.update() Method - GeeksforGeeks

16 Sep, 2020
The _.update() method accepts updater to produce the value to set. This method use _.updateWith() function to customize path creation. It is almost the same as _.set() function.
Syntax:
_.update(object, path, updater)

Parameters: This method accepts three parameters as mentioned above and described below:
object: This parameter holds the object to modify.
path: This parameter holds the path of the property to set. It will be array or string.
updater: This is the function to produce the updated value.
Return Value: This method returns the new object.
Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.  
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] };  // Use of _.update() method _.update(obj, 'cpp[0].java.python',     function(n) { return n * n; });  // return the new objectconsole.log(obj.cpp[0].java.python);
Output:
9

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] };  // Use of _.update() method _.update(obj, 'html[0].css.javascript',     function(n) { return n ? n + 1 : 0; });  // return the new objectconsole.log(obj.html[0].css.javascript);
Output:
0

Note: This will not work in normal JavaScript because it requires the library lodash to be installed. 
Reference: https://lodash.com/docs/4.17.15#update
JavaScript-Lodash
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
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Data Structures | Heap | Question 3 - GeeksforGeeks

28 Jun, 2021
A 3-ary max heap is like a binary max heap, but instead of 2 children, nodes have 3 children. A 3-ary heap can be represented by an array as follows: The root is stored in the first location, a[0], nodes in the next level, from left to right, is stored from a[1] to a[3]. The nodes from the second level of the tree from left to right are stored from a[4] location onward. An item x can be inserted into a 3-ary heap containing n items by placing x in the location a[n] and pushing it up the tree to satisfy the heap property.
Which one of the following is a valid sequence of elements in an array representing 3-ary max heap?(A) 1, 3, 5, 6, 8, 9(B) 9, 6, 3, 1, 8, 5(C) 9, 3, 6, 8, 5, 1(D) 9, 5, 6, 8, 3, 1Answer: (D)Explanation: Following 3-ary Max Heap can be constructed from sequence given option (D)
                                      9
                                   /  |   \
                                /     |     \
                              5       6      8
                           /  |
                         /    |
                       3      1

Quiz of this Question
Data Structures
Data Structures-Heap
Heap Quizzes
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count number of times each Edge appears in all possible paths of a given Tree
Difference between Singly linked list and Doubly linked list
Program to create Custom Vector Class in C++
Introduction to Data Structures
Data Structures | Stack | Question 2
Data Structures | Queue | Question 2
Advantages and Disadvantages of Linked List
Advantages of vector over array in C++
Data Structures | Queue | Question 11
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
PyQt5 – How to make semi-transparent label ? - GeeksforGeeks

26 Mar, 2020
While designing a GUI (Graphical User Interface) application we tend to make lot of labels, but sometimes some labels overlaps each other and only label which is on top is visible, that’s why semi transparent label is needed.
Normal label vs Semi-transparent label –        
In order to create semi-transparent labels setStyleSheet() method is used.
Syntax : label.setStyleSheet(“background-color: rgba(255, 255, 255, 10);”)Here we are setting color using RGBA i.e transparency factor, 255 is completely opaque, and an alpha of 0 is completely transparent.
Argument: It takes string as argument.
Action performed : It makes the color of the label transparent.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        # by default label will display at top left corner        self.label_1 = QLabel('back', self)          # moving position        self.label_1.move(100, 100)          # setting up border and background color        self.label_1.setStyleSheet("background-color: lightgreen;                                    border: 3px solid green")          # creating a label widget        # by default label will display at top left corner        self.label_2 = QLabel('front', self)            # moving position        self.label_2.move(140, 100)          # setting up border and background        # color with transparency factor         self.label_2.setStyleSheet("border: 3px solid blue;                   background-color: rgba(0, 255, 255, 90);")                  # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
aplaymidi Command in Linux with Examples - GeeksforGeeks

24 Jun, 2019
aplaymidi command in Linux is used to play standard MIDI(Musical Instrument Digital Interface) files, by sending the content of a MIDI file to an ALSA(Advanced Linux Sound Architecture) MIDI port, sound renderer like timidity or a hardware MIDI device are required to play MIDI files.
Syntax:
aplaymidi [options] [MIDIfile]
Options:
-h or –help: This is used to show all the options and syntax of the command.$ aplaymidi -h
$ aplaymidi -h
-V or –version: It is used to display the current version of the SW.$ aplaymidi -V
$ aplaymidi -V
-l or –list: It is used to display the list of all possible MIDI output ports.$ aplaymidi -l
$ aplaymidi -l
-p or –port=client:port : It specifies ports(s) to play MIDI to.$ aplaymidi -p 14:0 test1.mid
$ aplaymidi -p 14:0 test1.mid
-d or –delay=seconds : It delay once MIDI sound ends.$ aplaymidi -p 14:0 -d 10 test1.mid
$ aplaymidi -p 14:0 -d 10 test1.mid
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Benefit of NumPy arrays over Python arrays - GeeksforGeeks

05 Sep, 2020
The need for NumPy arises when we are working with multi-dimensional arrays. The traditional array module does not support multi-dimensional arrays.
Let’s first try to create a single-dimensional array (i.e one row & multiple columns) in Python without installing NumPy Package to get a more clear picture.
Python3
from array import *    arr = array('i', [25, 16, 3])print(arr)
Output:
array('i', [25, 16, 3])

Now, Let’s try to create a multi-dimensional array by using the array module.
Python3
from array import *    arr = array('i', [25, 16, 3], [5, 19, 28])print(arr)
Output:
TypeError: array() takes at most 2 arguments (3 given)

We see that the array module does not support multi-dimensional array, this is where we require NumPy. NumPy supports large, multi-dimensional arrays and has a large collection of high-level math functions that can operate on those arrays.
Let’s use NumPy to create a multi-dimensional array.
Python3
from numpy import *    arr = array ([[25, 31, 3], [5, 19, 28]])print(arr)
Output:
[[25 31  3]
 [ 5 19 28]]

Python-numpy
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 | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to restrict UITextField to take only numbers in Swift?

In iOS apps sometimes we need to restrict our text field to take only numbers as an input, this can be done in several ways, let’s see some of them.
Select the text field that you want to restrict to numeric input.
Go to its attribute inspector.
Select the keyboard type and choose number pad from there.
Select the text field
Create its outlet in the view controller.
Conform the view controller to UITextFieldDelegate
Set the text field’s delegate
Add the following function
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
   if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
      return true
   } else {
      return false
   }
}
Our whole example class looks like
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
   @IBOutlet weak var tf: UITextField!
      override func viewDidLoad() {
         tf.delegate = self
         super.viewDidLoad()
      }
      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
            return true
         } else {
         return false
      }
   }
}
This will create a text field that can only take digits as input and no other character.
Tryit Editor v3.7

Tryit: Different RGBA colors
Convert JSON to/from Map using Jackson library in Java?

The JSON Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can convert JSON to/from
Map using readValue() and writeValueAsString() methods of com.fasterxml.jackson.databind.ObjectMapper class.
public <T> T readValue(String content, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
public class ConvertJSONToMapTest {
   public static void main(String args[]) {
      try {
         ObjectMapper mapper = new ObjectMapper();
         String jsonString = "{\"Name\":\"Raja\", \"Technology\":\"Java\"}";
         Map<String, Object> jsonMap = new HashMap<String, Object>();
         jsonMap = mapper.readValue(jsonString, new TypeReference<Map<String, String>>(){}); // converts JSON to Map
         System.out.println(jsonMap);
      } catch(IOException ie) {
         ie.printStackTrace();
      }
   }
}
{Name=Raja, Technology=Java}
public String writeValueAsString(Object value) throws JsonProcessingException
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvertMapToJSONTest {
   public static void main(String args[]) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "";
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Raja", "Java Technology");
      map.put("Ravi", "Python Technology");
      map.put("Adithya", "Spark Technology");
      map.put("Vamsi", "Web Technology");
      jsonString = mapper.writeValueAsString(map); // converts Map to JSON
      System.out.println(map);
   }
}
{"Raja":"Java Technology", "Vamsi":"Web Technology", "Ravi":"Python Technology", "Adithya":"Spark Technology"}
How to give a div tag 100% height of the browser window using CSS - GeeksforGeeks

04 Dec, 2018
CSS allows to adjust the height of an element using the height property. While there are several units to specify the height of an element. The vh is a relative unit that is commonly used.
vh: It stands for viewport-height. The viewport refers to the browser window size. Thus when use vh as a unit, the element’s height is adjusted relative to the browser window (viewport’s) height.vw: It stands for viewport-width. It is used to set the browser width 100% relative to the browser window (viewport’s) width.
Syntax: To set a div element height to 100% of the browser window, it can simply use the following property of CSS:
height:100vh;
Example:
<!DOCTYPE html><!DOCTYPE html><html>    <head>        <title>Make div 100% of height</title>        <style>            #geeks {                height: 100vh;                width: 100vw;                font-size: 20px;                font-family: Times;                padding-top: 250px;                                 margin: 0px;                         background-color: green;                text-align: center;                color:white;            }            .gfg {                font-size:40px;                font-weight:bold;            }        </style>    </head>    <body>        <div id="geeks">        <div class = "gfg">GeeksforGeeks</div>        <div>A computer science portal for geeks</div>        </div>    </body></html>                    
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
Picked
Web technologies
CSS
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 create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
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 ?