code-rag-bench/online-tutorials huggingface dataset:
How to assign a column value in a data frame based on another column in another R data frame?

To assign a column value based on another column, we can use ifelse function. The ifelse function checks whether the value in one column of one data frame matches the value in another column of another data frame by using equal sign (==) and then replace the original value with the new column if there is no match else returns the original value. Check out the below example to understand how it can be done.
Consider the below data frame −
Live Demo
> x1<-rpois(20,2)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1
  x1 x2
1  3  5
2  3  7
3  0  6
4  0  5
5  4  6
6  3  8
7  1  5
8  0  8
9  4  6
10 1  2
11 2  3
12 2  6
13 0  0
14 1  9
15 0  0
16 4  2
17 3  5
18 3  8
19 1  3
20 2  7
Live Demo
> y1<-rpois(20,2)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2
  y1  y2
1  3  8
2  4  11
3  3  8
4  2  2
5  1  3
6  1  4
7  1  7
8  1  2
9  5  2
10 2  4
11 2  3
12 1  3
13 1  5
14 3  4
15 0  3
16 2  5
17 3  5
18 1  7
19 5  10
20 2  6
Replacing values in x1 of df1, if x2 of df1 is same as y2 of df2 otherwise returning x1 in df1 −
> df1$x1<-ifelse(df1$x2==df2$y2,df2$y2,df1$x1)
> df1
   x1 x2
1  3  5
2  3  7
3  0  6
4  0  5
5  4  6
6  3  8
7  1  5
8  0  8
9  4  6
10 1  2
11 3  3
12 2  6
13 0  0
14 1  9
15 0  0
16 4  2
17 5  5
18 3  8
19 1  3
20 2  7
while loop in C

A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in C programming language is −
while(condition) {
   statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 10;

   /* while loop execution */
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 Print
 Add Notes
 Bookmark this page
Java Program to add Period to LocalDate

Let us first set a Period with month and days:
Period p = Period.ofMonths(5).plusDays(15);
Now set the LocalDate:
LocalDate date = LocalDate.of(2019, 4, 10);
Add period to LocalDate:
LocalDate res = date.plus(p);
import java.time.LocalDate;
import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      Period p = Period.ofMonths(5).plusDays(15);
      LocalDate date = LocalDate.of(2019, 4, 10);
      System.out.println("Date = "+date);
      LocalDate res = date.plus(p);
      System.out.println("Updated date = "+res);
   }
}
Date = 2019-04-10
Updated date = 2019-09-25
How do I replace “+”(plus sign) with SPACE in MySQL?

To replace, use REPLACE() function from MySQL. Let us first create a table −
mysql> create table DemoTable
(
   Number varchar(100)
);
Query OK, 0 rows affected (0.86 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('+916578675547');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('+918976676564');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('+919800087678');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------+
| Number        |
+---------------+
| +916578675547 |
| +918976676564 |
| +919800087678 |
+---------------+
3 rows in set (0.00 sec)
Following is the query to replace “+”(plus sign) with SPACE −
mysql> update DemoTable set Number=replace(Number, '+', ' ');
Query OK, 3 rows affected (0.12 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable
This will produce the following output −
+---------------+
| Number        |
+---------------+
| 916578675547 |
| 918976676564 |
| 919800087678 |
+---------------+
3 rows in set (0.00 sec)
LocalDate ofInstant() method in Java with Examples - GeeksforGeeks

17 May, 2020
The ofInstant(Instant instant, ZoneId zone) method of LocalDate class in Java is used to create an instance of LocalDate from an Instant and zone ID. These two parameters are passed to the method and on the basis of those, an instance of LocalDate is created. The calculation of the LocalDate follows the following step.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.Finally, the local date is calculated using the instant and the obtained offset.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.
Finally, the local date is calculated using the instant and the obtained offset.
Syntax:
public static LocalDate 
       ofInstant(Instant instant,
                 ZoneId zone)

Parameters: This method accepts two parameters:
instant: It is of Instant type and represents the instant passed to create the date.
zone: It is of ZoneId type and represent the offset.
Return Value: This method returns the localdate.
Exceptions: This method throws DateTimeException if the result exceeds the supported range.
Note: This method is included in LocalDate class in the latest version of Java only, therefore it might not run in few of the online compilers.
Below programs illustrate the ofInstant(Instant instant, ZoneId zone) method in Java:Program 1:
// Java program to demonstrate// LocalDate.ofInstant(// Instant instant, ZoneId zone) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // Create LocalDate object        LocalDate localdate            = LocalDate.ofInstant(                Instant.now(),                ZoneId.systemDefault());          // Print full date        System.out.println("Date: "                           + localdate);    }}
Date: 2020-05-13

Program 2:
// Java program to demonstrate// LocalDate ofInstant() method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // Create LocalDate object        LocalDate localdate            = LocalDate.ofInstant(                Instant.now(),                ZoneId.systemDefault());          // Print year only        System.out.println(            "Year: "            + localdate.getYear());    }}
Year: 2020

References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#ofInstant(java.time.Instant, java.time.ZoneId)
Java-Functions
Java-LocalDate
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
How to use threading in PyQt5?

24 Feb, 2021
Prerequisite: PyQt5 and multithreading
Multithreading refers to concurrently executing multiple threads by rapidly switching the control of the CPU between threads (called context switching). The Python Global Interpreter Lock limits one thread to run at a time even if the machine contains multiple processors.​
In this article, we will learn, how to use threading in Pyqt5. While Creating a GUI there will be a need to do multiple work/operations at the backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During the execution of one operation, the GUI window will also not move and this is why we need threading. Both implementations are given below which obviously will help understand their differences better.
Approach
Import libraries required
Create a simple Window
Add Button with command
Execute Pyqt5
Without Threading
Working without threads, makes the process delayed. Also, the window will not move until full execution takes place.
Python3
# Import Moduleimport sysfrom PyQt5.QtWidgets import *import time  class ListBox(QWidget):      def __init__(self):        super().__init__()          self.Button()      def Button(self):        # Add Push Button        clear_btn = QPushButton('Click Me', self)        clear_btn.clicked.connect(self.Operation)          # Set geometry        self.setGeometry(200, 200, 200, 200)          # Display QlistWidget        self.show()      def Operation(self):        print("time start")        time.sleep(10)        print("time stop")    if __name__ == '__main__':    app = QApplication(sys.argv)          # Call ListBox Class    ex = ListBox()      # Close the window    sys.exit(app.exec_())
Output:
With Threading
Whenever we click on the “Click Me” Button, it will call the thread() method. Inside the thread method, we are creating a Thread Object where we define our function name.
Python3
# Import Moduleimport sysfrom PyQt5.QtWidgets import *import timefrom threading import *  class ListBox(QWidget):      def __init__(self):        super().__init__()          self.Button()      def Button(self):        # Add Push Button        clear_btn = QPushButton('Click Me', self)        clear_btn.clicked.connect(self.thread)          # Set geometry        self.setGeometry(200, 200, 200, 200)          # Display QlistWidget        self.show()      def thread(self):        t1=Thread(target=self.Operation)        t1.start()      def Operation(self):        print("time start")        time.sleep(10)        print("time stop")    if __name__ == '__main__':    app = QApplication(sys.argv)          # Call ListBox Class    ex = ListBox()      # Close the window    sys.exit(app.exec_())
Output:
Picked
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inline function in C

03 Dec, 2018
Inline Function are those function whose definitions are small and be substituted at the place where its function call is happened. Function substitution is totally compiler choice.
Let’s take below example:
#include <stdio.h>  // Inline function in Cinline int foo(){    return 2;}  // Driver codeint main(){      int ret;      // inline function call    ret = foo();      printf("Output is: %d\n", ret);    return 0;}
Compiler Error:
In function `main':
undefined reference to `foo'

Why this error happened?
This is one of the side effect of GCC the way it handle inline function. When compiled, GCC performs inline substitution as the part of optimisation. So there is no function call present (foo) inside main. Please check below assembly code which compiler will generate.
Normally GCC’s file scope is “not extern linkage”. That means inline function is never ever provided to the linker which is causing linker error, mentioned above.
How to remove this error?
To resolve this problem use “static” before inline. Using static keyword forces the compiler to consider this inline function in the linker, and hence the program compiles and run successfully.
Example:
#include <stdio.h>  // Inline function in Cstatic inline int foo(){    return 2;}  // Driver codeint main(){      int ret;      // inline function call    ret = foo();      printf("Output is: %d\n", ret);    return 0;}
Output is: 2

C Basics
C-Functions
Technical Scripter 2018
C Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tensorflow tf.sub() Function

07 Jun, 2022
The tf.sub() function returns the subtraction of two tf.Tensor objects element wise. The tf.Tensor object represents the multidimensional array of numbers.
Syntax:
tf.sub( a, b )
Parameters:
a: It contains the first tf.Tensor object. The value of this parameter can be tf.TensorTypedArray|Array.
b: It contains the second tf.Tensor object that subtract from first tf.Tensor object. The value of this parameter can be (tf.Tensor|TypedArray|Array). The type of this parameter is same as type of a.
Return Value: This function returns the tf.Tensor object.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr1 = tf.tensor1d([10, 20, 30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use sub() function to subtract// two Tensor objectsarr1.sub(arr2).print();
Output:
Tensor
    [5, 10, 15, 20, 25]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr1 = tf.tensor1d([30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use sub() function to subtract// two Tensor objectsarr1.sub(arr2).print();
Output:
An error occurred on line: 7
Operands could not be broadcast together with shapes 3 and 5.
Example 3:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr = tf.tensor1d([15, 10, 25, 20, 35]); // Declare a numberconst num = tf.scalar(30); // Use sub() function to subtract number// from Tensor objectarr.sub(num).print();
Output: 
Tensor
    [-15, -20, -5, -10, 5]
Reference: https://js.tensorflow.org/api/latest/#sub
nikhatkhan11
Tensorflow
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to prevent MongoDB from returning the object ID while finding a document?

To prevent MongoDB from returning the Object ID while finding a document, you need to set _id
to 0. Let us first create a collection with documents
> db.preventObjectIdDemo.insertOne(
...    {
...
...       "StudentName" : "Chris",
...       "StudentDetails" : [
...          {
...             "StudentTotalScore" : 540,
...             "StudentCountryName" : "US"
...          },
...          {
...             "StudentTotalScore" : 489,
...             "StudentCountryName" : "UK"
...          }
...       ]
...    }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
}
Following is the query to display all documents from a collection with the help of find() method
> db.preventObjectIdDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      },
      {
         "StudentTotalScore" : 489,
         "StudentCountryName" : "UK"
      }
   ]
}
Following is the query to prevent MongoDB from returning the Object ID when finding a
document
> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();
The following is the output where ObjectID isn’t visible
{
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      }
   ]
}
TensorFlow - TensorBoard Visualization

TensorFlow includes a visualization tool, which is called the TensorBoard. It is used for analyzing Data Flow Graph and also used to understand machine-learning models. The important feature of TensorBoard includes a view of different types of statistics about the parameters and details of any graph in vertical alignment.
Deep neural network includes up to 36,000 nodes. TensorBoard helps in collapsing these nodes in high-level blocks and highlighting the identical structures. This allows better analysis of graph focusing on the primary sections of the computation graph. The TensorBoard visualization is said to be very interactive where a user can pan, zoom and expand the nodes to display the details.
The following schematic diagram representation shows the complete working of TensorBoard visualization −
The algorithms collapse nodes into high-level blocks and highlight the specific groups with identical structures, which separate high-degree nodes. The TensorBoard thus created is useful and is treated equally important for tuning a machine learning model. This visualization tool is designed for the configuration log file with summary information and details that need to be displayed.
Let us focus on the demo example of TensorBoard visualization with the help of the following code −
import tensorflow as tf 

# Constants creation for TensorBoard visualization 
a = tf.constant(10,name = "a") 
b = tf.constant(90,name = "b") 
y = tf.Variable(a+b*2,name = 'y') 
model = tf.initialize_all_variables() #Creation of model 

with tf.Session() as session: 
   merged = tf.merge_all_summaries() 
   writer = tf.train.SummaryWriter("/tmp/tensorflowlogs",session.graph) 
   session.run(model) 
   print(session.run(y))
The following table shows the various symbols of TensorBoard visualization used for the node representation −

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    29 Lectures 
     3.5 hours 

 Mohammad Nauman

    82 Lectures 
     4 hours 

 Anis Koubaa
 Print
 Add Notes
 Bookmark this page
Pascal - Packed Array

These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more).
Normally, characters and Boolean values are stored in such a way that each character or truth value uses one storage unit like a word. This is called unpacked mode of data storage. Storage is fully utilized if characters are stored in consecutive bytes. This is called packed mode of data storage. Pascal allows the array data to be stored in packed mode.
Packed arrays are declared using the keywords packed array instead of array. For example −
type
   pArray: packed array[index-type1, index-type2, ...] of element-type;
var
   a: pArray;
The following example declares and uses a two-dimensional packed array −
program packedarray; 
var
   a: packed array [0..3, 0..3] of integer;
   i, j : integer;  

begin  
   for i:=0 to 3 do  
      for j:=0 to 3 do  
         a[i,j]:= i * j;  
   
   for i:=0 to 3 do  
   begin  
      for j:=0 to 3 do  
         write(a[i,j]:2,' ');  
      writeln;  
   end;  
end.
When the above code is compiled and executed, it produces the following result −
0 0 0 0
0 1 2 3
0 2 4 6
0 3 6 9


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to align the bars of a barplot with the X-axis using ggplot2 in R?

The bar plot is created with geom_bar function but there always exist some space between the bars and the X-axis labels. If we want to reduce that space or completely remove it we need to use scale_y_continuous function by defining expand argument for former and scale_y_continuous(expand=c(0,0)) for latter.
 Live Demo
Consider the below data frame −
set.seed(888)
x<-c("S1","S2","S3","S4")
y<-c(24,27,25,28)
df<-data.frame(x,y)
df
   x y
1 S1 24
2 S2 27
3 S3 25
4 S4 28
Loading ggplot2 package and creating bar plot of y −
library(ggplot2)
ggplot(df,aes(x,y))+geom_bar(stat="identity")
Creating the bar plot without space between X-axis labels and the bars −
ggplot(df,aes(x,y))+geom_bar(stat="identity")+scale_y_continuous(expand=c(0,0))
Heap overflow and Stack overflow in C

Heap is used to store dynamic variables. It is a region of process’s memory. malloc(), calloc(), resize() all these inbuilt functions are generally used to store dynamic variables.
Heap overflow occurs when −
A) If we allocate dynamic large number of variables −
int main() {
   float *ptr = (int *)malloc(sizeof(float)*1000000.0));
}
B) If we continuously allocate memory and do not free after using it.
int main() {
   for (int i=0; i<100000000000; i++) {
      int *p = (int *)malloc(sizeof(int));
   }
}
Stack is a Last in First out data structure. It is used to store local variables which is used inside the function. Parameters are passed through this function and their return addresses.
If a program consumes more memory space, then stack overflow will occur as stack size is limited in computer memory.
Stack overflow occurs when −
C) If a function is called recursively by itself infinite times then stack will be unable to store large number of local variables, so stack overflow will occur −
void calculate(int a) {
   if (a== 0)
      return;
      a = 6;
      calculate(a);
}
int main() {
   int a = 5;
   calculate(a);
}
D) If we declare a large number of local variables or declare a large dimensional array or matrix can result stack overflow.
int main() {
   A[20000][20000]
}
GATE-CS-2009 - GeeksforGeeks

22 Nov, 2021
What is the chromatic number of an n-vertex simple connected graph which does not contain any odd length cycle? Assume n >= 2. 
n-1 
3 
2 
n 
The chromatic number of a graph is the smallest number of colours needed to colour the vertices of so that no two adjacent vertices share the same colour. These types of questions can be solved by substitution with different values of n. 1) n = 2  
This simple graph can be coloured with 2 colours. 2) n = 3  
Here, in this graph let us suppose vertex A is coloured with C1 and vertices B, C can be coloured with colour C2 => chromatic number is 2 In the same way, you can check with other values, Chromatic number is equals to 2 A simple graph with no odd cycles is bipartite graph and a Bipartite graph can be colored using 2 colors 
A page table entry must contain Page frame number. Virtual page number is typically used as index in page table to get the corresponding page frame number. See this for details.
   1. Find the minimum value in the list
   2. Swap it with the value in the first position
   3. Repeat the steps above for the remainder of the list (starting at
      the second position and advancing each time)
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
D3.js group() Method

23 Sep, 2020
With the help of d3.group() method, we can group the iterable data structure into a map where the key is defined as the element from iterable and values as an array.
Syntax:
d3.group( iterable, ...keys )
Return value: It returns the map having key as element and value as an array.
Note: To execute the below examples you have to install the d3 library by using this command prompt we have to execute the following command.
npm install d3
Example 1: In this example, we can see that by using the d3.group() method. We are able to get the map from the group iterable where the key is an element and the value as an array.
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC", amount: "34.0",   date: "11/12/2015"},  {name: "DEF", amount: "120.11", date: "11/12/2015"},  {name: "MNO", amount: "12.01",  date: "01/04/2016"},  {name: "XYZ", amount: "34.05",  date: "01/04/2016"}]  var grouped_data = d3.group(data, d => d.name)  console.log(grouped_data)
Output:
Map {‘ABC’ => [ { name: ‘ABC’, amount: ‘34.0’, date: ’11/12/2015′ } ],‘DEF’ => [ { name: ‘DEF’, amount: ‘120.11’, date: ’11/12/2015′ } ],‘MNO’ => [ { name: ‘MNO’, amount: ‘12.01’, date: ’01/04/2016′ } ],‘XYZ’ => [ { name: ‘XYZ’, amount: ‘34.05’, date: ’01/04/2016′ } ]}
Example 2:
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC", amount: "34.0",   date: "11/12/2015"},  {name: "DEF", amount: "120.11", date: "11/12/2015"},  {name: "MNO", amount: "12.01",  date: "01/04/2016"},  {name: "XYZ", amount: "34.05",  date: "01/04/2016"}]  var grouped_data = d3.group(data,         d => d.name, d => d.amount)  console.log(grouped_data)
Output:
Map {
  'ABC' => Map { '34.0' => [ [Object] ] },
  'DEF' => Map { '120.11' => [ [Object] ] },
  'MNO' => Map { '12.01' => [ [Object] ] },
  'XYZ' => Map { '34.05' => [ [Object] ] } 
}

D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
replace() in Python to replace a substring

23 Nov, 2020
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str.
Examples:
Input  : str = "helloABworld"
Output : str = "helloCworld"

Input  : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"

This problem has existing solution please refer Replace all occurrences of string AB with C without using extra space link. We solve this problem in python quickly using replace() method of string data type.
How does replace() function works ?str.replace(pattern,replaceWith,maxCount) takes minimum two parameters and replaces all occurrences of pattern with specified sub-string replaceWith. Third parameter maxCount is optional, if we do not pass this parameter then replace function will do it for all occurrences of pattern otherwise it will replace only maxCount times occurrences of pattern.
# Function to replace all occurrences of AB with C  def replaceABwithC(input, pattern, replaceWith):    return input.replace(pattern, replaceWith)  # Driver programif __name__ == "__main__":    input   = 'helloABworld'    pattern = 'AB'    replaceWith = 'C'    print (replaceABwithC(input,pattern,replaceWith))
Output:
'helloCworld'

vaibhav2992
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
C library function - strxfrm()

The C library function size_t strxfrm(char *dest, const char *src, size_t n) transforms the first n characters of the string src into current locale and place them in the string dest.
Following is the declaration for strxfrm() function.
size_t strxfrm(char *dest, const char *src, size_t n)
dest − This is the pointer to the destination array where the content is to be copied. It can be a null pointer if the argument for n is zero.
dest − This is the pointer to the destination array where the content is to be copied. It can be a null pointer if the argument for n is zero.
src − This is the C string to be transformed into current locale.
src − This is the C string to be transformed into current locale.
n − The maximum number of characters to be copied to str1.
n − The maximum number of characters to be copied to str1.
This function returns the length of the transformed string, not including the terminating null-character.
The following example shows the usage of strxfrm() function.
#include <stdio.h>
#include <string.h>

int main () {
   char dest[20];
   char src[20];
   int len;

   strcpy(src, "Tutorials Point");
   len = strxfrm(dest, src, 20);

   printf("Length of string |%s| is: |%d|", dest, len);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Length of string |Tutorials Point| is: |15|


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Java Math asin() method with Example - GeeksforGeeks

06 Apr, 2018
The java.lang.Math.asin() returns the arc sine of an angle in between -pi/2 and pi/2. Arc sine is also called as an inverse of a sine.
If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
If the argument is zero, then the result is a zero with the same sign as the argument.
Syntax :
public static double asin(double angle)
Parameter :
angle : the value whose arc sine is to be returned.

Return :This method returns the arc sine of the argument.
Example 1 : To show working of java.lang.Math.asin() method.
// Java program to demonstrate working// of java.lang.Math.asin() methodimport java.lang.Math; class Gfg {     // driver code    public static void main(String args[])    {        double a = Math.PI;         // Output is NaN, because Math.PI gives 3.141 value        // greater than 1        System.out.println(Math.asin(a));         // convert Math.PI to radians        double b = Math.toRadians(a);         System.out.println(Math.asin(b));         double c = 1.0;        System.out.println(Math.asin(c));         double d = 0.0;        System.out.println(Math.asin(d));         double e = -1.0;        System.out.println(Math.asin(e));         double f = 1.5;         // value of f does not lie in between -1 and 1        // so output is NaN        System.out.println(Math.asin(f));    }}
Output:
NaN
0.054858647341251204
1.5707963267948966
0.0
-1.5707963267948966
NaN

Java-lang package
Java-Library
java-math
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Multidimensional Arrays in Java
Set in Java
BigInteger Multiply | Practice | GeeksforGeeks

Given two BigIntegers X and Y. You have to multiply X and Y.
 
Example 1:
Input:
X = 3, Y = 4
Output:
12
Explanation:
Multiplication of X and Y is 12

 
Example 2:
Input:
X = 8, Y = 2 
Output:
16
Explanation:
Multiplication of X and Y is 16.
 
Your Task:
Your task is to complete the function mul() which accepts x and y as input parameters and returns their multiplication.
 
Constraints:
1 <= X, Y, <= 1030
0
dell94593 weeks ago
Java:class MathematicalOperation{      static BigInteger mul(BigInteger x, BigInteger y){          // Your code here       return x.multiply(y);   }   }
+1
badgujarsachin834 months ago
 static BigInteger mul(BigInteger x, BigInteger y){
    
        // Your code here
        return x.multiply(y);
             
    }
    
0
gautam2002pandeyjee6 months ago
Remember not use operator here because this is not an integer ..
This is a BigInteger..
So you can not use operator here ..
 
 
0
gaurav27919977 months ago
return x.multiply(y);
0
Achintya Veer Singh9 months ago
Achintya Veer Singh
Eeez:
static BigInteger mul(BigInteger x, BigInteger y){        return x.multiply(y);    }
0
martial9 months ago
martial
https://uploads.disquscdn.c... https://uploads.disquscdn.c...
0
Sukanya Sinha1 year ago
Sukanya Sinha
return x.multiply(y);
-1
Tulsi Dey1 year ago
Tulsi Dey
Solution in Java:Execution time : 0.17
class MathematicalOperation{        static BigInteger mul(BigInteger x, BigInteger y){            return x.multiply(y);    }}
0
Lakshya Khandelwal2 years ago
Lakshya Khandelwal
add cpp to pls
0
jyoti2 years ago
jyoti
https://github.com/jYOTIHAR...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
ReactJS – componentWillUpdate() Method

In this article, we are going to see how to execute a function before the component is updated in the DOM tree.
This method is used during the updating phase of the React lifecycle. This function is generally called before the component is updated or when the state or props passed to the component changes. Don’t call setState() method in this function. This method will not be invoked if shouldComponentUpdate() methods return false.
Note: This method is now deprecated.
UNSAFE_componentWillUpdate(nextProps, nextState)
In this example, we will build a color changing React application which calls the componentWillUpdate method when the component is updated in the DOM tree.
Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.
App.jsx
import React from 'react';

class App extends React.Component {
   state = { color: 'green' };
   render() {
      setTimeout(() => {
         this.setState({ color: 'wheat' });
      }, 4000);
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <ChangeName color={this.state.color} />
         </div>
      );
   }
}
class ChangeName extends React.Component {
   UNSAFE_componentWillUpdate(nextProps, nextState) {
      console.log('Component will be updated soon');
   }
   render() {
      console.log('ChangeName component is called');
      return (
         <div>
            <h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
This will produce the following result.
Matplotlib.figure.Figure.set_figheight() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_figheight() method figure module of matplotlib library is used to set the height of the figure in inches.
Syntax: set_figheight(self, val, forward=True)
Parameters: This method accept the following parameters that are discussed below:
val : This parameter is the float value.
forward : This parameter contains the boolean value.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_figheight() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np         fig = plt.figure()        ax = Subplot(fig, 111) fig.add_subplot(ax)    fig.set_figheight(7.6)     fig.suptitle("""matplotlib.figure.Figure.set_figheight()function Example\n\n""", fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np           fig = plt.figure(figsize =(7, 6))         ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])      xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))     fig.set_figheight(4.8)     fig.suptitle("""matplotlib.figure.Figure.set_figheight()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
BCD to binary conversion in 8051

In this problem, we will see how to convert 8-bit BCD number to its Binary (Hexadecimal)equivalent. The BCD number is stored at location 20H. After converting, the results will be stored at 30H.
So let us assume the data is D5H. The program converts the binary value ofD5H to BCD value 213D.
   MOVR0,#20H; Initialize the address of the data
   MOVA,@R0;Get the data from an address, which is stored in R0
   MOVR2,A; Store the content of A into R2
   
   CLRA;Clear the content of A to 00H
   MOVR3,#00H
LOOP:   ADDA,#01H;increment A by 01H
   DAA; Decimal Adjust of the accumulator content
   INCR3; Increase R3 to keep track of the hex value
   CJNEA,02H,LOOP ;Run the loop until A = R2

MOVR0,#30H; Point the destination location
MOVA,R3; Move R3 to A
MOV@R0,A; Store A content to the memory location pointed by R0
HALT:   SJMPHALT
Here the logic is very simple. We are just taking the number from the memory. And storing that value into R2. By this value, we can compare while executing the loop.
The accumulator (A) and register R3 is set to 00H at first. So we are just increasing the value of A by 01H. We can use the INC A instruction to increment the value, but in this case, the value is incremented by using ADDA, #01H. The reason behind it is the INCinstruction does not affect the CY and AC flags. But these flags are needed to use DA A instruction for decimal adjusting. After increasing the value of A, DA A instruction is executed to convert the value to decimal. By using this decimal value, we can compare with the number stored inR2. In each iteration the value of R3 is incremented by 1, this is acting like a counter. So at the end, we are getting the output from register R3.
We can do the same thing using some other logic also. Here no additional loops are needed to do the task. We are just multiplying the digit of 10th place of the BCD number with 0AH. Then adding the second digit with the result to get the number. 
If the number is 94, then it is multiplying 0AH with 9.
(9 * 0AH) = 5AH, thenadding 4 with 5AH. (5AH + 4) = 5EH.
MOVR0,#20H; Initialize the address of the data
MOVA,@R0; Get the data from an address, which is stored in R0
MOVR2,A;Store the content of A into R2
SWAPA; Swap the nibbles of A register
ANLA,#0FH;Mask the Higher Nibble of A
MOVB,0AH;Take 0AH = 10D into B
MULAB ;Multiply A with B, and get result into A
MOVA,R2;Copy R2 content to A
ANLA,#0FH;Mask the higher nibble of A
ADDA,R2
MOVR0,#30H;Point the destination location
MOVA,R3;Move R3 to A
MOV@R0,A;Store A content to memory location pointed by R0
HALT:   SJMPHALT
std::bad_array_new_length class in C++ with Examples

28 May, 2020
Standard C++ contains several built-in exception classes, std::bad_array_new_length is one of them.It is an exception on bad array length and thrown if the size of array is less than zero and if the array size is greater than the limit. Below is the syntax for the same:
Header File:
<new>

Syntax:
class bad_array_new_length;

Return: The std::bad_array_new returns a null terminated character that is used to identify the exception.
Note: To make use of std::bad_array_new, one should set up the appropriate try and catch blocks.
Below are the Programs to understand the implementation of std::bad_array_new in a better way:
Program 1:
// C++ code for std::bad_array_new_length#include <bits/stdc++.h>  using namespace std;  // main methodint main(){    int a = -1;    int b = 1;    int c = INT_MAX;      // try block    try {        new int[a];        new int[b]{            1,            2,            3,            4        };        new int[50000000];    }      // catch block to handle the errors    catch (const bad_array_new_length& gfg) {        cout << gfg.what() << endl;    }      return 0;}
std::bad_array_new_length

Program 2:
// C++ code for std::bad_array_new_length#include <bits/stdc++.h>  using namespace std;  // main methodint main(){    int a = -1;    int b = 1;    int c = INT_MAX;      // try block    try {        new int[a];        new int[b]{            11,            25,            56,            27        };        new int[1000000];    }      // catch block to handle the errors    catch (const bad_array_new_length& gfg) {        cout << gfg.what() << endl;    }    return 0;}
std::bad_array_new_length

Reference: http://www.cplusplus.com/reference/new/bad_array_new_length/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find tuples which have all elements divisible by K from a list of tuples

05 Sep, 2020
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K.
Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6.
Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)] Explanation : Multiple of 5 tuples extracted. 
Method #1 : Using list comprehension + all()
In this, we test for all elements to be K multiple using all() for filtering purpose, and list comprehension is used for iteration of all tuples.
Python3
# Python3 code to demonstrate working of# K Multiple Elements Tuples# Using list comprehension + all()  # initializing listtest_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]  # printing original listprint("The original list is : " + str(test_list))  # initializing KK = 6  # all() used to filter elementsres = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]  # printing resultprint("K Multiple elements tuples : " + str(res))
The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

 Method #2 : Using filter() + lambda + all()
In this, we perform task of filtering using filter() + lambda, and logic provided by all(), as in above method.
Python3
# Python3 code to demonstrate working of# K Multiple Elements Tuples# Using filter() + lambda + all()  # initializing listtest_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]  # printing original listprint("The original list is : " + str(test_list))  # initializing KK = 6  # filter() + lambda for filter operationres = list(filter(lambda sub: all(ele % K == 0 for ele in sub), test_list))  # printing resultprint("K Multiple elements tuples : " + str(res))
The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

Python List-of-Tuples
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Kali Linux - Reporting Tools

In this chapter, we will learn about some reporting tools in Kali Linux.
In all this work that we have performed, it is important to share the results that was produced, to track our work, etc. For this purpose, Kali has a reporting tool called dradis which is a web service.
Step 1 − To start Dradis, type “service dradis start”.
Step 2 − To open, go to Applications → Reporting Tools → dradis.
The web URL will open. Anybody in LAN can open it in the following URL https://IP of kali machine:3004
Log in with the username and password that was used for the first time.
Step 3 − After logging in, you can import files from NMAP, NESSUS, NEXPOSE. To do so, go to “Import from file” → click “new importer(with real-time feedback)”.
Step 4 − Select the file type that you want to upload. In this case, it is “Nessus scan” → click “Browse”.
If you go to the home page now, on the left panel you will see that the imported scans have are in a folder with their host and port details.
Metagoofil performs a search in Google to identify and download the documents to the local disk and then extracts the metadata. It extracts metadata of public documents belonging to a specific company, individual, object, etc.
To open it, go to: “usr/share/metagoofil/”.
To start searching, type the following command −
python metagoofil.py 

You can use the following parameters with this command −
–d (domain name)
–d (domain name)
–t (filetype to download  dox,pdf,etc)
–t (filetype to download  dox,pdf,etc)
–l (limit the results  10, 100 )
–l (limit the results  10, 100 )
–n (limit files to download)
–n (limit files to download)
–o ( location to save the files) 
–o ( location to save the files) 
–f (output file)
–f (output file)
The following example shows only the domain name is hidden.

    84 Lectures 
     6.5 hours 

 Mohamad Mahjoub

    8 Lectures 
     1 hours 

 Corey Charles

    21 Lectures 
     4 hours 

 Atul Tiwari

    55 Lectures 
     3 hours 

 Musab Zayadneh

    29 Lectures 
     2 hours 

 Musab Zayadneh

    32 Lectures 
     4 hours 

 Adnaan Arbaaz Ahmed
 Print
 Add Notes
 Bookmark this page
Perl | Reverse an array - GeeksforGeeks

23 Sep, 2018
Reverse an array or string in Perl.
Iterative Way:Iterate over the array from 0 to mid of array.Swap the arr[i] element with arr[size-i] element.
#Perl code to reverse an array iteratively  #declaring an array of integers@arr = (2, 3, 4, 5, 6, 7);  # Store length on array in $n variable$n = $#arr;  #Print the original arrayprint "The original array is : ";for $i (0 .. $#arr){    print $arr[$i], " ";}  #run a loop from 0 to mid of arrayfor my $i (0 .. $#arr/2){    #swap the current element with size-current element    $tmp = $arr[$i];    $arr[$i] = $arr[$n-$i];    $arr[$n-$i] = $tmp;}  #Print the reversed arrayprint "\nThe reversed array is : ";for $i (0 .. $#arr){    print $arr[$i], " ";}
The original array is : 2 3 4 5 6 7 
The reversed array is : 7 6 5 4 3 2

Using Inbuilt Function:Perl has an inbuilt function to reverse an array or a string or a number.
#Perl code to reverse an array using inbuilt function reverse  #declaring an array of integers@arr = (2, 3, 4, 5, 6, 7);  #Print the original arrayprint "The original array is : ";for $i (0 .. $#arr){    print $arr[$i], " ";}  #store the reversed array in @rev_arr@rev_arr = reverse(@arr);  #Print the reversed arrayprint "\nThe reversed array is : ";for $i (0 .. $#rev_arr){    print $rev_arr[$i], " ";}
The original array is : 2 3 4 5 6 7 
The reversed array is : 7 6 5 4 3 2

Perl-String
Picked
Reverse
Perl
Reverse
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Writing to a File
Perl Tutorial - Learn Perl With Examples
Perl | Multidimensional Hashes
Perl | File Handling Introduction
Perl | Reading Excel Files
Perl | Special Character Classes in Regular Expressions
Perl | shift() Function
Perl | Date and Time
Perl | index() Function
Perl | Appending to a File
Batch Script - Creating Files

The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command.
@echo off
echo "Hello">C:\new.txt
If the file new.txt is not present in C:\, then it will be created with the help of the above command.
 Print
 Add Notes
 Bookmark this page