code-rag-bench/online-tutorials huggingface dataset:
rename function in C/C++

17 Nov, 2017
rename() function is used to change the name of the file or directory i.e. from old_name to new_name without changing the content present in the file. This function takes name of the file as its argument.If new_name is the name of an existing file in the same folder then the function may either fail or override the existing file, depending on the specific system and library implementation.Syntax:
int rename (const char *old_name, const char *new_name);

Parameters:
old_name : Name of an existing file to be renamed.
new_name : String containing new name of the file.

Return:Return type of function is an integer. If the file is renamed successfully, zero is returned. On failure, a nonzero value is returned.
Assume that we have a text file having name geeks.txt, having some content. So, we are going to rename this file, using the below C program present in the same folder where this file is present.
// C program to demonstrate use of rename()#include<stdio.h>  int main(){    // Old file name    char old_name[] = "geeks.txt";      // Any string    char new_name[] = "geeksforgeeks.txt";    int value;      // File name is changed here    value = rename(old_name, new_name);      // Print the result    if(!value)    {        printf("%s", "File name changed successfully");    }    else    {        perror("Error");    }    return 0;}
Output:
If file name changed
File name changed successfully
            OR
If file name not changed
Error: No such file or directory

C-File Handling
C-Library
cpp-file-handling
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Sorting Array without using sort() in JavaScript

We are required to write a JavaScript function that takes in an array of numbers.
The function should sort the array using the Array.prototype.sort() method, but, here, we are
required to use the Array.prototype.reduce() method to sort the array.
Therefore, let’s write the code for this function −
The code for this will be −
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
const sortWithReduce = arr => {
   return arr.reduce((acc, val) => {
      let ind = 0;
      while(ind < arr.length && val < arr[ind]){
         ind++;
      }
      acc.splice(ind, 0, val);
      return acc;
   }, []);
};
console.log(sortWithReduce(arr));
The output in the console will be −
[
   98, 57, 89, 37, 34,
   5, 56, 4, 3
]
How do I query a MongoDB collection?

To query or return a MongoDB collection, use getCollection(). Let us create a collection with documents −
> db.demo294.insertOne({"EmployeeId":101,"EmployeeName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4a1a5d93261e4bc9ea36")
}
> db.demo294.insertOne({"EmployeeId":102,"EmployeeName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4a255d93261e4bc9ea37")
}
> db.demo294.insertOne({"EmployeeId":103,"EmployeeName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4a335d93261e4bc9ea38")
}
Display all documents from a collection with the help of find() method −
> db.demo294.find();
This will produce the following output −
{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e4d4a255d93261e4bc9ea37"), "EmployeeId" : 102, "EmployeeName" : "Bob" }
{ "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
Following is the query to get MongoDB collection −
> db.getCollection('demo294').find({
...   "EmployeeId":{$in:[101,103]}});
This will produce the following output −
{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
Palindromic Substrings in Python

Suppose we have a string; we have to count how many palindromic substrings present in this string. The substrings with different start indices or end indices are counted as different substrings even they consist of same characters. So if the input is like “aaa”, then the output will be 6 as there are six palindromic substrings like “a”, “a”, “a”, “aa”, “aa”, “aaa”
To solve this, we will follow these steps −
count := 0
for i in range 0 to length if stringfor j in range i + 1 to length of string + 1temp := substring from index i to jif temp is palindrome, then increase count by 1
for j in range i + 1 to length of string + 1temp := substring from index i to jif temp is palindrome, then increase count by 1
temp := substring from index i to j
if temp is palindrome, then increase count by 1
return counter
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution:
   def countSubstrings(self, s):
      counter = 0
      for i in range(len(s)):
         for j in range(i+1,len(s)+1):
            temp = s[i:j]
            if temp == temp[::-1]:
               counter+=1
      return counter
ob1 = Solution()
print(ob1.countSubstrings("aaaa"))
"aaaa"
10
PHP program to change date format - GeeksforGeeks

11 May, 2018
You are given a string which contain date and time. Date in dd/mm/yyyy format and time in 12 hrs format.You have to convert date in yyyy/mm/dd format and time in 24 hrs format.
Examples:
Input : $date = "12/05/2018 10:12 AM"
Output : 2018-05-12 10:12:00

Input : $date = "06/12/2014 04:13 PM"
Output : 2014-12-06 16:13:00

First we will convert date to unix timestamp using strtotime() and then use date() to convert it to a specific format(The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT))
<?php      // function to convert string and print    function convertString ($date)    {        // convert date and time to seconds        $sec = strtotime($date);          // convert seconds into a specific format        $date = date("Y-m-d H:i", $sec);          // append seconds to the date and time        $date = $date . ":00";          // print final date and time        echo $date;    }          // Driver code    $date = "06/12/2014 04:13 PM";    convertString($date);?>
2014-06-12 16:13:00

PHP-date-time
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to convert array to string in PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Python program to print even length words in a string

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a string we need to display all the words in the string with even length.
Split the input string using the split() function.
Split the input string using the split() function.
Iterate over the words of a string using for a loop & Calculate the length of the word using len() function.
Iterate over the words of a string using for a loop & Calculate the length of the word using len() function.
If the length evaluates to be even, word gets displayed on the screen.
If the length evaluates to be even, word gets displayed on the screen.
Otherwise, no word appears on the screen.
Otherwise, no word appears on the screen.
Now let’s see the implementation given below −
def printWords(s):
# split the string
s = s.split(' ')
# iterate in words of string
for word in s:
   # if length is even
   if len(word)%2==0:
      print(word)
# main
s = "tutorial point"
printWords(s)
tutorial
All the variables and functions are declared in the global scope as shown below −
In this article, we learned about the approach to print even length words in a string.
How to set the position of a Tkinter window without setting the dimensions?

Tkinter windows are executed after initializing the object of the Tkinter frame or window. We can define the size of the Tkinter window or frame using the Geometry manager. It defines the width and height of the initial Tkinter window where we generally place our widgets. To set the position of the Tkinter window while omitting the width and height, we can define the specification in the geometry manager.
# Import the required Libraries
from tkinter import *
from tkinter import ttk

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

# Set the geometry of tkinter frame without specifying width and height
x = 500
y = 300
win.geometry("+%d+%d" %(x,y))

# Add a Label widget
label = Label(win, text=" Tkinter has a variety of inbuilt functions, " "modules, and packages.", font = ('Georgia 20'))
label.pack(pady=10)

win.mainloop()
Run the code to display a window that is set to its content width and height.
C library function - strcmp()

The C library function int strcmp(const char *str1, const char *str2) compares the string pointed to, by str1 to the string pointed to by str2.
Following is the declaration for strcmp() function.
int strcmp(const char *str1, const char *str2)
str1 − This is the first string to be compared.
str1 − This is the first string to be compared.
str2 − This is the second string to be compared.
str2 − This is the second string to be compared.
This function return values that are as follows −
if Return value < 0 then it indicates str1 is less than str2.
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2.
if Return value = 0 then it indicates str1 is equal to str2.
The following example shows the usage of strcmp() function.
#include <stdio.h>
#include <string.h>

int main () {
   char str1[15];
   char str2[15];
   int ret;


   strcpy(str1, "abcdef");
   strcpy(str2, "ABCDEF");

   ret = strcmp(str1, str2);

   if(ret < 0) {
      printf("str1 is less than str2");
   } else if(ret > 0) {
      printf("str2 is less than str1");
   } else {
      printf("str1 is equal to str2");
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
str2 is less than str1


    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
PostgreSQL - HAVING Clause

The HAVING clause allows us to pick out particular rows where the function's result meets some condition.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause.
The following is the position of the HAVING clause in a SELECT query −
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY clause if used. The following is the syntax of the SELECT statement, including the HAVING clause −
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

Consider the table COMPANY having records as follows −
# select * from COMPANY;
 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)
The following is an example, which would display record for which the name count is less than 2 −
testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) < 2;
This would produce the following result −
  name
 -------
  Teddy
  Paul
  Mark
  David
  Allen
  Kim
  James
(7 rows)

Now, let us create three more records in COMPANY table using the following INSERT statements −
INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00);
INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00);
INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00);
Now, our table has the following records with duplicate names −
  id | name  | age | address      | salary
 ----+-------+-----+--------------+--------
   1 | Paul  |  32 | California   |  20000
   2 | Allen |  25 | Texas        |  15000
   3 | Teddy |  23 | Norway       |  20000
   4 | Mark  |  25 | Rich-Mond    |  65000
   5 | David |  27 | Texas        |  85000
   6 | Kim   |  22 | South-Hall   |  45000
   7 | James |  24 | Houston      |  10000
   8 | Paul  |  24 | Houston      |  20000
   9 | James |  44 | Norway       |   5000
  10 | James |  45 | Texas        |   5000
(10 rows)
The following is the example, which would display record for which the name count is greater than 1 −
testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) > 1;
This would produce the following result −
 name
-------
 Paul
 James
(2 rows)


    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
final variables in Java - GeeksforGeeks

05 Oct, 2021
In Java, we can use final keyword with variables, methods, and classes. When the final keyword is used with a variable of primitive data types such as int, float, etc), the value of the variable cannot be changed. 
Example 1: Usage of final with primitive datatype
Java
// Java Program to illustrate Use of Final Keyword// With Primitive Datatypes // Main classclass GFG {     // Main driver method    public static void main(String args[])    {         // Final primitive variable        final int i = 10;        i = 30;         // Error will be generated above    }}
Output:
Now you must be wondering what if we do use final keyword non-primitive variables, let us explore the same as we did above with the help of an example. 
Note: Non-primitive variables are always references to objects in Java, the members of the referred object can be changed. final for non-primitive variables just means that they cannot be changed to refer to any other object.
Example 2: Usage of final with primitive datatype 
Java
// Java Program to illustrate Use of Final Keyword// With Primitive Datatypes // Class 1class Helper {    int i = 10;} // Clss 2// main classclass GFG {     // Main driver method    public static void main(String args[])    {         final Helper t1 = new Helper();        t1.i = 30; // Works         // Print statement for successful execution of        // Program        System.out.print("Successfully executed");    }}
Successfully executed
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 
solankimayank
anikakapoor
sweetyty
Java-keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Multithreading in Java
Singleton Class in Java
LinkedList in Java
Stack Class in Java
Collections in Java
Initialize tuples with parameters in Python

When it is required to initialize the tuples with certain parameters, the 'tuple' method and the '*' operator can be used.
The 'tuple' method will convert the iterable passed to it as parameter into a tuple class type.
The * operator can be used to get the product of two values. It can also be used to multiple a single value multiple times and display it on the console.
Below is a demonstration for the same −
Live Demo
N = 6
print("The value of N has been initialized to "+str(N))

default_val = 2
print("The default value has been initialized to " +str(default_val))

indx = 3
print("The index value has been initialized to "+ str(indx))

val_to_add = 6
print("The value to be added is initialized to " +str(val_to_add))

my_result = [default_val] * N
my_result[indx] = val_to_add
my_result = tuple(my_result)

print("The tuple formed is : ")
print(my_result)
The value of N has been initialized to 6
The default value has been initialized to 2
The index value has been initialized to 3
The value to be added is initialized to 6
The tuple formed is :
(2, 2, 2, 6, 2, 2)
The value for 'N', 'index', 'value to be added' and a default value are initialized and displayed on the console.
The default value is multiplied with 'N' and assigned to a variable.
This operation is assigned to a variable.
That variable's 'index' is assigned the value that needs to be added.
Next, the variable is converted into a tuple, and stored in a variable.
This variable is the output that is displayed on the console.
How to use range input type in HTML?

The <input type="range"> is to add a range for the values. You can also set a restriction on range for the numbers. For restrictions, use the attributes like min, max and step attributes. The default range is from 0 to 100.
You can try to run the following code to learn how to use range input type in HTML. The range will be visible as a slider −
<!DOCTYPE html>
<html>
<head>
<title>HTML input range</title>
</head>
<body>
<form action = "" method = "get">
Let us know where the installation of the software stopped :<br><br>
<input type = "range" name = "point" min = "0" max = "50"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
Move all zeroes to end of the array using List Comprehension in Python

Given a list of numbers, move all the zeroes to the end using list comprehensions. For example, the result of [1, 3, 0, 4, 0, 5, 6, 0, 7] is [1, 3, 4, 5, 6, 7, 0, 0, 0].
It's a single line code using the list comprehensions. See the following steps to achieve the result.
Initialize the list of numbers.
Initialize the list of numbers.
Generate non-zeroes from the list and generate zeroes from the list. Add both. And store the result in a list.
Generate non-zeroes from the list and generate zeroes from the list. Add both. And store the result in a list.
Print the new list.
Print the new list.
# initializing a list
numbers = [1, 3, 0, 4, 0, 5, 6, 0, 7]
# moving all the zeroes to end
new_list = [num for num in numbers if num != 0] + [num for num in numbers if num == 0]
# printing the new list
print(new_list)
[1, 3, 4, 5, 6, 7, 0, 0, 0]
If you run the above code, you will get the following result.
[1, 3, 4, 5, 6, 7, 0, 0, 0]
If you have any queries regarding the tutorial, mention them in the comment section.
Diagonal Traverse in C++

Suppose we have a matrix of M x N elements, we have to find all elements of the matrix in diagonal order. So if the matrix is like −
The output will be [1,2,4,7,5,3,6,8,9]
To solve this, we will follow these steps −
Make an array ret, set row := 0 and col := 0, n := row count, m := col count, down := false
for i in range 0 to n – 1x := i, y := 0create an array tempwhile x >= 0 and y < m, doinsert matrix[x,y] into temp, and decrease x by 1 and increase y by 1if down is true, then reverse the temp arrayfor i in range 0 to size of temp – 1, insert temp[i] into retdown := inverse of down
x := i, y := 0
create an array temp
while x >= 0 and y < m, doinsert matrix[x,y] into temp, and decrease x by 1 and increase y by 1
insert matrix[x,y] into temp, and decrease x by 1 and increase y by 1
if down is true, then reverse the temp array
for i in range 0 to size of temp – 1, insert temp[i] into ret
down := inverse of down
for i in range 1 to m – 1x := n – 1, y := 1, create an array tempwhile x >= 0 and y < m,insert matrix[x, y] into temp and decrease x by 1 and increase y by 1for i in range 0 to size of temp – 1, insert temp[i] into retdown := inverse of down
x := n – 1, y := 1, create an array temp
while x >= 0 and y < m,insert matrix[x, y] into temp and decrease x by 1 and increase y by 1
insert matrix[x, y] into temp and decrease x by 1 and increase y by 1
for i in range 0 to size of temp – 1, insert temp[i] into ret
down := inverse of down
return ret.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
      vector <int> ret;
      int row = 0;
      int col = 0;
      int n = matrix.size();
      int m = n? matrix[0].size() : 0;
      bool down = false;
      for(int i = 0; i < n; i++){
         int x = i;
         int y = 0;
         vector <int> temp;
         while(x >= 0 && y < m){
            temp.push_back(matrix[x][y]);
            x--;
            y++;
         }
         if(down) reverse(temp.begin(), temp.end());
         for(int i = 0; i < temp.size(); i++)ret.push_back(temp[i]);
         down = !down;
      }
      for(int i = 1; i < m; i++){
         int x = n - 1;
         int y = i;
         vector <int> temp;
         while(x >= 0 && y < m){
            temp.push_back(matrix[x][y]);
            x--;
            y++;
         }
         if(down) reverse(temp.begin(), temp.end());
         for(int i = 0; i < temp.size(); i++)ret.push_back(temp[i]);
         down = !down;
      }
      return ret;
   }
};
main(){
   vector<vector<int>> v = {{1,2,3},{4,5,6},{7,8,9}};
   Solution ob;
   print_vector(ob.findDiagonalOrder(v));
}
[[1,2,3],[4,5,6],[7,8,9]]
[1, 2, 4, 7, 5, 3, 6, 8, 9, ]
Apache Pig - Distinct Operator

The DISTINCT operator is used to remove redundant (duplicate) tuples from a relation.
Given below is the syntax of the DISTINCT operator.
grunt> Relation_name2 = DISTINCT Relatin_name1;

Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.
student_details.txt
001,Rajiv,Reddy,9848022337,Hyderabad
002,siddarth,Battacharya,9848022338,Kolkata 
002,siddarth,Battacharya,9848022338,Kolkata 
003,Rajesh,Khanna,9848022339,Delhi 
003,Rajesh,Khanna,9848022339,Delhi 
004,Preethi,Agarwal,9848022330,Pune 
005,Trupthi,Mohanthy,9848022336,Bhuwaneshwar
006,Archana,Mishra,9848022335,Chennai 
006,Archana,Mishra,9848022335,Chennai

And we have loaded this file into Pig with the relation name student_details as shown below.
grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',') 
   as (id:int, firstname:chararray, lastname:chararray, phone:chararray, city:chararray);
Let us now remove the redundant (duplicate) tuples from the relation named student_details using the DISTINCT operator, and store it as another relation named distinct_data as shown below.
grunt> distinct_data = DISTINCT student_details;

Verify the relation distinct_data using the DUMP operator as shown below.
grunt> Dump distinct_data;
It will produce the following output, displaying the contents of the relation distinct_data as follows.
(1,Rajiv,Reddy,9848022337,Hyderabad)
(2,siddarth,Battacharya,9848022338,Kolkata) 
(3,Rajesh,Khanna,9848022339,Delhi) 
(4,Preethi,Agarwal,9848022330,Pune) 
(5,Trupthi,Mohanthy,9848022336,Bhuwaneshwar)
(6,Archana,Mishra,9848022335,Chennai)


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Inverting a binary tree in JavaScript

Suppose, we have a binary tree represented like this −
      4
   /    \
  2      7
 / \    / \
1 3     6  9
We are required to write a JavaScript function that takes in the root of this binary tree and inverts it.
The inverted version of this above binary tree will look like this −
      4
      / \
    7    2
   / \ / \
   9 6 3 1
The code for this will be −
// class for a single tree node
class Node{
   constructor(val){
      this.val = val;
      this.left = null;
      this.right = null;
   };
};
// class for binary tree
class BinaryTree{
   constructor(){
      // root of the binary tree
      this.root = null;
   };
   insert = (data) => {
      // creating a new node with data
      const newNode = new Node(data);
      // if root is null, then this node will be the root
      if(this.root === null){
         this.root = newNode;
      }else{
         // otherwise we find the correct position to insert this node
         this.insertData(this.root, newNode);
      };
   };
   insertData = (node, newNode) => {
      if(newNode.val < node.val){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertData(node.left, newNode);
         }
      }else{
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertData(node.right, newNode);
         }
      }
   };
   // function to invert the binary tree
   invert = (node) => {
      if(node === null){
         return;
      };
      [node.left, node.right] = [node.right, node.left];
      this.invert(node.right);
      this.invert(node.left);
   }
   traverse = (node) => {
      if(node === null){
         return;
      };
      this.traverse(node.right);
      console.log(node.val);
      this.traverse(node.left);
   };
};
const Tree = new BinaryTree();
Tree.insert(2);
Tree.insert(7);
Tree.insert(4);
Tree.insert(1);
Tree.insert(9);
Tree.insert(3);
Tree.insert(6);
// original right to left traversal
Tree.traverse(Tree.root);
Tree.invert(Tree.root);
console.log('after inversion');
// traversal right to left after inversion
Tree.traverse(Tree.root);
And the output in the console will be −
9
7
6
4
3
2
1
after inversion
1
2
3
4
6
7
9
Postorder Tree Traversal in Data Structures

In this section we will see the post-order traversal technique (recursive) for binary search tree.
Suppose we have one tree like this −
The traversal sequence will be like: 8, 5, 15, 23, 20, 16, 10
postorderTraverse(root):
Begin
   if root is not empty, then
      postorderTraversal(left of root)
      postorderTraversal(right of root)
      print the value of root
   end if
End
 Live Demo
#include<iostream>
using namespace std;
class node{
   public:
      int h_left, h_right, bf, value;
      node *left, *right;
};
class tree{
   private:
      node *get_node(int key);
   public:
      node *root;
      tree(){
         root = NULL; //set root as NULL at the beginning
      }
      void postorder_traversal(node *r);
      node *insert_node(node *root, int key);
};
node *tree::get_node(int key){
   node *new_node;
   new_node = new node; //create a new node dynamically
   new_node->h_left = 0; new_node->h_right = 0;
   new_node->bf = 0;
   new_node->value = key; //store the value from given key
   new_node->left = NULL; new_node->right = NULL;
   return new_node;
}
void tree::postorder_traversal(node *r){
   if(r != NULL){ //When root is present, visit left - root - right
      postorder_traversal(r->left);
      postorder_traversal(r->right);
      cout << r->value << " ";
   }
}
node *tree::insert_node(node *root, int key){
   if(root == NULL){
      return (get_node(key)); //when tree is empty, create a node as root
   }
   if(key < root->value){ //when key is smaller than root value, go to the left
      root->left = insert_node(root->left, key);
   }else if(key > root->value){ //when key is greater than root value, go to the right
      root->right = insert_node(root->right, key);
   }
   return root; //when key is already present, do not insert it again
}
main(){
   node *root;
   tree my_tree;
   //Insert some keys into the tree.
   my_tree.root = my_tree.insert_node(my_tree.root, 10);
   my_tree.root = my_tree.insert_node(my_tree.root, 5);
   my_tree.root = my_tree.insert_node(my_tree.root, 16);
   my_tree.root = my_tree.insert_node(my_tree.root, 20);
   my_tree.root = my_tree.insert_node(my_tree.root, 15);
   my_tree.root = my_tree.insert_node(my_tree.root, 8);
   my_tree.root = my_tree.insert_node(my_tree.root, 23);
   cout << "Post-Order Traversal: ";
   my_tree.postorder_traversal(my_tree.root);
}
Post-Order Traversal: 8 5 15 23 20 16 10
Create a Calculator function in JavaScript

We have to write a function, say calculator() that takes in one of the four characters (+, - , *, / )
as the first argument and any number of Number literals after that. Our job is to perform the
operation specified as the first argument over those numbers and return the result.
If the operation is multiplication or addition, we are required to perform the same operation with
every element. But if the operation is subtraction or division, we have to consider the first
element as neutral and subtract all other elements from it or divide it by all other elements,
based on the operation.
Therefore, let’s write the code for this function −
const calculator = (operation, ...numbers) => {
   const legend = '+-*/';
   const ind = legend.indexOf(operation);
   return numbers.reduce((acc, val) => {
      switch(operation){
         case '+': return acc+val;
         case '-': return acc-val;
         case '*': return acc*val;
         case '/': return acc/val;
      };
   });
};
console.log(calculator('+', 12, 45, 21, 12, 6));
console.log(calculator('-', 89, 45, 21, 12, 6));
console.log(calculator('*', 12, 45, 21, 12, 6));
console.log(calculator('/', 189000, 45, 7, 12, 4));
The output in the console will be −
96
5
816480
12.5
Groovy - padLeft()

Pad the String with the spaces appended to the left.This method has 2 different variants.
String padLeft(Number numberOfCharacters) − Pad the String with the spaces appended to the left.
String padLeft(Number numberOfCharacters) − Pad the String with the spaces appended to the left.
Syntax
String padLeft(Number numberOfCharacters)

Parameters
numberOfCharacters – The number of characters to pad the string with.
Return Value − The new value of the string with the padded characters
String padLeft(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the left.
String padLeft(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the left.
Syntax
String padLeft(Number numberOfCharacters, String padding)

Parameters
numberOfCharacters − The number of characters to pad the string with.
numberOfCharacters − The number of characters to pad the string with.
Padding − The character to apply for the padding.
Padding − The character to apply for the padding.
Return Value − The new value of the string with the padded characters.
Following is an example of the usage of both method variants −
class Example { 
   static void main(String[] args) { 
      String a = "Hello World";
		
      println(a.padLeft(14)); 
      println(a.padLeft(16)); 
      println(a.padLeft(16,'*')); 
      println(a.padLeft(14,'*')); 
   } 
}
When we run the above program, we will get the following result −
Hello World 
Hello World 
*****Hello World 
***Hello World


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to extract subset of key-value pairs from Python dictionary object?

Use dictionary comprehension technique.
We have dictionary object having name and percentage of students
>>> marks = {
   'Ravi': 45.23,
   'Amar': 62.78,
   'Ishan': 20.55,
   'Hema': 67.20,
   'Balu': 90.75
}
To obtain dictionary of name and marks of students with percentage>50
>>> passed = { key:value for key, value in marks.items() if value > 50 }
>>> passed
{'Amar': 62.78, 'Hema': 67.2, 'Balu': 90.75}
To obtain subset of given names
>>> names = { 'Amar', 'Hema', 'Balu' }
>>> lst = { key:value for key,value in marks.items() if key in names}
>>> lst
{'Amar': 62.78, 'Hema': 67.2, 'Balu': 90.75}
Stack data structure - GeeksQuiz

06 May, 2017
              8 2 3 ^ / 2 3 * + 5 1 * - 
1. While there are input tokens left
    o Read the next token from input.
    o If the token is a value
       + Push it onto the stack.
    o Otherwise, the token is an operator 
      (operator here includes both operators, and functions).
       * It is known a priori that the operator takes n arguments.
       * If there are fewer than n values on the stack
        (Error) The user has not input sufficient values in the expression.
       * Else, Pop the top n values from the stack.
       * Evaluate the operator, with the values as arguments.
       * Push the returned results, if any, back onto the stack.
2. If there is only one value in the stack
    o That value is the result of the calculation.
3. If there are more values in the stack
    o (Error)  The user input has too many values.
    8, 2, 3
    8, 8
    1
    1, 2, 3
    1, 6
To evaluate an expression without any embedded function calls : 
As many stacks as the height of the expression tree are needed
One stack is enough
Two stacks are needed
A Turing machine is needed in the general case
Any expression can be converted into Postfix or Prefix form. Prefix and postfix evaluation can be done using a single stack. For example : Expression '10 2 8 * + 3 -' is given. PUSH 10 in the stack. PUSH 2 in the stack. PUSH 8 in the stack. When operator '*' occurs, POP 2 and 8 from the stack. PUSH 2 * 8 = 16 in the stack. When operator '+' occurs, POP 16 and 10 from the stack. PUSH 10 * 16 = 26 in the stack. PUSH 3 in the stack. When operator '-' occurs, POP 26 and 3 from the stack. PUSH 26 - 3 = 23 in the stack. So, 23 is the answer obtained using single stack.  Thus, option (A) is correct.  Please comment below if you find anything wrong in the above post.  
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Get Hired With GeeksforGeeks and Win Exciting Rewards!
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
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 Concat Two Columns Into One With the Existing Column Name in MySQL?
ReactJS – componentDidUpdate() Method

In this article, we are going to see how to execute a function when the component is updated in the DOM tree.
This method is called only when the component gets updated or when the props passed to it change. It isn’t called for the initial render of the component. This method is majorly used to perform some operations which are needed to be executed only if the DOM is updated.
To avoid any performance issues, it is advised to use this method with conditional loop like −
componentDidUpdate(prevProps, prevState) {
   if (prevState.text !== this.state.text) {
      // Write logic here.
   }
}
componentDidUpdate(prevProps, prevState, snapshot)
prevProps - Previous props passed into the component
prevProps - Previous props passed into the component
prevState   - Previous state of the component
prevState   - Previous state of the component
snapshot   - Value returned by getSnapshotBeforeUpdate() method
snapshot   - Value returned by getSnapshotBeforeUpdate() method
In this example, we will build a color-changing React application which changes the color of the text on the click of the button which will update the component and the componentDidUpdate method will be called.
Our first component in the following example is App. This component is the parent of the Change component. We are creating Change 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 {
   render() {
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <Change />
         </div>
      );
   }
}
class Change extends React.Component {
   constructor(props) {
      super(props);
      this.state = { color: '#000' };
   }
   componentDidUpdate() {
      console.log('componentDidUpdate method is called');
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Simply Easy Learning</h1>
            <button onClick={() => this.setState({ color: '#0f0' })}>
               Change Color
            </button>
         </div>
      );
   }
}
export default App;
This will produce the following result.
Django - Creating Views

A view function, or “view” for short, is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page.
In Django, views have to be created in the app views.py file.
We will create a simple view in myapp to say "welcome to my app!"
See the following view −
from django.http import HttpResponse

def hello(request):
   text = """<h1>welcome to my app !</h1>"""
   return HttpResponse(text)
In this view, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the view). To see this view as a page we just need to map it to a URL (this will be discussed in an upcoming chapter).
We used HttpResponse to render the HTML in the view before. This is not the best way to render pages. Django supports the MVT pattern so to make the precedent view, Django - MVT like, we will need −
A template: myapp/templates/hello.html
And now our view will look like −
from django.shortcuts import render

def hello(request):
   return render(request, "myapp/template/hello.html", {})
Views can also accept parameters −
from django.http import HttpResponse

def hello(request, number):
   text = "<h1>welcome to my app number %s!</h1>"% number
   return HttpResponse(text)
When linked to a URL, the page will display the number passed as a parameter. Note that the parameters will be passed via the URL (discussed in the next chapter).

    39 Lectures 
     3.5 hours 

 John Elder

    36 Lectures 
     2.5 hours 

 John Elder

    28 Lectures 
     2 hours 

 John Elder

    20 Lectures 
     1 hours 

 John Elder

    35 Lectures 
     3 hours 

 John Elder

    79 Lectures 
     10 hours 

 Rathan Kumar
 Print
 Add Notes
 Bookmark this page
ES6 - replace()

This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
The replacement string can include the following special replacement patterns −
$$
Inserts a "$".
$&
Inserts the matched substring.
$`
Inserts the portion of the string that precedes the matched substring.
$'
Inserts the portion of the string that follows the matched substring.
$n or $nn
Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
string.replace(regexp/substr, newSubStr/function[, flags]);

regexp − A RegExp object. The match is replaced by the return value of parameter #2.
regexp − A RegExp object. The match is replaced by the return value of parameter #2.
substr − A String that is to be replaced by newSubStr.
substr − A String that is to be replaced by newSubStr.
newSubStr − The String that replaces the substring received from parameter #1.
newSubStr − The String that replaces the substring received from parameter #1.
function − A function to be invoked to create the new substring.
function − A function to be invoked to create the new substring.
flags − A String containing any combination of the RegExp flags: g.
flags − A String containing any combination of the RegExp flags: g.
It simply returns a new changed string.
var re = /apples/gi; 
var str = "Apples are round, and apples are juicy."; 
var newstr = str.replace(re, "oranges"); 
console.log(newstr)   
oranges are round, and oranges are juicy.    

var re = /(\w+)\s(\w+)/; 
var str = "zara ali"; 
var newstr = str.replace(re, "$2, $1"); 
console.log(newstr);
ali, zara


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
log4j - Logging Methods

Logger class provides a variety of methods to handle logging activities. The Logger class does not allow us to instantiate a new Logger instance but it provides two static methods for obtaining a Logger object −
public static Logger getRootLogger();
public static Logger getLogger(String name);
The first of the two methods returns the application instance's root logger and it does not have a name.
Any other named Logger object instance is obtained through the second method by passing the name of the logger. The name of the logger can be any string you can pass, usually a class or a package name as we have used in the last chapter and it is mentioned below −
static Logger log = Logger.getLogger(log4jExample.class.getName());
Once we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.
It prints messages with the level Level.DEBUG.
It prints messages with the level Level.ERROR.
It prints messages with the level Level.FATAL.
It prints messages with the level Level.INFO.
It prints messages with the level Level.WARN.
It prints messages with the level Level.TRACE.
All the levels are defined in the org.apache.log4j.Level class and any of the above mentioned methods can be called as follows −
import org.apache.log4j.Logger;

public class LogClass {
   private static org.apache.log4j.Logger log = Logger.getLogger(LogClass.class);
   
   public static void main(String[] args) {
   
      log.trace("Trace Message!");
      log.debug("Debug Message!");
      log.info("Info Message!");
      log.warn("Warn Message!");
      log.error("Error Message!");
      log.fatal("Fatal Message!");
   }
}
When you compile and run LogClass program, it would generate the following result −
Debug Message!
Info Message!
Warn Message!
Error Message!
Fatal Message!

All the debug messages make more sense when they are used in combination with levels. We will cover levels in  the next chapter and then, you would have a good understanding of how to use these methods in combination with different levels of debugging.
 Print
 Add Notes
 Bookmark this page
Ruby | Array replace() function - GeeksforGeeks

06 Dec, 2019
Array#replace() : replace() is a Array class method which returns an array of all combinations of elements from all arrays.
Syntax: Array.replace()
Parameter: Array
Return: an array of all combinations of elements from all arrays.
Example #1 :
# Ruby code for replace() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [2, 5]  # replace method examplea.replace(b)puts "replace() method form : #{a}\n\n"  b.replace(c)puts "replace() method form : #{b}\n\n"  c.replace(a)puts "replace() method form : #{c}\n\n"
Output :
replace() method form : [1, 4, 1, 1, 88, 9]

replace() method form : [2, 5]

replace() method form : [1, 4, 1, 1, 88, 9]



Example #2 :
# Ruby code for replace() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["hi"]  # declaring arrayb = ["cow", nil, "dog"]  # replace method examplea.replace(b)puts "replace() method form : #{a}\n\n"  b.replace(c)puts "replace() method form : #{b}\n\n"  c.replace(a)puts "replace() method form : #{c}\n\n"
Output :
replace() method form : ["cow", nil, "dog"]

replace() method form : ["hi"]

replace() method form : ["cow", nil, "dog"]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Array slice() function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
MySQL | ENCODE( ) Function

13 Nov, 2019
The MySQL ENCODE() function is used for encoding a plain text string. The MySQL ENCODE() function returns a binary string which of the same size of the plain text string. The MySQL DECODE() function returns empty strings if the string passed is an empty string.
The ENCODE() function accepts two parameters which are the string to be encoded and the key string to encode the plain text string.
Syntax:
ENCODE(plain_string, password_string);
Parameters Used:
plain_string – It is used to specify the plain text that is to be encoded.
password_string – It is used to specify the password string to encode the plain text string.
Return Value:The ENCODE function in MySQL returns a binary string after encoding.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing ENCODE function on a string.
SELECT  
ENCODE('geeksforgeeks', 'passwordstring'); 
Output:
Q)?P????j[K 
Example-2: Implementing ENCODE function on a string which has a combination of characters and integers.
SELECT  
ENCODE('geeksforgeeks123', 'passwordstring'); 
Output:
Q)?P????j[K??= 
Example-3: Implementing ENCODE function on a NULL string.
SELECT  
ENCODE('NULL', 'passwordstring'); 
Output:
NULL 
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.