code-rag-bench/online-tutorials huggingface dataset:
SequenceEqual method in C#

The SequenceEqual method is used to test collections for equality.
Let us set three string arrays −
string[] arr1 = { "This", "is", "it" };
string[] arr2 = { "My", "work", "report" };
string[] arr3 = { "This", "is", "it" };
Now, compare the first array with the second using the SequenceEqual() method −
arr1.SequenceEqual(arr2);
The following is an example −
 Live Demo
using System;
using System.Linq;
class Program {
   static void Main() {
      string[] arr1 = { "This", "is", "it" };
      string[] arr2 = { "My", "work", "report" };
      string[] arr3 = { "This", "is", "it" };
      bool res1 = arr1.SequenceEqual(arr2);
      Console.WriteLine(res1);
      bool res2 = arr1.SequenceEqual(arr3);
      Console.WriteLine(res2);
   }
}
False
True
How to implement custom serializer using @JsonSerialize annotation in Java?

The @JsonSerialize annotation is used to declare custom serializer during the serialization of a field. We can implement a custom serializer by extending the StdSeralizer class. and need to override the serialize() method of StdSerializer class.
@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonSerialize
In the below program, we can implement a custom serializer using @JsonSerialize annotation
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.ser.std.*;
public class JsonSerializeAnnotationTest {
   public static void main (String[] args) throws JsonProcessingException, IOException {
      Employee emp = new Employee(115, "Adithya", new String[] {"Java", "Python", "Scala"});
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonString);
   }
}
// CustomSerializer class
class CustomSerializer extends StdSerializer {
   public CustomSerializer(Class t) {
      super(t);
   }
   public CustomSerializer() {
      this(Employee.class);
   }
   @Override
   public void serialize(Employee emp, JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonGenerationException {
      StringBuilder sb = new StringBuilder();
      jgen.writeStartObject();
      jgen.writeNumberField("id", emp.getId());
      jgen.writeStringField("name", emp.getName());
      for(String s: emp.getLanguages()) {
         sb.append(s).append(";");
      }
      jgen.writeStringField("languages", sb.toString());
      jgen.writeEndObject();
   }
}
// Employee class
@JsonSerialize(using=CustomSerializer.class)
class Employee {
   private int id;
   private String name;
   private String[] languages;
   public Employee(int id, String name, String[] languages) {
      this.id = id;
      this.name = name;
      this.languages = languages;
   }
   public int getId() {
      return this.id;
   }
   public String getName() {
      return this.name;
   }
   public String[] getLanguages() {
      return this.languages;
   }
   @Override
   public String toString() {
      StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name).append("\nLanguages:");
      for(String s: this.languages) {
         sb.append(" ").append(s);
      }
      return sb.toString();
   }
}
{
   "id" : 115,
   "name" : "Adithya",
   "languages" : "Java;Python;Scala;"
}
Parse a string to a Boolean object in Java

The valueOf() method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, Boolean, etc. Therefore, to parse a string to a Boolean object, use the Java valueOf() method.
The following is an example showing how to parse a string to a Boolean object in Java.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      System.out.println("Parsing a string to a Boolean object...");
      Boolean val = Boolean.valueOf("true");
      System.out.println("Value: "+val);
   }
}
Parsing a string to a Boolean object...
Value: true
Boolean object is used to parse a string in the above program.
Boolean val = Boolean.valueOf("true");
We have passed a string “true” to valueOf() method above. This string is parsed.
Difference between single quote (‘) and double quote (“) in PowerShell?

There is no such difference between the single quote (‘) and double quote(“) in PowerShell. It is similar to a programming language like Python. We generally use both quotes to print the statements.
PS C:\> Write-Output 'This will be printed using Single quote'
This will be printed using Single quote
PS C:\> Write-Output "This will be printed using double quote"
This will be printed using double quote
But when we evaluate any expression or print variable it makes a clear difference.
$date = Get-Date
Write-Output 'Today date is : $date'
Today date is : $date
Write-Output "Today date is : $date"
Today date is : 11/02/2020 08:13:06
You can see in the above example that a single quote can’t print the variable output and instead it is printing the name of the variable, while the double quotes can print the output of the variable. Even if we try to evaluate a variable name it can’t be done using a single quote.
PS C:\> Write-Output 'Today date is : $($date)'
Today date is : $($date)
Another example of multiplication operation,
PS C:\> Write-Output "Square of 4 : $(4*4)"
Square of 4 : 16
PS C:\> Write-Output 'square of 4 : $(4*4)'
square of 4 : $(4*4)
Take an example of printing multiple statements using an array.
$name = 'Charlie'
$age = 40
$str = @"
New Joinee name is $name
Her age is $age
"@
$str
New Joinee name is Charlie
Her age is 40
He will receive 1200 dollar bonus after 2 years
The above output is printed properly but when we use the single quote, it won’t print the variable name.
$str = @'
New Joinee name is $name
Her age is $age
He will receive $($age*30) dollar bonus after 2 years
'@
New Joinee name is $name
Her age is $age
He will receive $($age*30) dollar bonus after 2 years
It is concluded that, use a single quote only to print the plain text but to print variables and evaluating other expressions in the string, use the double quote in PowerShell.
Find frequency of each element in a limited range array in less than O(n) time in C++

Suppose we have an array of integers. The array is A, and the size is n. Our task is to find the frequency of all elements in the array less than O(n) time. The size of the elements must be less than one value say M. Here we will use the binary search approach. Here we will recursively divide the array into two parts if the end elements are different, if both its end elements are the same, it means all elements in the array are the same as the array is already sorted.
 Live Demo
#include<iostream>
#include<vector>
using namespace std;
void calculateFreq(int arr[], int left, int right, vector<int>& frequency) {
   if (arr[left] == arr[right])
      frequency[arr[left]] += right - left + 1;
   else {
      int mid = (left + right) / 2;
      calculateFreq(arr, left, mid, frequency);
      calculateFreq(arr, mid + 1, right, frequency);
   }
}
void getAllFrequency(int arr[], int n) {
   vector<int> frequency(arr[n - 1] + 1, 0);
   calculateFreq(arr, 0, n - 1, frequency);
   for (int i = 0; i <= arr[n - 1]; i++)
      if (frequency[i] != 0)
         cout << "Frequency of element " << i << " is " << frequency[i] << endl;
}
int main() {
   int arr[] = { 10, 10, 10, 20, 30, 30, 50, 50, 80, 80, 80, 90, 90, 99 };
   int n = sizeof(arr) / sizeof(arr[0]);
   getAllFrequency(arr, n);
}
Frequency of element 10 is 3
Frequency of element 20 is 1
Frequency of element 30 is 2
Frequency of element 50 is 2
Frequency of element 80 is 3
Frequency of element 90 is 2
Frequency of element 99 is 1
How to create a New Line in PHP ? - GeeksforGeeks

21 Sep, 2021
New Line helps the page to look better and presentable. We will learn to insert a new line in PHP using 2 ways.
Using Line Breaks as in HTML
Using New Line tags
Using Line Breaks as in HTML: The <br> tag in HTML is used to give the single line break. It is an empty tag, so it does not contain an end tag.
Syntax:
</br>
Example: 
PHP
<?phpecho "Akshit ". "<br>". "Loves GeeksForGeeks";?>
Akshit 
Loves GeeksForGeeks
Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.
Syntax: 
 "\n"
Example 1: 
PHP
<?phpecho "Akshit " ."\n"."Loves GeeksForGeeks";?>
Akshit 
Loves GeeksForGeeks
Syntax: 
"\r\n"
Example 2: 
PHP
<?phpecho "Akshit " ."\r\n"."Loves GeeksForGeeks";?>
Akshit 
Loves GeeksForGeeks
simmytarika5
HTML-Tags
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Find the Next perfect square greater than a given number

13 Apr, 2021
Given a number N, the task is to find the next perfect square greater than N.Examples: 
Input: N = 6
Output: 9
9 is a greater number than 6 and
is also a perfect square

Input: N = 9
Output: 16
Approach:  
Find the square root of given N.Calculate its floor value using floor function in C++.Then add 1 to it.Print square of that number.
Find the square root of given N.
Calculate its floor value using floor function in C++.
Then add 1 to it.
Print square of that number.
Below is the implementation of above approach:  
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <iostream>#include<cmath>using namespace std; // Function to find the next perfect squareint nextPerfectSquare(int N){    int nextN = floor(sqrt(N)) + 1;     return nextN * nextN;} // Driver Codeint main(){    int n = 35;     cout << nextPerfectSquare(n);    return 0;}
// Java implementation of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{     // Function to find the// next perfect squarestatic int nextPerfectSquare(int N){    int nextN = (int)Math.floor(Math.sqrt(N)) + 1;     return nextN * nextN;} // Driver Codepublic static void main(String args[]){    int n = 35;     System.out.println (nextPerfectSquare(n));}} // This code is contributed by Subhadeep
# Python3 implementation of above approach import math#Function to find the next perfect square def nextPerfectSquare(N):     nextN = math.floor(math.sqrt(N)) + 1     return nextN * nextN if __name__=='__main__':    N = 35    print(nextPerfectSquare(N)) # this code is contributed by Surendra_Gangwar
// C# implementation of above approachusing System; class GFG{     // Function to find the// next perfect squarestatic int nextPerfectSquare(int N){    int nextN = (int)Math.Floor(Math.Sqrt(N)) + 1;     return nextN * nextN;} // Driver Codepublic static void Main(){    int n = 35;     Console.WriteLine(nextPerfectSquare(n));}} // This code is contributed// by Shashank
<?php// PHP implementation// of above approach // Function to find the// next perfect squarefunction nextPerfectSquare($N){    $nextN = floor(sqrt($N)) + 1;     return $nextN * $nextN;} // Driver Code$n = 35; echo nextPerfectSquare($n); // This code is contributed by mits?>
<script>// Javascript implementation of above approach // Function to find the next perfect squarefunction nextPerfectSquare(N){    let nextN = Math.floor(Math.sqrt(N)) + 1;     return nextN * nextN;} // Driver Codelet n = 35; document.write(nextPerfectSquare(n)); // This code is contributed by souravmahato348.</script>
36
 
Time Complexity: O(1)
Auxiliary Space: O(1)
tufan_gupta2000
Mithun Kumar
SURENDRA_GANGWAR
Shashank12
subhammahato348
souravmahato348
maths-perfect-square
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Python | Scipy integrate.romb() method

23 Jan, 2020
With the help of scipy.integrate.romb() method, we can get the romberg integration using samples of a function from limit a to b by using scipy.integrate.romb() method.
Syntax : scipy.integrate.romb(y, dx, axis, show)Return : Return the romberg integration of a sample.
Example #1 :In this example we can see that by using scipy.integrate.romb() method, we are able to get the romberg integration using samples of a function from limit a to b by using this method.
# import numpy and scipy.integrateimport numpy as npfrom scipy import integratex = np.arange(3, 12)  # using scipy.integrate.romb() methodgfg = integrate.romb(x)  print(gfg)
Output :
56.0
Example #2 :
# import numpy and scipy.integrateimport numpy as npfrom scipy import integratex = np.arange(3, 12)y = np.cos(np.power(x, 3.5))  # using scipy.integrate.romb() methodgfg = integrate.romb(y)  print(gfg)
Output :
-3.5943771512643674
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How to Install Pyglet in python on Windows?

22 Sep, 2021
The pyglet library is a cross-platform windowing and multimedia library for Python, intended for developing games and other visually rich applications. In this article, we will look into the process of installing Pyglet in Python on Windows.
The only thing that you need for installing Numpy on Windows are:
Python 
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda,  open up the Anaconda Powershell Prompt and use the below command:
conda install -c conda-forge pyglet
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
To verify if pyglet library has been successfully installed in your system run the below command in Anaconda Powershell Prompt:
conda list pyglet
You’ll get the below message if the installation is complete:
If you want the installation to be done through PIP,  open up the Command Prompt and use the below command:
pip install pyglet
You will get a similar message once the installation is complete:
To verify if the Pyglet Library has been successfully installed in your system run the below command in Command Prompt:
python -m pip show pyglet
You’ll get the below message if the installation is complete:
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Difference Between Local Storage, Session Storage And Cookies
Explain the purpose of render() in ReactJS
How to Find the Wi-Fi Password Using CMD in Windows?
Java Tutorial
How to filter object array based on attributes?
How to Align Text in HTML?
How to Install FFmpeg on Windows?
Python | Numpy matrix.compress()

10 Apr, 2019
With the help of Numpy matrix.compress() method, we can select the elements from a matrix by passing a parameter as an array which contain the value 0 to not include the element or 1 to include the element in a matrix. Simply we pass the boolean array in matrix.compress() method.
Syntax : matrix.compress()
Return : Return a compressed array
Example #1 :In this example we can see that with the help of matrix.compress() method we are able to compress a matrix.
# import the important module in pythonimport numpy as np             # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4; 3, 1, 5, 6]')             # applying matrix.compress() methodgeeks = np.compress([1, 0, 1, 0, 1, 1], gfg)       print(geeks)
[[1 3 3 1]]

Example #2 :
# import the important module in pythonimport numpy as np             # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')             # applying matrix.compress() methodgeeks = np.compress([1, 0, 1, 1, 1, 0, 0, 1, 1], gfg)       print(geeks)
[[1 3 4 5 8 9]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
C library function - localeconv()

The C library function struct lconv *localeconv(void) sets or reads location dependent information. These are returned in an object of the lconv structure type.
Following is the declaration for localeconv() function.
struct lconv *localeconv(void)
NA
NA
This function returns a pointer to a struct lconv for the current locale, which has the following structure −
typedef struct {
   char *decimal_point;
   char *thousands_sep;
   char *grouping;	
   char *int_curr_symbol;
   char *currency_symbol;
   char *mon_decimal_point;
   char *mon_thousands_sep;
   char *mon_grouping;
   char *positive_sign;
   char *negative_sign;
   char int_frac_digits;
   char frac_digits;
   char p_cs_precedes;
   char p_sep_by_space;
   char n_cs_precedes;
   char n_sep_by_space;
   char p_sign_posn;
   char n_sign_posn;
} lconv
The following example shows the usage of localeconv() function.
#include <locale.h>
#include <stdio.h>

int main () {
   struct lconv * lc;

   setlocale(LC_MONETARY, "it_IT");
   lc = localeconv();
   printf("Local Currency Symbol: %s\n",lc->currency_symbol);
   printf("International Currency Symbol: %s\n",lc->int_curr_symbol);

   setlocale(LC_MONETARY, "en_US");
   lc = localeconv();
   printf("Local Currency Symbol: %s\n",lc->currency_symbol);
   printf("International Currency Symbol: %s\n",lc->int_curr_symbol);

   setlocale(LC_MONETARY, "en_GB");
   lc = localeconv();
   printf ("Local Currency Symbol: %s\n",lc->currency_symbol);
   printf ("International Currency Symbol: %s\n",lc->int_curr_symbol);

   printf("Decimal Point = %s\n", lc->decimal_point);
   
   return 0;
}
Let us compile and run the above program that will produce the following result −
Local Currency Symbol: EUR
International Currency Symbol: EUR
Local Currency Symbol: $
International Currency Symbol: USD
Local Currency Symbol: £
International Currency Symbol: GBP
Decimal Point = .


    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
Creating 3D Globe using React-three-fiber

In this article, you will learn how to create a globe using react-threefiber. We will first make a sphere and then map a whole Earth map on it. This is an interesting texture loader feature using which we canmake any image to wrap over a sphere as texture. So, let's get started!
First, download important libraries −
npm i --save @react-three/fiber three
This library react-three/fiber will be used to add webGL renderer to the website and to connect threejs and React.
Download an image of Earth map and place it in the “src” folder. We have named the image file as "world-map.gif".
Add the following lines of code in App.js −
import React, { useRef } from "react";
import { Canvas,useFrame,useLoader } from "@reactthree/fiber";
import * as THREE from "three";
import earthImg from './world-map.gif'
import "./App.css";

const Sphere=()=>{
   const base=new THREE.TextureLoader().load(earthImg)
   const ref=useRef()
   useFrame(() => (ref.current.rotation.x=ref.current.rotation.y += 0.01))
   <return(
      <mesh visible castShadow ref={ref}>
      <directionalLight intensity={0.5} />
      <sphereGeometry attach="geometry" args={[2, 32, 32]} />
      <meshBasicMaterial
         map={base}
         color="white"
      />
      </mesh>
   )
}
export default function App(){
   return (
      <Canvas>
         <ambientLight />
         <Sphere/>
      </Canvas>
   );
};
Here we first created a Sphere and loaded a texture. Then we wrapped
the texture over the sphere.
<mesh> is used to make threeJS object, and inside it we made a box using SphereGeometry which is used to define size, shape and other structural things.
meshBasicMaterial which is use to design our geometrical structure. <mesh> is used to combine the structure and the design together. We created a functional component inside which we made a reference. Next, we created a Frame which is used to change the position of our mesh object or sphere. Then we added frame to reference and gave reference to mesh.
The Position argument simply positions the object. <AmbientLight> is used to make the colors visible. In its absence, <Sphere> will look whole black.
It will produce the following output −
Your browser does not support HTML5 video.
How to compare timestamps in MySQL?

To compare timestamps in MySQL, you can use DATE(). Let us first create a table−
mysql> create table comparingTimestampDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> AdmissionDate timestamp
   -> );
Query OK, 0 rows affected (0.54 sec)
Following is the query to insert records in the table using insert command −
mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-03-31');
Query OK, 1 row affected (0.13 sec)
mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-04-10');
Query OK, 1 row affected (0.12 sec)
mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-04-15');
Query OK, 1 row affected (0.17 sec)
mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-03-29');
Query OK, 1 row affected (0.15 sec)
mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-04-07');
Query OK, 1 row affected (0.18 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from comparingTimestampDemo;
This will produce the following output −
+----+---------------------+
| Id | AdmissionDate       |
+----+---------------------+
| 1  | 2019-03-31 00:00:00 |
| 2  | 2019-04-10 00:00:00 |
| 3  | 2019-04-15 00:00:00 |
| 4  | 2019-03-29 00:00:00 |
| 5  | 2019-04-07 00:00:00 |
+----+---------------------+
5 rows in set (0.00 sec)
Let us now compare timestamps in MySQL −
mysql> SELECT DATE(`AdmissionDate`) FROM comparingTimestampDemo WHERE
DATE(`AdmissionDate`) < CURDATE() - INTERVAL 3 DAY;
This will produce the following output −
+-----------------------+
| DATE(`AdmissionDate`) |
+-----------------------+
| 2019-03-31            |
| 2019-03-29            |
+-----------------------+
2 rows in set (0.00 sec)
How to remove an item from a C++ STL vector with a certain value?

Erase function is used to remove an item from a C++ STL vector with a certain value.
Begin
Declare vector v and iterator it to the vector.
Initialize the vector.
Erase() function is used to remove item from end.
Print the remaining elements.
End.
#include <iostream>
#include <vector>
using namespace std;
int main() {
   vector<int> v{ 6,7,8,9,10};
   vector<int>::iterator it;
   it = v.end();
   it--;
   v.erase(it);
   for (auto it = v.begin(); it != v.end(); ++it)
      cout << ' ' << *it;
   return 0;
}
The current content of the vector is :
6 7 8 9 10
Please enter the element to be deleted -> 7
The current content of the vector is :
6 8 9 10
How to execute zombie and orphan process in a single program? - GeeksforGeeks

04 Sep, 2018
Prerequisite: Zombie and Orphan Processes in C
Zombie Process:A zombie process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child’s exit status.A process that terminates cannot leave the system until its parent accepts its return code. If its parent process is already dead, it’ll already have been adopted by the “init” process, which always accepts its children’s return codes. However, if a process’s parent is alive but never executes a wait ( ), the process’s return code will never be accepted and the process will remain a zombie.
Orphan Process:An orphan process is a process that is still executing, but whose parent has died. They do not become zombie processes; instead, they are adopted by init (process ID 1), which waits on its children.When a parent dies before its child, the child is automatically adopted by the original “init” process whose PID is 1.
Approach:In the following code, we have made a scenario that there is a parent and it has a child and that child also has a child, firstly if our process gets into child process, we put our system into sleep for 5 sec so that we could finish up the parent process so that its child become orphan, then we have made a child’s child as zombie process, the child’s child finishes its execution while the parent(i.e child) sleeps for 1 seconds, hence the child’s child doesn’t call terminate, and it’s entry still exists in the process table.
Below is the implementation of above approach:
// C program to execute zombie and// orphan process in a single program#include <stdio.h>int main(){      int x;    x = fork();      if (x > 0)        printf("IN PARENT PROCESS\nMY PROCESS ID                               : %d\n", getpid());      else if (x == 0) {        sleep(5);        x = fork();          if (x > 0) {   printf("IN CHILD PROCESS\nMY PROCESS ID :%d\n           PARENT PROCESS ID : %d\n", getpid(), getppid());     while(1)     sleep(1);     printf("IN CHILD PROCESS\nMY PARENT PROCESS ID                                : %d\n", getppid());        }          else if (x == 0)            printf("IN CHILD'S CHILD PROCESS\n                  MY PARENT ID : %d\n", getppid());    }      return 0;}
Output:Note: Above code may not work with the online compiler as fork() is disabled.
CPP-Library
Operating Systems-Process Management
system-programming
C Language
C++
Operating Systems Questions
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
MongoDB - Atomic Operations

The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. This would make sure that all the updates for a single document are atomic.
Assume we have created a collection with name productDetails and inserted a documents in it as shown below −
>db.createCollection("products")
{ "ok" : 1 }
> db.productDetails.insert(
	{
		"_id":1,
		"product_name": "Samsung S3",
		"category": "mobiles",
		"product_total": 5,
		"product_available": 3,
		"product_bought_by": [
			{
				"customer": "john",
				"date": "7-Jan-2014"
			},
			{
				"customer": "mark",
				"date": "8-Jan-2014"
			}
		]
	}
)
WriteResult({ "nInserted" : 1 })
>
In this document, we have embedded the information of the customer who buys the product in the product_bought_by field. Now, whenever a new customer buys the product, we will first check if the product is still available using product_available field. If available, we will reduce the value of product_available field as well as insert the new customer's embedded document in the product_bought_by field. We will use findAndModify command for this functionality because it searches and updates the document in the same go.
>db.products.findAndModify({ 
   query:{_id:2,product_available:{$gt:0}}, 
   update:{ 
      $inc:{product_available:-1}, 
      $push:{product_bought_by:{customer:"rob",date:"9-Jan-2014"}} 
   }    
})
Our approach of embedded document and using findAndModify query makes sure that the product purchase information is updated only if it the product is available. And the whole of this transaction being in the same query, is atomic.
In contrast to this, consider the scenario where we may have kept the product availability and the information on who has bought the product, separately. In this case, we will first check if the product is available using the first query. Then in the second query we will update the purchase information. However, it is possible that between the executions of these two queries, some other user has purchased the product and it is no more available. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have sold a product which is not available.

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
callable() in Python

The callable() function in python is part of its standard library which returns true if the object is callable and returns false if it is not.The object itself should have a call method to be callable. For example if we just declare a variable with value, it is not callable, but if we declare a function then it becomes callable.
Below we declare a function which is callable. That can be verified by actually making a call to the function, as well as checking through the callable function.
def func_callable():
   x = 3
   y = 5
   z = x^y
   return z
# an object is created of Geek()
res = func_callable
print(callable(res))
print(res)
# Call and use the function
final_res=func_callable()
print(final_res)
Running the above code gives us the following result −
True
6
Here we see the same program as above but without using any functions. We just use some variables for calculations. When the results are nor printed we see that the variable values are not callable.
x = 3
y = 5
z = x^y
print(callable(z))
print(z)
Running the above code gives us the following result −
False
6
How can I get the current Android SDK version programmatically using Kotlin?

This example demonstrates how to
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="4dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textColor="@android:color/black"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
   private lateinit var textView: TextView
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      textView = findViewById(R.id.textView)
      val versionAPI = Build.VERSION.SDK_INT
      val versionRelease = Build.VERSION.RELEASE
      textView.text = "API Version : $versionAPI\nVersion Release : $versionRelease"
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Deserialize JSON to Object in Python - GeeksforGeeks

07 Jul, 2021
Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module to perform this task :  
loads() : to deserialize a JSON document to a Python object.
load() : to deserialize a JSON formatted stream ( which supports reading from a file) to a Python object.
Example 1 : Using the loads() function.  
Python3
# importing the moduleimport json # creating the JSON data as a stringdata = '{"Name" : "Romy", "Gender" : "Female"}' print("Datatype before deserialization : "      + str(type(data)))  # deserializing the datadata = json.loads(data) print("Datatype after deserialization : "      + str(type(data)))
Output :  
Datatype before deserialization : 
Datatype after deserialization : 
Example 2 : Using the load() function. We have to deserialize a file named file.json.  
 
Python3
# importing the moduleimport json # opening the JSON filedata = open('file.json',) print("Datatype before deserialization : "      + str(type(data)))    # deserializing the datadata = json.load(data) print("Datatype after deserialization : "      + str(type(data)))
Output :  
Datatype before deserialization : 
Datatype after deserialization : 
 
gabaa406
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Java Scope

In Java, variables are only accessible inside the region they are created. This is called
scope.
Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:
public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    int x = 100;

    // Code here can use x
    System.out.println(x);
  }
}

Try it Yourself »

A block of code refers to all of the code between curly braces {}.
Variables
declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared:
public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    { // This is a block

      // Code here CANNOT use x

      int x = 100;

      // Code here CAN use x
      System.out.println(x);

   } // The block ends here

  // Code here CANNOT use x

  }
}

Try it Yourself »

A block of code may exist on its
own or it can belong to an if, while or for statement. In the case of for statements,
variables declared in the statement itself are also available inside the block's scope.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Default constructor in Java

Java compiler automatically creates a default constructor (Constructor with no arguments) in case no constructor is present in the java class. Following are the motive behind a default constructor.
Create the Object
Create the Object
Call the super class constructor()
Call the super class constructor()
Initialize all the instance variables of the class object.
Initialize all the instance variables of the class object.
 Live Demo
public class Tester {
   int a;
   String b;
   public static void main(String[] args) {

      //Default constructor
      //is called to create a new object
      Tester t = new Tester();
      //print the default values
      System.out.println(t.a);
      System.out.println(t.b);
   }
}
0
null
C++ List Library - pop_front() Function

The C++ function std::list::pop_front() removes first element from list and reduces size of list by one.
Following is the declaration for std::list::pop_front() function form std::list header.
void pop_front();

None
None
This member function never throws exception. Calling this function on empty list causes undefined behavior.
Constant i.e. O(1)
The following example shows the usage of std::list::pop_front() function.
#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l = {1, 2, 3, 4, 5};

   cout << "List contains following elements before pop_back operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   l.pop_front();

   cout << "List contains following elements after pop_back operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
List contains following elements before pop_back operation
1
2
3
4
5
List contains following elements after pop_back operation
2
3
4
5

 Print
 Add Notes
 Bookmark this page
How to include() all PHP files from a directory ? - GeeksforGeeks

10 Jan, 2019
Given list of PHP files in a directory and the task is to include all files from a directory. In order to include all PHP files from directory at once need a foreach-loop.
Example: This example contains four PHP files (file1.php, file2.php, file3.php, file4.php) in a directory. Create one file named as main.php which contains PHP code to include files.
Create file1.php in folder ‘myGeeks’:
<?php echo "1st File Included Successfully<br>";?>
Create file2.php in folder ‘myGeeks’:
<?php echo "2nd File Included Successfully<br>";?>
Create file3.php in folder ‘myGeeks’:
<?php echo "3rd File Included Successfully<br>";?>
Create file4.php in folder ‘myGeeks’:
<?php echo "4th File Included Successfully<br>";?>
Create main.php outside folder:
<?phpforeach (glob("folder/*.php") as $filename) {    include $filename;}?>
Run on Windows platform:
Folder myGeeks which contains all files:
Folder htdocs contains main.php file:
Run on Browser:
Run on Ubuntu platform:
Folder ‘Desktop/folder’ which contains all files:
Folder ‘Desktop’ contains main.php file:
Run on Terminal:
Output:
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
PyQt5 - Add Label to StatusBar - GeeksforGeeks

22 Apr, 2020
In this article we will see how to add label to a status bar. We can set text to status bar by using showMessage method.
Label and StatusBar ?A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. A label is generally used to identify a nearby text box or other widget. A status bar is a horizontal bar, usually at the bottom of the screen or window, showing information about a document being edited or a program running.
In order to do this we will do following steps :
1. Create a label2. Add text to label3. Create object of status bar4. Add label to status bar
Code :
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Python")          # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)          # setting status bar message        self.statusBar().showMessage("This is status bar")          # setting  border and padding with different sizes        self.statusBar().setStyleSheet("border :3px solid black;")          # creating a label widget        self.label_1 = QLabel("Label 1")            # setting up the border        self.label_1.setStyleSheet("border :2px solid blue;")          # adding label to status bar        self.statusBar().addPermanentWidget(self.label_1)        # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()    # start the appsys.exit(App.exec())
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
GATE | GATE-CS-2017 (Set 1) | Question 25 - GeeksforGeeks

13 Aug, 2021
Consider the following functions from positives integers to real numbers
10, √n, n, log2n, 100/n.
The CORRECT arrangement of the above functions in increasing order of asymptotic complexity is:(A) log2n, 100/n, 10, √n, n(B) 100/n, 10, log2n, √n, n(C) 10, 100/n ,√n, log2n, n(D) 100/n, log2n, 10 ,√n, nAnswer: (B)Explanation: For the large number, value of inverse of number is less than a constant and value of constant is less than value of square root.
10 is constant, not affected by value of n.√n Square root and log2n is logarithmic. So log2n is definitely less than √nn has linear growth and 100/n grows inversely with value of n. For bigger value of n, we can consider it 0, so 100/n is least and n is max.So the increasing order of asymptotic complexity will be :
100/n < 10 < log2n < √n < n
So, option (b) is true.
YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGate PYQs on Addressing Modes with Ashish Verma |GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:28 / 42:29•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cGRKsf_9sv8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90