code-rag-bench/online-tutorials huggingface dataset:
FileInputStream close() Method in Java with Examples

01 Dec, 2021
FileInputStream class is helpful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
After any operation to the file, we have to close that file. For that purpose, we have a close method. We will learn that in this article. The FileInputStream.close() method closes this file input stream and releases any system resources associated with the stream.
Syntax:
FileInputStream.close()
Return Value: The method does not return any value.
Exception: IOException − If any I/O error occurs.
Step 1: Attach a file to a FileInputStream as this will enable us to close the file as shown below as follows:
FileInputStream  fileInputStream =new FileInputStream(“file.txt”);
Step 2: To close the file, we have to call the close() method using the above instance.
fileInputStream.close(); 
Approach:
1. We will first read a file and then close it.
2. After closing a file, we will again try to read it.
Java
// Java program to demonstrate the working// of the FileInputStream close() method  import java.io.File;import java.io.FileInputStream;  public class abc {      public static void main(String[] args)    {          // Creating file object and specifying path        File file = new File("file.txt");          try {            FileInputStream input                = new FileInputStream(file);            int character;            // read character by character by default            // read() function return int between            // 0 and 255.              while ((character = input.read()) != -1) {                System.out.print((char)character);            }              input.close();            System.out.println("File is Closed");            System.out.println(                "Now we will again try to read");            while ((character = input.read()) != -1) {                System.out.print((char)character);            }        }        catch (Exception e) {            System.out.println(                "File is closed. Cannot be read");            e.printStackTrace();        }    }}
Output
GeeksforGeeks is a computer science portal
File is Closed
Now we will again try to read
File is closed. Cannot be read
java.io.IOException: Stream Closed
       at java.base/java.io.FileInputStream.read0(Native Method)
       at java.base/java.io.FileInputStream.read(Unknown Source)
       at abc.main(abc.java:28)
Note: This code will not run on an online IDE as it requires a file on the system.
Java-FileInputStream
Java-Functions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
GATE | GATE CS 2020 | Question 65 - GeeksforGeeks

26 May, 2021
Consider a TCP connection between a client and a server with the following specifications; the round trip time is 6 ms, the size of the receiver advertised window is 50 KB, slow-start threshold at the client is 32 KB, and the maximum segment size is 2 KB. The connection is established at time t=0. Assume that there are no timeouts and errors during transmission.
Then the size of the congestion window (in KB) at time t+60 ms after all acknowledgements are processed is _________ .
Note – This question was Numerical Type.(A) 33(B) 44(C) 55(D) 50Answer: (B)Explanation: Given,
Threshold = 32 Kb, 
MSS = 2KB, 
RTT = 6ms 
Here, t + 60 is nothing but at the 10 RTT (60/6 = 10).
Now,
1st transmission: 2 KB
2nd transmission: 4 KB
3rd transmission: 8 KB
4th transmission: 16 KB
5th transmission: 32 KB (Threshold reached)
6th transmission: 34 KB
7th transmission: 36 KB
8th transmission: 38 KB
9th transmission: 40 KB
10th transmission: 42 KB 
Now, after receiving acknowledgements of 10th transmission RTT = 10*6 = 60 ms.
And, after receiving acknowledgements of 10th transmission RTT (means at 11th transmission),The congestion window size will be 44 KB.
Option (B) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Matplotlib.axes.Axes.set_ybound() in Python - GeeksforGeeks

19 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.set_ybound() function in axes module of matplotlib library is used to set the lower and upper numerical bounds of the y-axis.
Syntax: Axes.set_ybound(self, lower=None, upper=None)
Parameters: This method accepts the following parameters.
lower, upper: These parameters are the lower and upper bounds. If None, the respective axis bound is not modified.
Returns:This method returns the following
lower, upper :This returns the new lower and upper y-axis bounds.
Note: This function can be used in place of set_ylim in various conditions.
Below examples illustrate the matplotlib.axes.Axes.set_ybound() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionfrom matplotlib.widgets import Cursorimport numpy as npimport matplotlib.pyplot as plt      np.random.seed(19680801)   fig, ax = plt.subplots()   x, y = 4*(np.random.rand(2, 50) - .5)ax.plot(x, y, 'g')ax.set_ybound(-4, 4)       ax.set_title('matplotlib.axes.Axes.set_ybound() Example\n',             fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np   fig1, ax1 = plt.subplots()fig2, ax2 = plt.subplots()ax1.set(xlim =(-0.5, 1.5), ylim =(-0.5, 1.5),         autoscale_on = False)  ax2.set(xlim =(0.5, 0.75), ylim =(0.5, 0.75),        autoscale_on = False)   x, y, s, c = np.random.rand(4, 200)s *= 200   ax1.scatter(x, y, s, c)ax2.scatter(x, y, s, c)      def GFG(event):      if event.button != 1:        return      x, y = event.xdata, event.ydata    ax2.set_xbound(x - 0.1, x + 0.1)    ax2.set_ybound(y - 0.2, y + 0.2)    fig2.canvas.draw()   fig1.canvas.mpl_connect('button_press_event', GFG)   ax1.set_title('matplotlib.axes.Axes.set_ybound()\ Example\n Original Window ',             fontsize = 14, fontweight ='bold')  ax2.set_title('Zoomed window ',             fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
numpy.info() function in Python - GeeksforGeeks

25 Oct, 2020
In Numpy we can get all the information about the function, class, or module like what will the parameter and what will be the type of the return value with the help of numpy.info() function. This function returns the help information for a function, class, or module.
Syntax: numpy.info(numpy.info(object=None, maxwidth=76, output=<_io.TextIOWrapper name='<stdout>’ mode=’w’ encoding=’utf-8′>, toplevel=’numpy’))
Parameters:
objectobject or str, optional: This is object or name for input to get information about.
maxwidthint, optional: For Width.
outputfile like object, optional: Object opening mode.
toplevelstr, optional: Start search at this level.
Return: All the information about add function in the numpy.
Example :
Python
import numpy as np    print(np.info(np.add))
Output :
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
T-Test Approach in R Programming - GeeksforGeeks

16 Dec, 2021
We will be trying to understand the T-Test in R Programming with the help of an example. Suppose a businessman with two sweet shops in a town wants to check if the average number of sweets sold in a day in both the stores is the same or not. 
So, the businessman takes the average number of sweets sold to 15 random people in the respective shops. He found out that the first shop sold 30 sweets on average whereas the second shop sold 40. So, from the owner’s point of view, the second shop was doing better business than the former. But the thing to notice is that the data-set is based on a mere number of random people and they cannot represent all the customers. This is where T-testing comes into play it helps us to understand that the difference between the two means is real or simply by chance.
Mathematically, what the t-test does is, take a sample from both sets and establish the problem assuming a null hypothesis that the two means are the same.
Classification of T-tests
One Sample T-test
Two sample T-test
Paired sample T-test
The One-Sample T-Test is used to test the statistical difference between a sample mean and a known or assumed/hypothesized value of the mean in the population. 
So, for performing a one-sample t-test in R, we would use the syntax t.test(y, mu = 0) where x is the name of the variable of interest and mu is set equal to the mean specified by the null hypothesis. 
For Example: 
R
set.seed(0)sweetSold <- c(rnorm(50, mean = 140, sd = 5))t.test(sweetSold, mu = 150) # Ho: mu = 150
Output:
It is used to help us to understand that the difference between the two means is real or simply by chance. The general form of the test is t.test(y1, y2, paired=FALSE). By default, R assumes that the variances of y1 and y2 are unequal, thus defaulting to Welch’s test. To toggle this, we use the flag var.equal=TRUE.
For Example: 
R
set.seed(0) shopOne <- rnorm(50, mean = 140, sd = 4.5)shopTwo <- rnorm(50, mean = 150, sd = 4) t.test(shopOne, shopTwo, var.equal = TRUE)
Output:
This is a statistical procedure that is used to determine whether the mean difference between two sets of observations is zero. In a paired sample t-test, each subject is measured two times, resulting in pairs of observations.
The test is run using the syntax t.test(y1, y2, paired=TRUE)
For Example:
R
set.seed(2820) sweetOne <- c(rnorm(100, mean = 14, sd = 0.3))sweetTwo <- c(rnorm(100, mean = 13, sd = 0.2)) t.test(sweetOne, sweetTwo, paired = TRUE)
Output:
kumar_satyam
Picked
R-Mathematics
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
Scala Set size() method with example - GeeksforGeeks

18 Oct, 2019
The size() method is utilized to find the number of elements in the set.
Method Definition: def size: Int
Return Type: It returns the number of elements in the set.
Example #1:
// Scala program of size() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(1, 2, 3, 4, 5)                   // Applying size method         val result = s1.size                  // Display output        println(result)    } } 
5

Example #2:
// Scala program of size() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(1, 0)                   // Applying size method         val result = s1.size                  // Display output        println(result)    } } 
2

Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala | Arrays
How to get the first element of List in Scala
Inheritance in Scala
Scala String replace() method with example
Scala Map get() method with example
RequireJS - jQuery Using Shim Config

jQuery uses shim configuration to define the dependencies for jQuery plugins and set a module value by declaring dependencies.
require(['jquery','jquery.myjsfile1','jquery.myjsfile2'], function($) {
   $(function() {
      //code here
   });
});
The following example uses shim configuration to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it −
<!DOCTYPE html>
<html>
   <head>
      <title>jQuery Shim Config</title>
      <script data-main = "app" src = "lib/require.js"></script>
   </head>
   
   <body>
      <h2>jQuery Shim Config</h2>
      <p>Welcome to Tutorialspoint!!!</p>
   </body>
</html>
Create a js file with the name app.js and add the following code in it −
//You can configure loading modules from the lib directory
requirejs.config ({
   "baseUrl": "lib",
   
   "paths": {
      "app": "../app"
   },
   
   "shim": {
      "jquery.shim1": ["jquery"],
      "jquery.shim2": ["jquery"]
   }
});

//To start the application, load the main module from app folder
requirejs(["app/main"]);
Create a folder called app and load the main.js module from this folder −
define(["jquery", "jquery.shim1", "jquery.shim2"], function($) {
   //loading the jquery.shim1.js and jquery.shim2.js plugins 
   $(function() {
      $('body').shim1().shim2();
   });
});
Create one more folder called lib to store the require.js file and other js files as shown below −
$.fn.shim1 = function() {
   return this.append('<p>This is shim1 config...!</p>');
};
$.fn.shim2 = function() {
   return this.append('<p>This is shim2 config...!</p>');
};
Open the HTML file in a browser; you will receive the following output −
 Print
 Add Notes
 Bookmark this page
Python - Word Replacement

Replacing the complete string or a part of string is a very frequent requirement in text processing. The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Following is the syntax for replace() method −
str.replace(old, new[, max])
old − This is old substring to be replaced.
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.
max − If this optional argument max is given, only the first count occurrences are replaced.
This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced.
The following example shows the usage of replace() method.
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
When we run above program, it produces the following result −
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

 
import re
sourceline  = re.compile("Tutor", re.IGNORECASE)
 
Replacedline  = sourceline.sub("Tutor","Tutorialspoint has the best tutorials for learning.")
print (Replacedline)

When we run the above program, we get the following output −
Tutorialspoint has the best Tutorials for learning.


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
C Program For Making Middle Node Head In A Linked List - GeeksforGeeks

13 Jan, 2022
Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples:
Input: 1 2 3 4 5 
Output: 3 1 2 4 5

Input: 1 2 3 4 5 6
Output: 4 1 2 3 5 6 
The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head. 
C
// C program to make middle node as // head of linked list.#include <stdio.h>#include <stdlib.h>  // Link list node struct Node {    int data;    struct Node* next;};  /* Function to get the middle and set at   beginning of the linked list*/void setMiddleHead(struct Node** head){    if (*head == NULL)        return;      // To traverse list nodes one by one    struct Node* one_node = (*head);      // To traverse list nodes by skipping    // one.    struct Node* two_node = (*head);      // To keep track of previous of middle    struct Node* prev = NULL;    while (two_node != NULL &&            two_node->next != NULL)     {        // For previous node of middle node         prev = one_node;          // Move one node each time        two_node = two_node->next->next;          // Move two node each time        one_node = one_node->next;    }      // Set middle node at head     prev->next = prev->next->next;    one_node->next = (*head);    (*head) = one_node;}  // To insert a node at the beginning // of linked list.void push(struct Node** head_ref,           int new_data){    // Allocate node     struct Node* new_node =           (struct Node*)malloc(sizeof(struct Node));      new_node->data = new_data;      // Link the old list off the new node     new_node->next = (*head_ref);      // Move the head to point to the     // new node     (*head_ref) = new_node;}  // A  function to print a given linked listvoid printList(struct Node* ptr){    while (ptr != NULL)    {        printf("%d ", ptr->data);        ptr = ptr->next;    }    printf("");}  // Driver codeint main(){    // Create a list of 5 nodes    struct Node* head = NULL;    int i;    for (i = 5; i > 0; i--)        push(&head, i);      printf(" list before: ");    printList(head);      setMiddleHead(&head);      printf(" list After:  ");    printList(head);      return 0;}
Output:
list before: 1 2 3 4 5
list After : 3 1 2 4 5 
Please refer complete article on Make middle node head in a linked list for more details!
Tortoise-Hare-Approach
C Programs
Linked List
Misc
Misc
Linked List
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
Ascii() in python

ASCII is abbreviated from of American Standard Code for Information Interchange. It is a character encoding standard. For example the ASCII value of English alphabet A is 65. Python provides this function to get the printable representation of an object. It takes one parameter which is an object that can be a list, strings, tuple etc. The output of the function is the hex representation. The non-ascii characters can be escaped using \x, \u or \U escapes.
The syntax is −
Syntax:
ascii(object)
Printing strings with individual characters and multiple characters.
# Individual Characters
print(ascii("Ω"))
print(ascii("θ"))
# A string int multiple characters
print(ascii("TΨtΦrial"))
Running the above code gives us the following result −
'\u03a9'
'\u03b8'
'T\u03a8t\u03a6rial'
PHP date_interval_format() Function

The date_interval_format() function is an alias of DateInterval::format(). This function accepts an interval and a format string as parameters and, formats the given interval in the specified format.
date_interval_format($interval, $format)

interval (Mandatory)
This is an object of the DateInterval you need to format.
format (Mandatory)
This is a string value, specifying the format.
This function returns the formatted interval
This function was first introduced in PHP Version 5.3 and, works with all the later versions.
Following example demonstrates the usage of the date_interval_create_from_date_string() function −
<?php
  $interval = new DateInterval('P25DP8MP9Y');
  $format = "%d days;
  $res = date_interval_format($interval, $format);
  print($res);  
?>
This will produce following result −
25 days

Unlike other date/time functions date_interval_format() doesn't recalculate carry over points in date and time strings. Therefore if you pass date/time values beyond their boundaries, they will be formatted as it is  −
<?php
   $interval = new DateInterval('P45M');
   $format = "%m months";
   $res1 = date_interval_format($interval, $format);
   print($res1); 
  
   $res2 = date_interval_format(new DateInterval('PT30H'), "%h hours");
   print("\n".$res2);
?>
This will produce following result −
45 months
30 hours

Following example calculates the difference between a given date and the current date and formats the result using the date_interval_format function −
<?php
   $date1 = date_create("25-09-1989");
   $date2 = date_create("1-09-2012");
   $interval = date_diff($date1, $date2);
   $res = date_interval_format($interval, '%Y years %d days');
   print($res);  

?>
<?php
print(date_interval_format(new DateInterval('P12D'), "%d days")."\n");
print(date_interval_format(new DateInterval('P7M'), "%m months")."\n");
print(date_interval_format(new DateInterval('P12Y'), "%y years")."\n");
print(date_interval_format(new DateInterval('PT9H'), "%h hours")."\n");
print(date_interval_format(new DateInterval('PT45S'), "%s seconds")."\n");
?>
This will produce following result −
22 years 7 days
12 days
7 months
12 years
9 hours
45 seconds


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
PostgreSQL – Copy Database

22 Feb, 2021
In this article, we will discuss the process of copying a PostgreSQL database on the same server or from a server to another. 
If a situation arises where one needs to copy a PostgreSQL database within a database server for testing purposes. PostgreSQL makes it simple to do so using the CREATE DATABASE statement as follows: 
Syntax:
CREATE DATABASE target_database 
WITH TEMPLATE source_database;
This statement copies the source_database to the target_database. For instance, to copy the dvdrental sample database which is described here and can be downloaded from here, to the dvdrental_test database, you use the following statement: 
CREATE DATABASE dvdrental_test 
WITH TEMPLATE dvdrental;
It may take a while to complete copying depending upon the size of the original database. 
There are many ways to copy a database between various PostgreSQL database servers. The connection between servers grows slower as the database gets larger. One way of doing so is to create a database dump and restore the same dump to another server. To do so the following commands need to be followed: 
Step 1: Create a Dump file of the source database.
pg_dump -U postgres -d source_database -f source_database.sql
Step 2: Copy the dump file to the remote server. 
Step 3: Create a new database in the remote server where you want to restore the database dump:
CREATE DATABASE target_database;
Step 4: Restore the dump file on the remote server: 
psql -U postgres -d target_database -f source_database.sql
Example: Here we will copy the dvdrental database from the local server to the remote server. First, we will dump the dvdrental database into a dump file e.g., dvdrental.sql: 
pg_dump -U postgres -O dvdrental dvdrental.sql
Then we will copy the dump file to a remote server and we will create the dvdrental database on the remote server: 
CREATE DATABASE dvdrental;
Now, we will restore the dump file that we just created into the remote server: 
psql -U postgres -d dvdrental -f dvdrental.sql
For high-speed connections between servers or for smaller databases, you can also use the following command: 
pg_dump -C -h local -U localuser source_database | psql -h remote -U remoteuser target_database
For instance, if one desires to copy the dvdrental database from the localhost to the remote server, you do it as follows: 
pg_dump -C -h localhost -U postgres dvdrental | psql -h remote -U postgres dvdrental
RajuKumar19
postgreSQL-managing-database
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - SELECT DISTINCT clause
Python 3 - Number atan2() Method

The atan2() method returns atan(y / x), in radians.
Following is the syntax for atan2() method −
atan2(y, x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
y − This must be a numeric value.
y − This must be a numeric value.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns atan(y / x), in radians.
The following example shows the usage of atan2() method.
#!/usr/bin/python3
import math

print ("atan2(-0.50,-0.50) : ",  math.atan2(-0.50,-0.50))
print ("atan2(0.50,0.50) : ",  math.atan2(0.50,0.50))
print ("atan2(5,5) : ",  math.atan2(5,5))
print ("atan2(-10,10) : ",  math.atan2(-10,10))
print ("atan2(10,20) : ",  math.atan2(10,20))
When we run the above program, it produces the following result −
atan2(-0.50,-0.50) :  -2.35619449019
atan2(0.50,0.50) :  0.785398163397
atan2(5,5) :  0.785398163397
atan2(-10,10) :  -0.785398163397
atan2(10,20) :  0.463647609001


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Replacing every nth instance of characters in a string - JavaScript

We are required to write a JavaScript function that takes in a string as the first argument, a number, say n, as the second argument and a character, say c, as the third argument. The function should replace the nth appearance of any character with the character provided as the third argument and return the new string.
Following is the code −
const str = 'This is a sample string';
const num = 2;
const char = '*';
const replaceNthAppearance = (str, num, char) => {
   const creds = str.split('').reduce((acc, val, ind, arr) => {
      let { res, map } = acc;
      if(!map.has(val)){
         map.set(val, 1);
         if(num === 0){
            res += char;
         }else{
            res += val;
         }
      }else{
         const freq = map.get(val);
         if(num - freq === 1){
            res += char;
         }else{
            res += val;
      };
      map.set(val, freq+1);
   };
   return { res, map };
   }, {
      res: '',
      map: new Map()
   });
   return creds.res;
}
console.log(replaceNthAppearance(str, num, char));
Following is the output in the console −
This ***a s*mple string
C Program to find IP Address, Subnet Mask & Default Gateway - GeeksforGeeks

09 Nov, 2021
Terminology
IP Address : An IP address, short for Internet Protocol address, is an identifying number for a piece of network hardware. Having an IP address allows a device to communicate with other devices over an IP-based network like the internet.
Subnet mask: A subnet mask is a 32-bit number used to differentiate the network component of an IP address by dividing the IP address into a network address and host address. Subnet masks are used to design subnetworks, or subnets, that connect local networks and determine what subnet an IP address belongs to.
Default Gateway: A default gateway serves as an access point or IP router that a networked computer uses to send information to a computer in another network or the Internet. The default simply means that this gateway is used by default, unless an application specifies another gateway. A default gateway allows computers on a network to communicate with computers on another network. Without it, the network is isolated from the outside.
Using system command
To get the IP Address, Subnet Mask and Default Gateway, we execute ipconfig command in the cmd.Here, we will make use of system() from < stdlib.h > to perform a system operation with the help of a C program:
#include <stdio.h>#include <stdlib.h>  int main(){  system("c:\\windows\\system32\\ipconfig");  return 0;}
Using execl command
This displays the IPv4 address, Subnet Mask and the Default Gateway.The same operation can also be performed with the execl() function.To execute the later, we code:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>  int main(){  execl("c:\\windows\\system32\\ipconfig", "ipconfig", 0);  return 0;}
Output:
This article is contributed by Amaryta Ranjan Saikia. 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.
vaibhavsinghtanwar3
C Language
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Caesar Cipher in Cryptography
Socket Programming in Python
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
Typecasting in C

Typecasting is a method in C language of converting one data type to another.
There are two types of typecasting.
1.Implicit Type casting − This conversion is done by the compiler. When more than one data type of variables are used in an expression, the compiler converts data types to avoid loss of data.
Here is an example of implicit type casting in C language,
 Live Demo
#include <stdio.h>
int main() {
   int a = 10;
   char b = 'S';
   float c = 2.88;
   a = a+b;
   printf("Implicit conversion from character to integer : %d\n",a);
   c = c+a;
   printf("Implicit conversion from integer to float : %f\n",c);
   return 0;
}
Implicit conversion from character to integer : 93
Implicit conversion from integer to float : 95.879997
2.Explicit Type casting − This conversion is done by user. This is also known as typecasting. Data type is converted into another data type forcefully by the user.
Here is the syntax of explicit type casting in C language,
(type) expression
Here is an example of explicit type casting in C language,
 Live Demo
#include <stdio.h>
int main() {
   float c = 5.55;
   int s = (int)c+1;
   printf("Explicit Conversion : %d\n",s);
   return 0;
}
Explicit Conversion : 6
XQuery - FLWOR

FLWOR is an acronym that stands for "For, Let, Where, Order by, Return". The following list shows what they account for in a FLWOR expression −
F - For - Selects a collection of all nodes.
F - For - Selects a collection of all nodes.
L - Let - Puts the result in an XQuery variable.
L - Let - Puts the result in an XQuery variable.
W - Where - Selects the nodes specified by the condition.
W - Where - Selects the nodes specified by the condition.
O - Order by - Orders the nodes specified as per criteria.
O - Order by - Orders the nodes specified as per criteria.
R - Return - Returns the final result.
R - Return - Returns the final result.
Following is a sample XML document that contains information on a collection of books. We will use a FLWOR expression to retrieve the titles of those books with a price greater than 30.
<?xml version="1.0" encoding="UTF-8"?>
<books>
   
   <book category="JAVA">
      <title lang="en">Learn Java in 24 Hours</title>
      <author>Robert</author>
      <year>2005</year>
      <price>30.00</price>
   </book>
   
   <book category="DOTNET">
      <title lang="en">Learn .Net in 24 hours</title>
      <author>Peter</author>
      <year>2011</year>
      <price>70.50</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XQuery in 24 hours</title>
      <author>Robert</author>
      <author>Peter</author> 
      <year>2013</year>
      <price>50.00</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XPath in 24 hours</title>
      <author>Jay Ban</author>
      <year>2010</year>
      <price>16.50</price>
   </book>
   
</books>
The following Xquery document contains the query expression to be executed on the above XML document.
let $books := (doc("books.xml")/books/book)
return <results>
{
   for $x in $books
   where $x/price>30
   order by $x/price
   return $x/title
}
</results>
<title lang="en">Learn XQuery in 24 hours</title>
<title lang="en">Learn .Net in 24 hours</title>

To verify the result, replace the contents of books.xqy (given in theEnvironment Setup chapter) with the above XQuery expression and execute the XQueryTester java program.
 Print
 Add Notes
 Bookmark this page
How to clear the content of the recycle bin in PowerShell?

Recycle bin in Windows operating system is to store the soft-deleted data. Soft deleted data means, data that is not deleted with (SHIFT + DEL) button but simply deleted with DEL button. Each local disk has its own configured recycle bin space.
To delete the recycle bin data using GUI, you can simply right click and delete the content.
It is also possible to delete the recycle bin content with the PowerShell command with the Clear-Recyclebin cmdlet. This command is introduced in PowerShell 5 and available in newer versions as well.
Clear-RecycleBin
PS C:\WINDOWS\system32> Clear-RecycleBin
Confirm
Are you sure you want to perform this action?
Performing the operation "Clear-RecycleBin" on target "All of the contents of the Recycle Bin".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
User needs to confirm how the contents should be deleted as per the above output.
To delete the content of the specific drive, you need to specify –DriveLetter parameter.
Clear-RecycleBin -DriveLetter D
You can also delete the content without the user consent with the –Force parameter.
Clear-RecycleBin -Force
Clear-RecycleBin doesn’t generate any output on the successful deletion of contents.
To delete the recycle bin content of the remote computers, you need to use the remote commands.
For example,
Invoke-Command -ComputerName Test-PC -ScriptBlock{Clear-RecycleBin -Force}

You need to make sure that the remote PowerShell version is also 5.0 or higher while running these commands.
Remove All Adjacent Duplicates in String II in C++

Suppose a string s is given, a k duplicate removal consists of choosing k adjacent and equal letters from string s and removing them causing the left and the right side of the deleted substring to concatenate together. We will repeatedly make k duplicate removals on the given string s until we cannot change any remaining. We have to find the final string after all such duplicate removals have been made. So if the input is like s = “deeedbbcccbdaa”, and k = 3, then the output will be “aa”, at first delete the “eee” and “ccc” and we will get “ddbbbaa”, then delete “bbb”, the string will be “dddaa”, then delete “ddd”, and the output will be “aa”
To solve this, we will follow these steps −
ans := empty string
create one stack for char-int pair, n := size of the string
for i in range 0 to nx := s[i]if stack is not empty and integer of the stack top element = k, then delete top element from stackif i = n, then breakif stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1otherwise increase the integer part of the stack top element, and increase i by 1
x := s[i]
if stack is not empty and integer of the stack top element = k, then delete top element from stack
if i = n, then break
if stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1
otherwise increase the integer part of the stack top element, and increase i by 1
while stack is not emptytemp := stack top elementwhile integer part of temp is not 0,ans := ans + character part of tempdecrease integer part of temp by 1delete the top element from stack
temp := stack top element
while integer part of temp is not 0,ans := ans + character part of tempdecrease integer part of temp by 1
ans := ans + character part of temp
decrease integer part of temp by 1
delete the top element from stack
reverse the ans string and return.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string removeDuplicates(string s, int k) {
      string ans = "";
      stack < pair<char, int> > st;
      int n = s.size();
      for(int i = 0; i <= n;){
         char x = s[i];
         if(!st.empty() && st.top().second == k)st.pop();
         if(i == n)break;
         if(st.empty() || st.top().first != x){
            st.push({x, 1});
            i++;
         } else {
            st.top().second++;
            i++;
         }
      }
      while(!st.empty()){
         pair <char, int> temp = st.top();
         while(temp.second--) ans += temp.first;
         st.pop();
      }
      reverse(ans.begin(), ans.end());
      return ans;
   }
};
main(){
   Solution ob;
   cout <<(ob.removeDuplicates("deeedbbcccbdaa", 3));
}
"deeedbbcccbdaa"
3
aa
Printing the numbers in reverse order using Division and modulo operators using C

How to print the given two-digit number in reverse order with the help of division and Modulo operator using C programming language?
So far, we had seen how to reverse the string using string function and without string function. Now let’s see how to reverse the two-digit number without using the predefined function.
The logic we use to reverse the number with the help of operators is −
int firstno=number%10; //stores remainder
int secondno=number/10;// stores quotient
Then print the first number followed by the second number then you will get the reverse number for the given number.
In this example, we will take a 2-digit number and apply division and modulo operator to reverse the number −
#include<stdio.h>
int main(){
   int number;
   printf("enter a number:");
   scanf("%4d",&number);
   int firstno=number%10; //stores remainder
   int secondno=number/10;// stores quotient
   printf("After reversing =%d%d\n",firstno,secondno);
   return 0;
}
enter a number:45
After reversing =54
In this example, we will take a 3-digit number and apply division and modulo operator to reverse the number −
 Live Demo
#include<stdio.h>
int main(){
   int number,num1,num2,num3,result;
   printf("enter a number:");
   scanf("%4d",&number);
   num1 = number / 100;
   num2 = (number % 100) / 10;
   num3 = number%10 ;
   result = 100*num3 + 10*num2 + num1;
   printf("After reversing =%d\n",result);
   return 0;
}
enter a number:479
After reversing =974
Can we explicitly define datatype in a Python Function?

In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally. In Java, C++, and other statically-typed languages, you must specify the datatype of the function return value and each function argument.
If we explicitly define datatype in a python function, it still works like a normal program where data type is not declared explicitly.
We get the following output for the given code
C:/Users/TutorialsPoint1/~.py
The required Sum is:  13.0
Consider this function
def addSum(x,y):
       return x+y
print addSum(2.2, 5.6)
print addSum(float(2.2), float(5.6))
7.8
7.8
So the declaration of the datatype of a variable explicitly has no impact on the output.
How to bring Tkinter window in front of other windows?

Tkinter window are created and executed by mainloop() function. The mainloop() function gets executed until the application is not closed by the user abruptly.
To keep the Tkinter window above all the other windows, we can use win.after(duration, function()) function in a loop. This function inside the loop gets executed and forces the main window to appear above all the other windows.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Define a function to make the window above
def lift_window():
   win.lift()
   win.after(1000, lift_window)

# Add A label widget
Label(win, text="Hey Folks, Welcome to TutorialsPoint✨", font=('Aerial 18 italic')).place(x=130, y=150)

lift_window()

win.mainloop()
Run the above code to display a window that will appear above all the other windows.
Switch case in Arduino

Switch case in Arduino is just like the switch case in C language. For those who are unaware of switch case, it is a more compact way of writing multiple if statements, when they concern the value of a variable.
switch (var) {
   case value1:
      // statements for value1
      break;
   case value2:
      // statements for value2
      break;
.
.
.
   default:
      // statements for default value
      break;
}
var is the variable whose different values we are checking. If its value is equal to value1, then the statements for value1 will be executed. If its value is equal to value2, then the statements for value2 will be executed, and so on. If the value is not equal to any values listed, then the statements corresponding to the default value will be executed. If you don’t add the break statement after each case, then all the cases following it will be executed, till the first break is encountered.
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   while(!Serial.available()){
      Serial.print('.');
      delay(500);
   }

   int a = Serial.parseInt();
   Serial.print("Serial value received is "); Serial.println(a);
   switch(a){
      case 1:
         Serial.println("Value 1 received");
         break;

      case 2:
         Serial.println("Value 2 received");
         break;

      case 3:
         Serial.println("Value 3 received");
         break;

      default:
         Serial.println("Value outside 1,2,3 received");
         break;
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}
As you can see, we take one integer from the user (Serial.parseInt()), and print different values depending on the value of the input.
The Serial Monitor Output is shown below −
Average of each n-length consecutive segment in a Python list

We have a list containing only numbers. We plan to get the average of a set of sequential numbers from the list which keeps rolling from the first number to next number and then to next number and so on.
The below example simplifies the requirement of finding the average of each 4-length consecutive elements of the list.
Given list:
[10,12,14,16,18,20,22,24,26]

Average of every segment of 4 consecutive numbers:

[13.0, 15.0, 17.0, 19.0, 21.0, 23.0]
We use the list comprehension approach to take the sum of the consecutive numbers by applying range to keep track of how many numbers we gathered. Then we keep dividing the sum with the segment length with the help of a loop. Finally the result is gathered into a new list.
 Live Demo
listA = [10,12,14,16,18,20,22,24,26]
print("Given list:\n",listA)
seg = 4
# List comprehension
res = [sum(listA[m:m + seg])/seg
      for m in range(len(listA) - seg + 1)]
print("new list with averages:\n ",res)
Running the above code gives us the following result −
Given list:
   [10, 12, 14, 16, 18, 20, 22, 24, 26]
new list with averages:
   [13.0, 15.0, 17.0, 19.0, 21.0, 23.0]
In this approach we take help of python modules which can calculate these values in a more direct way. We keep slicing the elements of the list in the given range using the isslice function and then apply the mean function directly on the new list to get the final result.
 Live Demo
from statistics import mean
from itertools import islice

listA = [10,12,14,16,18,20,22,24,26]
print("Given list:\n",listA)

# With islice and mean
listB = zip(*(islice(listA, i, None) for i in range(4)))
res = list(map(mean, listB))

print("new list with averages:\n ",res)
Running the above code gives us the following result −
Given list:
   [10, 12, 14, 16, 18, 20, 22, 24, 26]
new list with averages:
   [13, 15, 17, 19, 21, 23]
How to remove the key-value pairs corresponding to the given keys from an object using JavaScript ?

22 Jul, 2021
In JavaScript objects store data in the form of key-value pairs where the key may be any property of the object. In this article let us see how to remove key-value pairs corresponding to a given key in the object.
Using delete operator. When only a single key is to be removed we can directly use the delete operator specifying the key in an object. 
Syntax:
 
delete(object_name.key_name);
/* or */
delete(object_name[key_name]);
 
Example:
 
HTML
<script>      var myObj = {        Name: "Raghav",        Age: 30,        Sex: "Male",        Work: "Web Developer",        YearsOfExperience: 6,        Organisation: "GeeksforGeeks",        Address: "address--address some value"      };        console.log("After removal: ");      // Deleting address key      delete (myObj.Address); // Or delete(myObj[Address]);      console.log(myObj);</script>    
Output:
"After removal: "
[object Object] {
  Age: 30,
  Name: "Raghav",
  Organisation: "GeeksforGeeks",
  Sex: "Male",
  Work: "Web Developer",
  YearsOfExperience: 6
}
When multiple keys are to be removed then the keys can be stored in an array and can be passed to a function that uses a loop to delete the required keys in the array. 
Syntax:
 
function function_name(object_name, array_of_keys) {
    { Iterate through the array using loop. }
    return object_name;
}
 
Example 2:
 
HTML
<script>    // Function to delete the keys given in the array    function DeleteKeys(myObj, array) {      for (let index = 0; index < array.length; index++) {          delete myObj[array[index]];      }      return myObj;    }      // Declaring the object    var myObj = {      Name: "Raghav",      Age: 30,      Sex: "Male",      Work: "Web Developer",      YearsOfExperience: 6,      Organisation: "Geeks For Geeks",      Address: "address--address some value"    };      // Adding the keys to be deleted in the array    var array =     ["Work", "Address", "Organisation", "YearsOfExperience"];    var finalobj = DeleteKeys(myObj, array);    console.log("After removal: ");    console.log(finalobj);</script>
Output:
"After removal: "
[object Object] {
  Age: 30,
  Name: "Raghav",
  Sex: "Male"
}
saurabh1990aror
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.