code-rag-bench/online-tutorials huggingface dataset:
How to declare a two-dimensional array in C#

A 2-dimensional array is a list of one-dimensional arrays. Declare it like the two dimensional array shown below −
int [,] a
Two-dimensional arrays may be initialized by specifying bracketed values for each row.
int [,] a = new int [4,4] {
{0, 1, 2, 3} ,
{4, 5, 6, 7} ,
{8, 9, 10, 11} ,
{12, 13, 14, 15}
};
The following is an example showing how to work with two-dimensional arrays in C# −
 Live Demo
using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         /* an array with 3 rows and 2 columns*/
         int[,] a = new int[3, 2] {{0,0}, {1,2}, {2,4} };
         int i, j;

         /* output each array element's value */
         for (i = 0; i < 3; i++) {

            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}
a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
Check whether a character is Lowercase or not in Java

To check whether a character is in Lowercase or not in Java, use the Character.isLowerCase() method.
We have a character to be checked.
char val = 'q';
Now let us use the Character.isLowerCase() method.
if (Character.isLowerCase(val)) {
   System.out.println("Character is in Lowercase!");
}else {
   System.out.println("Character is in Uppercase!");
}
Let us see the complete example now to check for Lowercase in Java.
 Live Demo
public class Demo {
   public static void main(String []args) {
      System.out.println("Checking for Lowercase character...");
      char val = 'q';
      System.out.println("Character: "+val);
      if (Character.isLowerCase(val)) {
         System.out.println("Character is in Lowercase!");
      } else {
         System.out.println("Character is in Uppercase!");
      }
   }
}
Checking for Lowercase character...
Character: q
Character is in Lowercase!
Can we call methods using this keyword in java?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it. But, you should call them only from instance methods (non-static).
In the following example, the Student class has a private variable name, with setter and getter methods, using the setter method we have assigned value to the name variable from the main method and then, we have invoked the getter (getName) method using "this" keyword from the instance method.
public class ThisExample_Method {
   private String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void display() {
      System.out.println("name: "+this.getName());
   }
   public static void main(String args[]) {
      ThisExample_Method obj = new ThisExample_Method();
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      obj.setName(name);
      obj.display();
   }
}
Enter the name of the student:
Krishna
name: Krishna
How to convert a value to a number in JavaScript?

Javascript has introduced Number() method to convert a value into a number. This method can convert number strings to numbers and boolean values to 1's or 0's. Let's discuss it briefly.
var num = Number(value);
In the following example, Number() method has converted number strings and boolean values to numbers and displayed the output as shown. 
Live Demo
<html>
<body>
<script>
   document.write(Number("10.5") + "</br>");
   document.write(Number(" 123 ") + "</br>");
   document.write(Number(true) + "</br>");
   document.write(Number(false) + "</br>");
   document.write(Number(null));
</script>
</body>
</html>
10.5
123
1
0
0
This method not only converts a normal value to a number but also converts a hexadecimal value to a number as shown below.
 Live Demo
<html>
<body>
<script>
   document.write(Number(" ") + "<br>");  
   document.write(Number("") + "<br>");  
   document.write(Number("123e-1") + "<br>");  
   document.write(Number("0xFF") + "<br>");
</script>
</body>
</html>
0
0
12.3
255
Round float and double numbers in Java

In order to round float and double numbers in Java, we use the java.lang.Math.round() method. The method accepts either double or float values and returns an integer value. It returns the closest integer to number. This is computed by adding 1⁄2 to the number and then flooring it.
Declaration - The java.lang.Math.round() method is declared as follows −
public static int round(float a)
public static int round(double a)
where a is the value to be rounded.
Let us see a program where float and double numbers are rounded in Java.
 Live Demo
import java.lang.Math;
public class Example {
   public static void main(String[] args) {
      // declaring and initializing some double and values
      double x = 25.5;
      float y = 8.1f;
      // printing the rounded values
      System.out.println("The round-off of "+ x + " is "+ Math.round(x));
      System.out.println("The round-off of "+ y + " is "+ Math.round(y));
   }
}
The round-off of 25.5 is 26
The round-off of 8.1 is 8
VueJS - Introduction

Vue is a JavaScript framework for building user interfaces. Its core part is focused mainly on the view layer and it is very easy to understand. The version of Vue that we are going to use in this tutorial is 2.0.
As Vue is basically built for frontend development, we are going to deal with lot of HTML, JavaScript and CSS files in the upcoming chapters. To understand the details, let us start with a simple example.
In this example, we are going to use the development verison of vuejs.
<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "intro" style = "text-align:center;">
         <h1>{{ message }}</h1>
      </div>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               message: 'My first VueJS Task'
            }
         });
      </script>
   </body>
</html>
This is the first app we have created using VueJS. As seen in the above code, we have included vue.js at the start of the .html file.
<script type = "text/javascript" src = "js/vue.js"></script>
There is a div which is added in the body that prints “My first VueJS Task” in the browser.
<div id = "intro" style = "text-align:center;">
   <h1>{{ message }}</h1>
</div>
We have also added a message in a interpolation, i.e. {{}}. This interacts with VueJS and prints the data in the browser. To get the value of the message in the DOM, we are creating an instance of vuejs as follows −
var vue_det = new Vue({
   el: '#intro',
   data: {
      message: 'My first VueJS Task'
   }
})
In the above code snippet, we are calling Vue instance, which takes the id of the DOM element i.e. e1:’#intro’, it is the id of the div. There is data with the message which is assigned the value ‘My first VueJS Task’. VueJS interacts with DOM and changes the value in the DOM {{message}} with ’My first VueJS Task’.
If we happen to change the value of the message in the console, the same will be reflected in the browser. For example −
In the above console, we have printed the vue_det object, which is an instance of Vue. We are updating the message with “VueJs is interesting” and the same is changed in the browser immediately as seen in the above screenshot.
This is just a basic example showing the linking of VueJS with DOM, and how we can manipulate it. In the next few chapters, we will learn about directives, components, conditional loops, etc.
 Print
 Add Notes
 Bookmark this page
CSS - Media Types

One of the most important features of style sheets is that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc.
We have currently two ways to specify media dependencies for style sheets −
Specify the target medium from a style sheet with the @media or @import at-rules.
Specify the target medium from a style sheet with the @media or @import at-rules.
Specify the target medium within the document language.
Specify the target medium within the document language.
An @media rule specifies the target media types (separated by commas) of a set of rules.
Given below is an example −
<style tyle = "text/css">
   <!--
      @media print {
         body { font-size: 10pt }
      }
	
      @media screen {
         body { font-size: 12pt }
      }
      @media screen, print {
         body { line-height: 1.2 }
      }
   -->
</style>
In HTML 4.0, the media attribute on the LINK element specifies the target media of an external style sheet −
Following is an example −
<style tyle = "text/css">
   <!--
      <!doctype html public "-//w3c//dtd html 4.0//en">
      <html>
         <head>
            <title>link to a target medium</title>
            <link rel = "stylesheet" type = "text/css" media = "print, 
               handheld" href = "foo.css">
         </head>

         <body>
            <p>the body...
         </body>
      </html>
   -->
</style>
The names chosen for CSS media types reflect target devices for which the relevant properties make sense. They give a sense of what device the media type is meant to refer to. Given below is a list of various media types −
all
Suitable for all devices.
aural
Intended for speech synthesizers.
braille
Intended for braille tactile feedback devices.
embossed
Intended for paged braille printers.
handheld
Intended for handheld devices (typically small screen, monochrome, limited bandwidth).
print
Intended for paged, opaque material and for documents viewed on screen in print preview mode. Please consult the section on paged media.
projection
Intended for projected presentations, for example projectors or print to transparencies. Please consult the section on paged media.
screen
Intended primarily for color computer screens.
tty
Intended for media using a fixed-pitch character grid, such as teletypes, terminals, or portable devices with limited display capabilities.
tv
Intended for television-type devices.
NOTE − Media type names are case-insensitive.

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Lex program to count the frequency of the given word in a file - GeeksforGeeks

10 Oct, 2021
Problem: Given a text file as input, the task is to count frequency of a given word in the file. Explanation: Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Approach: As we know, yytext holds the value of current matched token, we can compare it with the word whose frequency is to be counted. if the value of yytext and the given word are same, increment the count variable.Input File: input.txt 
Below is the implementation of above approach:
C
/* LEX code to count the frequency   of the given word in a file */ /* Definition section *//* variable word indicates the word   whose frequency is to be count *//* variable count is used to store the   frequency of the given word */ %{#include<stdio.h>#include<string.h> char word [] = "geeks";int count = 0;  %} /* Rule Section *//* Rule 1 compares the matched token with the   word to count and increments the count variable   on successful match  *//* Rule 2 matches everything other than string   (consists of alphabets only ) and do nothing */ %%[a-zA-Z]+    { if(strcmp(yytext, word)==0)                   count++; }.  ;        %%  int yywrap(){    return 1;} /* code section */int main(){        extern FILE *yyin, *yyout;                 /* open the input file           in read mode */        yyin=fopen("input.txt", "r");        yylex();                  printf("%d", count);     }
Output:
ruhelaa48
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Code Optimization in Compiler Design
Intermediate Code Generation in Compiler Design
Difference between Top down parsing and Bottom up parsing
Loop Optimization in Compiler Design
Difference between Compiler and Interpreter
Symbol Table in Compiler
Input Buffering in Compiler Design
Ambiguous Grammar
Introduction of Compiler Design
Types of Parsers in Compiler Design
Association, Composition and Aggregation in Java


Association refers to the relationship between multiple objects. It refers to how objects are related to each other and how they are using each other's functionality. Composition and aggregation are two types of association.
The composition is the strong type of association. An association is said to composition if an Object owns another object and another object cannot exist without the owner object. Consider the case of Human having a heart. Here Human object contains the heart and heart cannot exist without Human.
Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently. For example, a Team object and a Player object. The team contains multiple players but a player can exist without a team.
//Car must have Engine
public class Car {
   //engine is a mandatory part of the car
   private final Engine engine;

   public Car () {
      engine = new Engine();
   }
}

//Engine Object
class Engine {}
//Team
public class Team {      
   //players can be 0 or more
   private List players;

   public Car () {
      players = new ArrayList();
   }
}
//Player Object
class Player {}
numpy.diff() in Python

22 Jul, 2021
numpy.diff(arr[, n[, axis]]) function is used when we calculate the n-th order discrete difference along the given axis. The first order difference is given by out[i] = arr[i+1] – arr[i] along the given axis. If we have to calculate higher differences, we are using diff recursively.
Syntax: numpy.diff()Parameters: arr : [array_like] Input array. n : [int, optional] The number of times values are differenced. axis : [int, optional] The axis along which the difference is taken, default is the last axis.Returns : [ndarray]The n-th discrete difference. The output is the same as a except along axis where the dimension is smaller by n.  
Code #1 :  
Python3
# Python program explaining# numpy.diff() method    # importing numpyimport numpy as geek # input arrayarr = geek.array([1, 3, 4, 7, 9])  print("Input array  : ", arr)print("First order difference  : ", geek.diff(arr))print("Second order difference : ", geek.diff(arr, n = 2))print("Third order difference  : ", geek.diff(arr, n = 3))
Input array  :  [1 3 4 7 9]
First order difference  :  [2 1 3 2]
Second order difference :  [-1  2 -1]
Third order difference  :  [ 3 -3]
 
  Code #2 : 
Python3
# Python program explaining# numpy.diff() method    # importing numpyimport numpy as geek # input arrayarr = geek.array([[1, 2, 3, 5], [4, 6, 7, 9]])  print("Input array  : ", arr)print("Difference when axis is 0 : ", geek.diff(arr, axis = 0))print("Difference when axis is 1 : ", geek.diff(arr, axis = 1))
Input array  :  [[1 2 3 5]
 [4 6 7 9]]
Difference with axis 0 :  [[3 4 4 4]]
Difference with axis 1 :  [[1 1 2]
 [2 1 2]]
 
sumitgumber28
Python-numpy
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java - Logical Operators Example

The following simple example program demonstrates the logical operators. Copy and paste the following Java program in Test.java file and compile and run this program −
public class Test {

   public static void main(String args[]) {
      boolean a = true;
      boolean b = false;

      System.out.println("a && b = " + (a&&b));
      System.out.println("a || b = " + (a||b) );
      System.out.println("!(a && b) = " + !(a && b));
   }
}
This will produce the following result −
a && b = false
a || b = true
!(a && b) = true
Getting the Determinant of the Matrix in R Programming – det() Function

03 Jun, 2020
det() function in R Language is used to calculate the determinant of the specified matrix.
Syntax: det(x, ...)
Parameters:x: matrix
Example 1:
# R program to illustrate# det function  # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(c(3, 2, 6, -1, 7, 3, 2, 6, -1), 3, 3)  # Getting the matrix representationx  # Calling the det() functiondet(x)
Output:
     [, 1] [, 2] [, 3]
[1, ]    3   -1    2
[2, ]    2    7    6
[3, ]    6    3   -1

[1] -185

Example 2:
# R program to illustrate# det function  # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(c(3, 2, 6, -1, 7, 3, 2, 6, -1), 3, 3)  # Getting the matrix representationx  # Getting the transpose of the matrix xy <- t(x)y  # Calling the det() functiondet(y)
Output:
     [, 1] [, 2] [, 3]
[1, ]    3   -1    2
[2, ]    2    7    6
[3, ]    6    3   -1

     [, 1] [, 2] [, 3]
[1, ]    3    2    6
[2, ]   -1    7    3
[3, ]    2    6   -1

[1] -185

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Difference between Ambiguous and Unambiguous Grammar

15 Jul, 2020
Prerequisite – Context Free Grammars1. Ambiguous Grammar :A context-free grammar is called ambiguous grammar if there exists more than one derivation tree or parse tree.
Example –
S -> S + S / S * S / S / a 
2. Unambiguous Grammar :A context-free grammar is called unambiguous grammar if there exists one and only one derivation tree or parse tree.
Example –
X -> AB
A -> Aa / a
B -> b 
Difference between Ambiguous and Unambiguous Grammar :
Difference Between
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Pandas - How to delete a row from a DataFrame

To delete a row from a DataFrame, use the drop() method and set the index label as the parameter.
At first, let us create a DataFrame. We have index label as w, x, y, and z:
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],
columns=['a', 'b'])
Now, let us use the index label and delete a row. Here, we will delete a row with index label ‘w’
dataFrame = dataFrame.drop('w')

Following is the code
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b'])

# DataFrame
print"DataFrame...\n",dataFrame

# deleting a row
dataFrame = dataFrame.drop('w')
print"DataFrame after deleting a row...\n",dataFrame
This will produce the following output
DataFrame...
   a   b
w  10  15
x  20  25
y  30  35
z  40  45
DataFrame after deleting a row...
   a   b
x  20  25
y  30  35
z  40  45
How to get the current URL using AngularJS ?

29 Sep, 2020
In this article, we are going to see how to get the current URL with the help of AngularJS. We will be using the $location.absURL() method to get the complete URL of the current page.
Syntax:
$location.absURL()
Example 1: Just use the $location.absURL() method to get the complete URL of the current page.
HTML
<!DOCTYPE HTML><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>      <script>        var myApp = angular.module("app", []);        myApp.controller("controller",            function ($scope, $location) {                $scope.url = '';                $scope.getUrl = function () {                    $scope.url = $location.absUrl();                };            });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>        <p>        Get current URL in angularJS    </p>        <div ng-app="app">        <div ng-controller="controller">              <p>Url = {{url}}</p>              <input type="button"                 value="Click to get URL"                 ng-click="getUrl()">        </div>    </div></body>  </html>
Output:
Example 2: Similar to the previous example but using the split() method to get the domain name of the URL.
HTML
<!DOCTYPE HTML><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>      <script>        var myApp = angular.module("app", []);        myApp.controller("controller",            function ($scope, $location) {                $scope.url = '';                $scope.getUrl = function () {                    // Will change the current url to                     // ide.geeksforgeeks.org                    $scope.url = $location                        .absUrl().split('/')[2];;                };            });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>        <p>        Get current URL in angularJS    </p>        <div ng-app="app">        <div ng-controller="controller">              <p>Url = {{url}}</p>              <input type="button"                 value="Click to get URL"                 ng-click="getUrl()">        </div>    </div></body>  </html>
Output:
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert Java object to JSON using the Gson library in Java?


A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert a bean/ java object to a JSON object. We can call the toJson() method of Gson class to convert a Java object to a JSON object.
public java.lang.String toJson(java.lang.Object src)
import com.google.gson.Gson;
public class ConvertJavaObjectToJSONTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      Student student = new Student("Raja", "Ramesh", 30, "Hyderabad");
      System.out.println(gson.toJson(student)); // converts java object to json object.
   }
}
// student class
class Student {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Student(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String toString() {
      return "Student[ " +
               " firstName = " + firstName +
               ", lastName = " + lastName +
               ", age = " + age +
               ", address = " + address +
               " ]";
   }
}
{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
alias - Unix, Linux Command

alias - This command creates an alias. Aliases allow a string to be substituted for a word when it is used as the first word of a simple command.
alias [-p] [name[=value] ...]
If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, alias will print the current value of the alias. Without arguments or with the -p option, alias prints the list of aliases on the standard output in a form that allows them to be reused as input. The value cannot contain any positional parameters ($1 etc), if you need to do that use a shell function instead.

To create an alias to clear the screen.
$ alias cls='clear'

Use the alias
$ cls


To create an alias to clear the screen.
$ alias cls='clear'

Use the alias
$ cls

To create an alias 'ls' to change the default action of ls.
$ alias ls='ls --a'

Use the alias
$ ls
. .. sample.txt


To create an alias 'ls' to change the default action of ls.
$ alias ls='ls --a'

Use the alias
$ ls
. .. sample.txt

To create various alias using cd command to go into to sub-sub directories.
$ alias ..='cd ..' 
$ alias ...='cd ../..'
$ alias ....='cd ../../..'

Use the alias
$ mkdir sample
$ cd sample
$ pwd
/sample
$ ..
$ pwd
/


To create various alias using cd command to go into to sub-sub directories.
$ alias ..='cd ..' 
$ alias ...='cd ../..'
$ alias ....='cd ../../..'

Use the alias
$ mkdir sample
$ cd sample
$ pwd
/sample
$ ..
$ pwd
/

To create alias to display present working directory.
$ alias .='echo $PWD'

Use the alias
$ .
/


To create alias to display present working directory.
$ alias .='echo $PWD'

Use the alias
$ .
/

To create alias to prevent accidental deletion.
$ alias rm='rm -i'

First create a sample.txt file
sample text

Remove the sample.txt file interactively
$ rm sample.txt
rm: remove regular file 'sample.txt' ? 


To create alias to prevent accidental deletion.
$ alias rm='rm -i'

First create a sample.txt file
sample text

Remove the sample.txt file interactively
$ rm sample.txt
rm: remove regular file 'sample.txt' ? 


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Enum for days of week in Java

To set enum for days of the week, set them as constants
enum Days {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
Now create objects and set the above constants −
Days today = Days.Wednesday;
Days holiday = Days.Sunday;
The following is an example −
 Live Demo
public class Demo {
   enum Days {
      Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
   }
   public static void main(String[] args) {
      Days today = Days.Wednesday;
      Days holiday = Days.Sunday;
      System.out.println("Today = " + today);
      System.out.println(holiday+ " is holiday");
   }
}
Today = Wednesday
Sunday is holiday
C++ Program to Implement Next_Permutation in STL

Next_permutation in STL is used to rearrange the elements in the range [first, last] into the next lexicographically greater permutation. A permutation is each one of the N! possible arrangements the elements can take. This is C++ program to implement Next_permutation in STL.
Begin
   Define one integer array variable elements[].
   Get the number of data e from the user.
   Initialize the array elements[] with e number of data from the keyboard.
   Sort all the array elements.
   do
      show(elements, e) //to display the current content of the array
   while (next_permutation(elements, elements + e))
End
#include<iostream>
#include <algorithm>
using namespace std;
void show(int a[], int n) {
   for(int i = 0; i < n; i++) {
      cout<<a[i]<<" ";
   }
   cout<<endl;
}
int main () {
   int e, i;
   cout<<"Enter number of elements to be inserted: ";
   cin>>e;
   int elements[e];
   for (i = 0; i < e; i++) {
      cout<<"Enter "<<i + 1<<" element: ";
      cin>>elements[i];
   }
   sort (elements, elements + e);
   cout << "The "<<e<<"! possible permutations with ";
   cout<<e<<" elements: "<<endl;
   do {
      show(elements, e);
   }
   while (next_permutation(elements, elements + e));
   return 0;
}
Enter number of elements to be inserted: 4
Enter 1 element: 7
Enter 2 element: 6
Enter 3 element: 2
Enter 4 element: 10
The 4! possible permutations with 4 elements:
2 6 7 10
2 6 10 7
2 7 6 10
2 7 10 6
2 10 6 7
2 10 7 6
6 2 7 10
6 2 10 7
6 7 2 10
6 7 10 2
6 10 2 7
6 10 7 2
7 2 6 10
7 2 10 6
7 6 2 10
7 6 10 2
7 10 2 6
7 10 6 2
10 2 6 7
10 2 7 6
10 6 2 7
10 6 7 2
10 7 2 6
10 7 6 2
Wand push() and pop() in Python

16 Oct, 2021
We can use ImageMagick’s internal graphic context stack to manage different styles and operations in Wand. There are total four push functions for context stack.  
push()
push_clip_path()
push_defs()
push_pattern()
push() function is used to grow context stack and pop() is another function and used to restore stack to previous push. 
Syntax :  
# for push()
wand.drawing.push()

# for pop()
wand.drawing.pop()
Parameters : No parameters for push() as well as for pop() function
Example #1:  
Python3
from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as ctx:    ctx.fill_color = Color('RED')    ctx.stroke_color = Color('BLACK')    ctx.push()     ctx.circle((50, 50), (25, 25))    ctx.pop()     ctx.fill_color = Color('YELLOW')    ctx.stroke_color = Color('GREEN')    ctx.push()     ctx.circle((150, 150), (125, 125))    ctx.pop()     with Image(width = 200, height = 200, background = Color('lightgreen')) as image:        ctx(image)        image.save(filename = "push.png")
Output:  
Example #2:  
Python3
from wand.color import Colorfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.compat import nestedfrom math import cos, pi, sin with nested(Color('lightblue'),            Color('transparent'),            Drawing()) as (bg, fg, draw):    draw.stroke_width = 3    draw.fill_color = fg     for degree in range(0, 360, 15):        draw.push()  # Grow stack        draw.stroke_color = Color('hsl({0}%, 100 %, 50 %)'.format(degree * 100 / 360))        t = degree / 180.0 * pi        x = 35 * cos(t) + 50        y = 35 * sin(t) + 50        draw.line((50, 50), (x, y))        draw.pop()  # Restore stack     with Image(width = 100, height = 100, background = Color('green')) as img:        draw(img)        img.save(filename = "pushpop.png")
Output: 
 
saurabh1990aror
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Using Async Await in Node.js

19 Feb, 2019
Before Node version 7.6, the callbacks were the only official way provided by Node to run one function after another. As Node architecture is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed.
Example of a Callback:
app.get('/', function(){
 function1(arg1, function(){
   ...
})
});

The problem with this kind of code is that this kind of situations can cause a lot of trouble and the code can get messy when there are several functions. This situation is called what is commonly known as a callback hell.So, to find a way out, the idea of Promises and function chaining was introduced.
Example: Before async/await
function fun1(req, res){
  return request.get('http://localhost:3000')
   .catch((err) =>{
     console.log('found error');
}).then((res) =>{
   console.log('get request returned.');
});

Explanation:The above code demos a function implemented with function chaining instead of callbacks. It can be observed that the code is now more easy to understand and readable. The code basically says that GET localhost:3000, catch the error if there is any; if there is no error then implement the following statement:console.log(‘get request returned.’);
With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise. The code now looks like below.
Example: After async/await
async function fun1(req, res){
  let response = await request.get('http://localhost:3000');
    if (response.err) { console.log('error');}
    else { console.log('fetched response');
}

Explanation:The code above basically asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.Code writing and understanding becomes easy with async/await as can be observed from both the examples.
JavaScript-Misc
Node.js
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
Preorder Tree Traversal in Data Structures

In this section we will see the pre-order traversal technique (recursive) for binary search tree.
Suppose we have one tree like this −
The traversal sequence will be like: 10, 5, 8, 16, 15, 20, 23
preorderTraverse(root):
Begin
   if root is not empty, then
      print the value of root
      preorderTraversal(left of root)
      preorderTraversal(right 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 preorder_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::preorder_traversal(node *r){
   if(r != NULL){ //When root is present, visit left - root - right
      cout << r->value << " ";
      preorder_traversal(r->left);
      preorder_traversal(r->right);
   }
}
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 << "Pre-Order Traversal: ";
   my_tree.preorder_traversal(my_tree.root);
}
Pre-Order Traversal: 10 5 8 16 15 20 23
Python | sympy.is_complex method

13 May, 2022
With the help of sympy.is_complex method, we can check whether element is complex or not this method will return the boolean value i.e True or False.
Syntax : sympy.is_complexReturn : Return True if complex else False.
Example #1 :In this example we can see that by using sympy.is_complex method, we are able to check the complex value and it will return a boolean value.
# import sympyfrom sympy import *  # Use sympy.is_complex methodgfg = simplify(2 * I).is_complex    print(gfg)
Output :
True
Example #2 :
# import sympyfrom sympy import *  # Use sympy.is_complex methodgfg = simplify(5).is_complex    print(gfg)
Output :
True
ankita_saini
SymPy
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
When can we use the pack() method in Java?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes. An alternative to the pack() method is to establish a frame size explicitly by calling the setSize() or setBounds() methods. In general, using the pack() method is preferable to call than setSize() method, since pack leaves the frame layout manager in charge of the frame size and layout managers are good at adjusting to platform dependencies and other factors that affect the component size.
public void pack()
import java.awt.*;
import javax.swing.*;
public class PackMethodTest extends JFrame {
   public PackMethodTest() {
      setTitle("Pack() method Test");
      setLayout(new FlowLayout());
      setButton();
      pack(); // calling the pack() method
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   void setButton() {
      for(int i=1; i < 6; i++) {
         add(new JButton("Button" +i));
      }
   }
   public static void main(String args[]) {
      new PackMethodTest();
   }
}
PyQt5 QSpinBox – Setting step type

06 May, 2020
In this article we will see how we can set the step type to the spin box, there are two types of step types i.e default one which increment value normally and other is adaptive decimal. Adaptive decimal step means that the step size will continuously be adjusted to one power of ten below the current value i.e if value is 900 it get next increment will be off 10 for value equals to 1000 increment will be of 100. By default it is set to default step type although we can change.
In order to do this we will use setStepType method
Note : This feature was introduced in Qt 5.12. so lower versions don’t have this feature.
Syntax :spin_box.setStepType(QAbstractSpinBox.AdaptiveDecimalStepType)orspin_box.setStepType(1)
Argument : It takes QAbstractionSpinBox object or we can pass 1 i.e its value as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.Qt import PYQT_VERSION_STR  print("PyQt version:", PYQT_VERSION_STR)  import sys  class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 150, 40)          # setting range        self.spin.setRange(0, 10000)          # setting value        self.spin.setValue(950)          # setting step type        self.spin.setStepType(QAbstractSpinBox.AdaptiveDecimalStepType)            # creating label        label = QLabel(self)          # setting geometry to the label        label.setGeometry(100, 160, 200, 30)          # getting single step size        step = self.spin.singleStep()          # setting text to the label        label.setText("Step Size : " + str(step))  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Fetch specific values from array of objects in JavaScript?

Let’s say the following are our array of objects:
const details =
   [
      {
         employeeFirstName: "John",
         employeeLastName: "Doe"
      },
      {
         employeeFirstName: "David",
         employeeLastName: "Miller"
      },
      {
         employeeFirstName: "John",
         employeeLastName: "Smith"
      }
   ]
Following is the code to fetch specific values, in this case with first name “John” −
const details =
   [
      {
            employeeFirstName: "John",
            employeeLastName: "Doe"
      },
      {
         employeeFirstName: "David",
         employeeLastName: "Miller"
      },
      {
         employeeFirstName: "John",
         employeeLastName: "Smith"
      }
   ]
for (var index = 0; index < details.length; index++) {
   if (details[index].employeeFirstName === "John") {
      console.log("FirstName=" + details[index].employeeFirstName + " LastName= " + details[index].employeeLastName);
   }
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo223.js.
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo223.js
FirstName=John LastName= Doe
FirstName=John LastName= Smith
Change figure size and figure format in Matplotlib

Using the figsize attribute of figure(), we can change the figure size. To change the format of a figure, we can use the savefig method.
Store the figure size in the variable.
Store the figure size in the variable.
Create a new figure, or activate an existing figure, with given figure size.
Create a new figure, or activate an existing figure, with given figure size.
Plot the line using x.
Plot the line using x.
Set the image title with its size.
Set the image title with its size.
Save the figure using savefig() method.
Save the figure using savefig() method.
from matplotlib import pyplot as plt

figure_size = (10, 10)
plt.figure(figsize=figure_size)
x = [1, 2, 3]
plt.plot(x, x)
plt.title("Figure dimension is: {}".format(figure_size))
plt.savefig("imgae.png", format="png")
Python 3 - List extend() Method

The extend() method appends the contents of seq to list.
Following is the syntax for extend() method −
list.extend(seq)

seq − This is the  list of elements
This method does not return any value but add the content to existing list.
The following example shows the usage of extend() method.
#!/usr/bin/python3

list1 = ['physics', 'chemistry', 'maths']
list2 = list(range(5))     #creates list of numbers between 0-4
list1.extend(list2)
print ('Extended List :', list1)
When we run above program, it produces the following result −
Extended List :  ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How can I delete an item from an Object in MongoDB?

To delete an item from an object in MongoDB, use $unset. Let us create a collection with documents −
> db.demo467.insertOne(
... {
... _id:101,
... "Information":{"Name":"Chris"}
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo467.insertOne(
... {
... _id:102,
... "Information":{"Name":"David"}
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo467.find();
This will produce the following output −
{ "_id" : 101, "Information" : { "Name" : "Chris" } }
{ "_id" : 102, "Information" : { "Name" : "David" } }
Following is the query to delete an item from an Object −
> db.demo467.update({_id:102},{$unset: {"Information.Name":1}},{multi: true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo467.find();
This will produce the following output −
{ "_id" : 101, "Information" : { "Name" : "Chris" } }
{ "_id" : 102, "Information" : { } }
Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers

When it is required to create a class to get all the possible subsets of integers from a list, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations.
Below is a demonstration for the same −
 Live Demo
class get_subset:
   def sort_list(self, my_list):
      return self. subset_find([], sorted(my_list))
   def subset_find(self, curr, my_list):
      if my_list:
         return self. subset_find(curr, my_list[1:]) + self. subset_find(curr + [my_list[0]], my_list[1:])
      return [curr]
my_list = []
num_elem = int(input("Enter the number of elements in the list.. "))
for i in range(0,num_elem):
   elem=int(input("Enter the element.."))
   my_list.append(elem)
print("Subsets of the list are : ")
print(get_subset().sort_list(my_list))
Enter the number of elements in the list.. 3
Enter the element..45
Enter the element..12
Enter the element..67
Subsets of the list are :
[[], [67], [45], [45, 67], [12], [12, 67], [12, 45], [12, 45, 67]]
A class named ‘get_subset’ class is defined, that has functions like ‘sort_list’, and ‘subset_find’.
These are used to perform operations such as sort the list, and get all the possible subsets from the list data respectively.
An instance of this class is created.
The list data is entered, and operations are performed on it.
Relevant messages and output is displayed on the console.