code-rag-bench/online-tutorials huggingface dataset:
Implement a stack from a LinkedList in Java

A stack can be implemented using a LinkedList by managing the LinkedList as a stack. This is done by using a class Stack which contains some of the Stack methods such as push(), top(), pop() etc.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.LinkedList;
class Stack {
   private LinkedList l = new LinkedList();
   public void push(Object obj) {
     l.addFirst(obj);
   }
   public Object top() {
      return l.getFirst();
   }
   public Object pop() {
      return l.removeFirst();
   }
}
public class Demo {
   public static void main(String[] args) {
      Stack s = new Stack();
      s.push(5);
      s.push(1);
      s.push(3);
      s.push(9);
      s.push(7);
      System.out.println("The top element of the stack is: " + s.top());
      System.out.println("The stack element that is popped is: " + s.pop());
      System.out.println("The stack element that is popped is: " + s.pop());
      System.out.println("The top element of the stack is: " + s.top());
   }
}
The top element of the stack is: 7
The stack element that is popped is: 7
The stack element that is popped is: 9
The top element of the stack is: 3
Now let us understand the above program.
A class Stack is created which contains some of the Stack methods such as push(), top(), pop() etc. A code snippet which demonstrates this is as follows −
class Stack {
   private LinkedList l = new LinkedList();
   public void push(Object obj) {
      l.addFirst(obj);
   }
   public Object top() {
      return l.getFirst();
   }
   public Object pop() {
      return l.removeFirst();
   }
}
In the method main(), an object s is created of the class Stack. Then this is used to push elements into the stack, display the top element and pop elements from the stack. A code snippet which demonstrates this is as follows −
public static void main(String[] args) {
   Stack s = new Stack();
   s.push(5);
   s.push(1);
   s.push(3);
   s.push(9);
   s.push(7);
   System.out.println("The top element of the stack is: " + s.top());
   System.out.println("The stack element that is popped is: " + s.pop());
   System.out.println("The stack element that is popped is: " + s.pop());
   System.out.println("The top element of the stack is: " + s.top());
}
How to check if the file is empty using PowerShell?

To check if the file is empty using PowerShell, we can use the string method called IsNullorWhiteSpace(). This method provides result true if the file is empty or only contains the white spaces otherwise false.
For example, We have a test2.txt text file which has whitespaces.
[String]::IsNullOrWhiteSpace((Get-content C:\Test2.txt))
True
But if you have a file like CSV which contains few headers but the data is empty, in that case, Get-Content will show the wrong output because it will consider headers. For example,
[String]::IsNullOrWhiteSpace((Get-content C:\Temp\NewUsers.csv))
False

Because the file has headers.
PS C:\> Get-Content C:\Temp\NewUsers.csv Name,FirstName,Surname,EMPNumber,Country
In that case, we can use the Import-CSV command inside the brackets.
[String]::IsNullOrWhiteSpace((Import-Csv C:\Temp\NewUsers.csv))
True
Sort array of objects by string property value - JavaScript

Suppose, we have an array of Objects like this −
const arr = [
   { first_name: 'Lazslo', last_name: 'Jamf'     },
   { first_name: 'Pig',    last_name: 'Bodine'   },
   { first_name: 'Pirate', last_name: 'Prentice' }
];
We are required to write a JavaScript function that takes in one such array and sort this array according to the alphabetical value of the last_name key.
Following is the code −
const arr = [
   { first_name: 'Lazslo', last_name: 'Jamf' },
   { first_name: 'Pig', last_name: 'Bodine' },
   { first_name: 'Pirate', last_name: 'Prentice' }
];
const sortByLastName = arr => {
   arr.sort((a, b) => {
      return a.last_name.charCodeAt(0) - b.last_name.charCodeAt(0);
   });
};
sortByLastName(arr);
console.log(arr);
This will produce the following output on console −
[
   { first_name: 'Pig', last_name: 'Bodine' },
   { first_name: 'Lazslo', last_name: 'Jamf' },
   { first_name: 'Pirate', last_name: 'Prentice' }
]
Reading an image using Python OpenCv module

In OpenCv module,we can use the function cv2.imread() to read an image. When inputting the image path, the image should be in the working directory or a full path of image should be given.
cv2.IMREAD_COLOR − This function loads a color image and any transparency of image will be neglected. It is the default flag.
cv2.IMREAD_GRAYSCALE − This function loads image in grayscale mode
cv2.IMREAD_UNCHANGED − This function loads image as such including alpha channel
import numpy as np
import cv2
my_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg', 0)
cv2.imshow('image', my_img)
k = cv2.waitKey(0) & 0xFF
# wait for ESC key to exit
if k == 27:
   cv2.destroyAllWindows()
elif k == ord('s'):
   cv2.imwrite('C:/Users/TP/Desktop/poor/poverty_india_gray.jpg',my_img)
   cv2.destroyAllWindows()
import cv2
import numpy as np
import matplotlib.pyplot as plt
my_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg',cv2.IMREAD_GRAYSCALE)
cv2.imshow('image', my_img)
cv2.waitKey(0)
cv2.destoryAllWindows()
SHA in Python

In this tutorial, we are going to learn about the hashlib module that gives us different SHA.
(Secure Hash Algorithms) is set of cryptographic hash functions.
Let's install the module by typing the following command.
pip install hashlib
We can see the available algorithms in the hashlib module using algorithms_guaranteed set. Let's see them by running the following code.
 Live Demo
# importing the hashlib module
import hashlib
# printing available algorithms
print(hashlib.algorithms_guaranteed)
If you run the above code, then you will get the following result.
{'sha256', 'sha512', 'sha224', 'shake_256', 'blake2s', 'shake_128', 'sha384', 'sha3_384', 'sha3_512', 'sha3_224', 'md5', 'sha3_256', 'sha1', 'blake2b'}
Let's see an example on how to user sha256 algorithm.
 Live Demo
# importing the hashlib module
import hashlib
# initialinzing a string
# the string will be hashed using the 'sha256'
name = 'Tutorialspoint'
# convert the string to bytes using 'encode'
# hash functions only accepts encoded strings
encoded_name = name.encode()
# Now, pass the encoded_name to the **sha256** function
hashed_name = hashlib.sha256(encoded_name)
# we have hashed object
# we can't understand it
# print the hexadecimal version using 'hexdigest()' method
print("Object:", hashed_name)
print("Hexadecimal format:", hashed_name.hexdigest())
If you run the above code, then you will get the following result.
Object: <sha256 HASH object @ 0x000002A416E1BAE0>
Hexadecimal format: 447c2329228a452aa77102dc7d4eca0ee4c6d52a17e9c17408f8917e51e
3
You can use the remaining algorithms similar to the sha256. If you have any queries in the
tutorial, mention them in the comment section.
How to shade the regions between the curves in Matplotlib?

To shade the regions between curves, we can use the fill_between() method.
Initialize the variable n. Initiliize x and y data points using numpy.
Initialize the variable n. Initiliize x and y data points using numpy.
Create a figure and a set of subplots, fig and ax.
Create a figure and a set of subplots, fig and ax.
Plot the curve using plot method.
Plot the curve using plot method.
Use fill_between() method, fill the area between the two curves.
Use fill_between() method, fill the area between the two curves.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig, ax = plt.subplots()
ax.plot(X, Y, color='blue', alpha=1.0)
ax.fill_between(X, 0, Y, color='blue', alpha=.2)
plt.show()
How to enable / Disable Enhanced Protection Mode in Internet Explorer using PowerShell?

Internet Explorer (IE) supports the enhanced protection mode for more security of the browser and the same can be enabled/disabled using PowerShell. Let see when we can find this setting in IE.
Internet Explorer → Internet Options → Advanced → Enable Enhanced Protection Mode
We can modify this setting using PowerShell and for that registry settings need to be done. Registry value can be found under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main and the key name is Isolation for enhanced protection mode.
PMIL – To disable IE enhanced protection Mode
PMIL – To disable IE enhanced protection Mode
PMEM – To Enable IE enhanced protection mode
PMEM – To Enable IE enhanced protection mode
To make the changes using the script.
If there is no Isolation Key exists you can use the below command to create a new key and value.
New-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' `
   -Name Isolation -Value "PMEM" -ErrorAction Ignore -Verbose
If the Isolation key already exists then you just need to set the registry value. For example,
Set-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' `
   -Name Isolation -Value "PMEM" -ErrorAction Ignore -Verbose
If there is no Isolation Key exists you can use the below command to create a new key and value.
New-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' `
   -Name Isolation -Value "PMIL" -ErrorAction Ignore -Verbose
If the Isolation key already exists then you just need to set the registry value. For example,
Set-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' `
   -Name Isolation -Value "PMIL" -ErrorAction Ignore -Verbose
Import Modules From Another Folder in Python - GeeksforGeeks

17 Jun, 2021
In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder.
It can be done in two ways:
Using sys.path
Using PythonPath.
Create a module for demonstration:
File name: module0.py
Python3
def run():    print("Module 0 imported successfully")
sys.path: It is a built-in variable within the python sys module. It contains a list of directories that the interpreter will search in for the required modules.
Python3
import sys  # Prints the list of directories that the # interpreter will search for the required module. print(sys.path)
Output:
In this approach, Insert or Append the path of the directory containing the modules in sys.path.
Syntax:
sys.path.insert(0, path)
sys.path.append(path)
Example: Suppose we need to import the following modules from “Desktop\\Task\\modules” in “Desktop\\VScode\\Projects\\ImportModule\\main.py”.
Insert/Append the path to sys.path and import module0 present in the directory and call its run function.
Python3
import sys  # Insert the path of modules folder sys.path.insert(0, "C:\\Users\\anila\\Desktop\\Task\\modules")  # Import the module0 directly since # the current path is of modules.import module0  # Prints "Module0 imported successfully"module0.run()
Output:
PYTHONPATH : It is an environment variable which you can set to add additional directories where python will look for modules and packages.
Open a terminal or command prompt and enter the following command:
Syntax: set PYTHONPATH=path_to_module_folder
Add the path to PYTHONPATH and import module0 present in the directory and call its run function.
Below is the implementation:
Python3
# Import the module0 directly since # the current path is of modules.import module0  # Prints "Module0 imported successfully"module0.run()
Output:
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Difference between Dilation and Erosion - GeeksforGeeks

12 Aug, 2021
Dilation and Erosion are basic morphological processing operations that produce contrasting results when applied to either gray-scale or binary images.
Dilation: Dilation is the reverse process with regions growing out from their boundaries.Dilation is A XOR B.
Dilation is A XOR B.
Erosion: Erosion involves the removal of pixels ate the edges of the region.Erosion is just the dual of Dilation.
Erosion is just the dual of Dilation.
Both dilation and erosion are produced by the interaction of s set called a structuring element(SE). 
Difference between Dilation and Erosion:  
varshagumber28
MATLAB
Difference Between
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 IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Difference between SQL and NoSQL
Logical and Physical Address in Operating System
Difference between DDL and DML in DBMS
Difference between Prim's and Kruskal's algorithm for MST
Difference between Primary Key and Foreign Key
jQuery | select() with Examples - GeeksforGeeks

13 Feb, 2019
The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field.
Syntax:
$(selector).select(function);
Parameter: This method accepts single parameter function which is optional. Th function parameter will run after select method call.
Return Value: This method returns a notification when something is select.
Below example illustrates the select() method in jQuery:
Example:
<!DOCTYPE html><html>    <head>        <title>Select Method</title>        <script src=        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">        </script>                  <!-- JQuery code to show the working of this method -->        <script>            $(document).ready(function() {                $("input").select(function() {                    alert("Something was selected");                });            });        </script>        <style>            div {                width: 250px;                height: 40px;                padding: 20px;                border: 2px solid green;            }        </style>    </head>    <body>        <div>            <!-- select any thing from inside this field -->            <input type="text" value="GeeksforGeeks!">        </div>    </body></html>
Output:Before select anything !After selecting some letters or words !
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Python | Pandas MultiIndex.swaplevel() - GeeksforGeeks

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.swaplevel() function is used to swap levels of the MultiIndex. It swap level i with level j. Calling this method does not change the ordering of the values.
Syntax: MultiIndex.swaplevel(i=-2, j=-1)
Parameters :i : First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.j : Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.
Returns : A new MultiIndex
Example #1: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',                                      'Anthropology', 'Science'],                                              [88, 84, 98, 95]])  # Print the MultiIndexprint(midx)
Output :
Now let’s swap the 0th level with the 1st level of the MultiIndex.
# swap the levelsmidx.swaplevel(0, 1)
Output :As we can see in the output, the function has swapped the 0th level with the 1st level of the MultiIndex. Example #2: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Beagle', 'Sephard', 'Labrador', 'Retriever'],                                       [8, 4, 11, 3], ['A1', 'B1', 'A2', 'C1']])  # Print the MultiIndexprint(midx)
Output :
Now let’s swap the 0th level with the 2nd level of the MultiIndex.
# swap the levelsmidx.swaplevel(0, 2)
Output :As we can see in the output, the function has swapped the 0th level with the 2nd level of the MultiIndex.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
Replacing column value of a CSV file in Python - GeeksforGeeks

02 Sep, 2020
Let us see how we can replace the column value of a CSV file in Python. CSV file is nothing but a comma-delimited file.
Method 1: Using Native Python way 
Using replace() method, we can replace easily a text into another text.  In the below code, let us have an input CSV file as “csvfile.csv” and be opened in “read” mode. The join() method takes all lines of a CSV file in an iterable and joins them into one string. Then, we can use replace() method on the entire string and can perform single/multiple replacements. In the entire string, the given text is searched and replaced with the specified text.
Example: 
The input file will be:
Python3
# reading the CSV filetext = open("csvfile.csv", "r")  #join() method combines all contents of # csvfile.csv and formed as a stringtext = ''.join([i for i in text])   # search and replace the contentstext = text.replace("EmployeeName", "EmpName") text = text.replace("EmployeeNumber", "EmpNumber") text = text.replace("EmployeeDepartment", "EmpDepartment") text = text.replace("lined", "linked")   # output.csv is the output file opened in write modex = open("output.csv","w")  # all the replaced text is written in the output.csv filex.writelines(text)x.close()
Output:
Method 2: Using Pandas DataFrame
We can read the CSV file as a DataFrame and then apply the replace() method.
Python3
# importing the moduleimport pandas as pd     # making data frame from the csv file dataframe = pd.read_csv("csvfile1.csv")     # using the replace() methoddataframe.replace(to_replace ="Fashion",                  value = "Fashion industry",                   inplace = True)dataframe.replace(to_replace ="Food",                  value = "Food Industry",                   inplace = True)dataframe.replace(to_replace ="IT",                  value = "IT Industry",                   inplace = True)  # writing  the dataframe to another csv filedataframe.to_csv('outputfile.csv',                  index = False)
Output:
python-csv
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
How to dismiss the dialog with click on outside of the dialog?

This example demonstrate about how to dismiss the dialog with click on outside of the dialog
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"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/click"
      android:layout_width = "wrap_content"
      android:textSize = "30sp"
      android:layout_height = "wrap_content"
      android:text = "Click"/>
</LinearLayout>
In the above code, we have taken text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   TextView text;
   @TargetApi(Build.VERSION_CODES.LOLLIPOP)
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      text = findViewById(R.id.click);
      text.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showAlertDialog();
         }
      });
   }
   private void showAlertDialog() {
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
      alertDialog.setTitle("AlertDialog");
      alertDialog.setMessage("Sairamkrishna Mammahe do you wanna close it or not?");
      alertDialog.setIcon(R.drawable.logo);
      alertDialog.setPositiveButton("yes", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this,"you clicked on yes button",Toast.LENGTH_LONG).show();
         }
      });
      alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
         @Override
            public void onClick(DialogInterface dialog, int which) {
         }
      });
      AlertDialog alert = alertDialog.create();
      alert.setCanceledOnTouchOutside(false);
      alert.show();
   }
}
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 Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Now click on textview to open Alert Dialog.
Click here to download the project code
Large input field with Bootstrap

Use the .input-lg class to set large input field in Bootstrap.
You can try to run the following code to implement .input-lg class −
Live Demo
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Bootstrap Example</title>
      <meta charset = "utf-8">
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Candidate Profile</h2>
         <form>
            <div class = "form-group">
               <label for = "sel2">What is your job profile?</label>
               <select class = "form-control input-lg" id = "sel2">
                  <option>Programmer</option>
                  <option>Web Developer</option>
                  <option>DBA</option>
                  <option>Support Engineer</option>
               </select>
            </div>
            <div class = "form-group">
               <label for = "sel3">Educational Qualifcation</label>
               <select class = "form-control input-sm" id = "sel3">
                  <option>Undergraduate</option>
                  <option>Graduate</option>
                  <option>Post-Graduate</option>
               </select>
            </div>
         </form>
      </div>
   </body>
</html>
Set Date value in Java HashMap?

Create a Calendar instance and Date object −
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
Now, create a HashMap and store Date value −
LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>();
hashMap.put("year", cal.get(Calendar.YEAR));
hashMap.put("month", cal.get(Calendar.MONTH));
hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH));
 Live Demo
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
public class Demo {
   public static void main(String[] argv) {
      Calendar cal = Calendar.getInstance();
      Date date = new Date();
      System.out.println("Date = "+date);
      cal.setTime(date);
      LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>();
      hashMap.put("year", cal.get(Calendar.YEAR));
      hashMap.put("month", cal.get(Calendar.MONTH));
      hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH));
      System.out.println("HashMap (Date) = "+hashMap);
      hashMap.put("hour", cal.get(Calendar.HOUR_OF_DAY));
      hashMap.put("minute", cal.get(Calendar.MINUTE));
      hashMap.put("second", cal.get(Calendar.SECOND));
      hashMap.put("millisecond", cal.get(Calendar.MILLISECOND));
      System.out.println("HashMap (DateTime) = "+hashMap);
   }
}
Date = Fri Apr 19 17:45:24 IST 2019
HashMap (Date) = {year=2019, month=3, day=19}
HashMap (DateTime) = {year=2019, month=3, day=19, hour=17, minute=45, second=24, millisecond=98}
Extract particular element in MongoDB within a Nested Array?

To extract the particular element in MongoDB, you can use $elemMatch operator. Let us first create a collection with documents −
> db.particularElementDemo.insertOne(
   {
      "GroupId" :"Group-1",
      "UserDetails" : [
         {
            "UserName" : "John",
            "UserOtherDetails" : [
               {
                  "UserEmailId" : "John123@gmail.com",
                  "UserFriendName" : [
                     {
                        "Name" : "Chris"
                     }
                  ]
               },
               {
                  "UserEmailId" : "John22@hotmail.com",
                  "UserFriendName" : [
                     {
                        "Name" : "Robert"
                     }
                  ]
               }
            ]
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.particularElementDemo.find().pretty();
{
   "_id" : 100,
   "GroupId" : "Group-1",
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserOtherDetails" : [
            {
               "UserEmailId" : "John123@gmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Chris"
                  }
               ]
            },
            {
               "UserEmailId" : "John22@hotmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Robert"
                  }
               ]
            }
         ]
      }
   ]
}
Display all documents from a collection with the help of find() method −
> db.particularElementDemo.find().pretty();
This will produce the following output −
{
   "_id" : 100,
   "GroupId" : "Group-1",
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserOtherDetails" : [
            {
               "UserEmailId" : "John123@gmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Chris"
                  }
               ]
            },
            {
               "UserEmailId" : "John22@hotmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Robert"
                  }
               ]
            }
         ]
      }
   ]
}
Following is the query to extract particular element in MongoDB in nested arrays −
> db.particularElementDemo.find(
   {
      'UserDetails':{
         $elemMatch:{
            'UserOtherDetails':{
               $elemMatch:{
                  'UserFriendName':{ $elemMatch: {"Name" : "Robert" } }
               }
            }
         }
      }
   },{"UserDetails.UserOtherDetails.UserFriendName.Name":1}
);
This will produce the following output −
{ "_id" : 100, "UserDetails" : [ { "UserOtherDetails" : [ { "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }
isinf() function in C++

In this article we will be discussing the isinf() function in C++, its syntax, working and what will be its return value.
isinf() is an inbuilt function in C++ which comes under header file, the function is used to check whether the variable passed in it is infinity or not, no matter if the number is negative infinity or positive infinity. If the number is infinite the function returns a non-zero value (true) and if it is not then it passes zero (false). Also if the number is NAN then also the function will return 0.
bool isinf(float n);
or
bool isinf(double n);

or
bool isinf(long double n);
This function accepts only one floating point number.
Function returns boolean value, 0 for false(not infinity) and 1 if it is true(infinite).
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   float a = 0.0, b = 10.0;
   isinf(a/b)?cout<<"\nInfinte":cout<<"\nFinite"; //check the number is infinte or finite
   isinf(b/a)?cout<<"\nInfinite":cout<<"\nFinite";
}
If we run the above code it will generate the following output −
Finite
Infinite
 Live Demo
#include <iostream>
#include <cmath>
using namespace std; int main() {
   float a = 0.0;
   cout<<isinf(a);
   cout<<isinf(sqrt(-1.0));
}
If we run the above code it will generate the following output −
0 0
Normality? How do we check that?. Is your data normal and how to check... | by Harshdeep Singh | Towards Data Science

Before I mention a couple of ways as to how to check normality, let me tell why “your data” being “normal” is good news.
Normal distribution has certain properties which others don’t:
It has the infamous bell shape curve which is symmetric around the mean and makes it an appealing choice for linear regression models.and then because of the Central Limit Theorem, for large number of samples, normal distribution can approximate other known distributions.and also the mean, median and mode are equal.
It has the infamous bell shape curve which is symmetric around the mean and makes it an appealing choice for linear regression models.
and then because of the Central Limit Theorem, for large number of samples, normal distribution can approximate other known distributions.
and also the mean, median and mode are equal.
The above mentioned properties make normal distributions more analytically appealing and solvable.
But how do we check the normality? There are different tests which one could use depending upon how much data is available to you — sometimes you might have a few samples or a lot of samples and hence it depends on the situation!
Before I describe the ways to check normality, let’s have an example dataset which has a normal distribution with a mean of 0.05 and variance of 0.9.
>>> import numpy as np>>> mu, sigma = 0.05, 0.90>>> data = np.random.normal(mu, sigma, 10000)
a.) The first kind of test could be to “compare the data” with a given distribution. Examples of such test can be: Lilliefors test (when the estimated parameters are known), Andrew-Darling test etc.
We will have a look at the Lilliefors test which calculate the distance between the empirical distribution function of your data with the CDF of the reference distribution. Please note, that this is similar to the Kolmogorov-Smirnov test but with parameters estimated.
>>> import statsmodels.api as sm>>> ## Return KS-distance, p-value>>> ks, p = sm.stats.lilliefors(data)>>> print(p)0.66190841161592895
Now since the p-value is higher than the threshold (generally, 0.05), we say that the null hypothesis is true. In other words, this means that data comes from the normal distribution.
b.) The second kind of test would be to “look at the descriptive statistics” of your data such as the kurtosis (how the tails are different from standard normal distribution), or skewness (measuring the asymmetry around the mean), or a test which combines both kurtosis and skewness called as the omnibus test.
>>> from scipy import stats>>> s, p = stats.normaltest(data)>>> print(p)0.6246248916944541
which similar to the observation we got from (a) and hence we can say that both test predict that the data is from the normal distribution.
If you know of any other common ways to check the normality of the data, please mention it down in the comments.
I hope you find this article interesting and useful.
How to add the slider to a menu item in JavaFX?

JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the number values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum, and initial values of the slider.
In JavaFX you can create a slider by instantiating the javafx.scene.control.Slider class.
A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class.
A menu item is an option in the menu it is represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it.
The MenuItem class has a property named graphic this is of the type Node; this specifies the optional graphic for the current menu-item. You can set the value to this property using the setGraphic() method.
To add slider as a menu item create a slider object, invoke the setGrapic() method by passing this object as a parameter.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Slider;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SliderAsMenuItem extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a slider
      Slider slider = new Slider(0, 100, 0);
      slider.setShowTickLabels(true);
      slider.setShowTickMarks(true);
      slider.setMajorTickUnit(25);
      slider.setBlockIncrement(10);
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating menu item
      MenuItem item = new MenuItem();
      //Setting slider as a menu item
      item.setGraphic(slider);
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(item);
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      menuBar.setTranslateX(200);
      menuBar.setTranslateY(20);
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Menu");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Python program to check if two lists have at least one common element

In this problem we use two user input list. Our task is to check that there is any common element or not. We use very simple traversing technique, traverse both the list and check the every element of first list and second list.
Input : A = [10, 20, 30, 50]
        B = [90, 80, 30, 10, 3]
Output : FOUND
Input : A = [10, 20, 30, 50]
        B = [100,200,300,500]
Output : NOT FOUND

commonelement(A,B)
/* A and B are two user input list */
Step 1: First use one third variable c which is display the result.
Step 2: Traverse both the list and compare every element of the first list with every element of the second list.
Step 3: If common element is found then c display FOUND otherwise display NOT FOUND.

# Python program to check  
# if two lists have at-least  
# one element common 
# using traversal of list 
  
def commonelement(A, B): 
   c = "NOT FOUND"

   # traverse in the 1st list 
   for i in A: 
      # traverse in the 2nd list 
      for j in B: 
         # if one common 
         if i == j: 
            c="FOUND"
            return c  
    return c 

# Driver code
A=list()
B=list()
n1=int(input("Enter the size of the first List ::"))
print("Enter the Element of first List ::")
for i in range(int(n1)):
   k=int(input(""))
   A.append(k)
n2=int(input("Enter the size of the second List ::"))
print("Enter the Element of second List ::")
for i in range(int(n2)):
   k=int(input(""))
   B.append(k)

print("Display Result ::",commonelement(A, B)) 
Enter the size of the first List ::4
Enter the Element of first List ::
2
1
4
9
Enter the size of the second List ::5
Enter the Element of second List ::
9
90
4
89
67
Display Result :: FOUND

Enter the size of the first List ::4
Enter the Element of first List ::
67
89
45
23
Enter the size of the second List ::4
Enter the Element of second List ::
1
2
3
4
Display Result :: NOT FOUND
How to change the password in MongoDB for existing user?

To change the password in MongoDB for existing user, you can use changeUserPassword(). Following is the syntax
db.changeUserPassword("yourExistingUserName", "yourPassword");
Let us first switch the database to admin. Following is the syntax
> use admin
This will produce the following output
switched to db admin
Now, display users from the database. Following is the query
> db.getUsers();
This will produce the following output
[
   {
      "_id" : "admin.John",
      "user" : "John",
      "db" : "admin",
      "roles" : [
         {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   }
]
Following is the query to change the password for user “John”
> db.changeUserPassword("John", "123456");
Now the password has been changed with value “123456”.
C program to find the sum of arithmetic progression series

Find the sum of an arithmetic progression series, where the user has to enter first number, total number of elements and the common difference.
Arithmetic Progression (A.P.) is a series of numbers in which the difference of any two consecutive numbers is always the same. Here, total number of elements is mentioned as Tn.
Sum of A.P. Series: Sn = n/2(2a + (n – 1) d)
Tn term of A.P. Series: Tn = a + (n – 1) d
Refer an algorithm given below to find the arithmetic progression.
Step 1: Declare variables.
Step 2: Initialize sum=0
Step 3: Enter first number of series at runtime.
Step 4: Enter total number of series at runtime.
Step 5: Enter the common difference at runtime.
Step 6: Compute sum by using the formula given below.
   sum = (num * (2 * a + (num - 1) * diff)) / 2
Step 7: Compute tn by using the formula given below.
   tn = a + (num - 1) * diff
Step 8: For loop
   i = a; i <= tn; i = i + diff
   i. if(i != tn)
      printf("%d + ", i);
   ii. Else,
      printf("%d = %d", i, sum);
Step 9: Print new line
Following is the C Program to find the sum of arithmetic progression series−
 Live Demo
#include <stdio.h>
int main() {
   int a, num, diff, tn, i;
   int sum = 0;
   printf(" enter 1st no of series: ");
   scanf("%d", &a);
   printf(" enter total no's in series: ");
   scanf("%d", &num);
   printf("enter Common Difference: ");
   scanf("%d", &diff);
   sum = (num * (2 * a + (num - 1) * diff)) / 2;
   tn = a + (num - 1) * diff;
   printf("\n sum of A.P series is : ");
   for(i = a; i <= tn; i = i + diff){
      if(i != tn)
         printf("%d + ", i);
      else
         printf("%d = %d", i, sum);
   }
   printf("\n");
   return 0;
}
When the above program is executed, it produces the following result −
enter 1st no of series: 3
enter total no's in series: 10
enter Common Difference: 5
sum of A.P series is: 3 + 8 + 13 + 18 + 23 + 28 + 33 + 38 + 43 + 48 = 255
enter 1st no of series: 2
enter total no's in series: 15
enter Common Difference: 10
sum of A.P series is: 2 + 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + 92 + 102 + 112 + 122 + 132 + 142 = 1080
How to declare an Array Variables in Java?

You can declare an array just like a variable −
int myArray[];
You can create an array just like an object using the new keyword −
myArray = new int[5];
You can initialize the array by assigning values to all the elements one by one using the index −
myArray [0] = 101;
myArray [1] = 102;
You can access the array element using the index values −
System.out.println("The first element of the array is: " + myArray [0]);
System.out.println("The first element of the array is: " + myArray [1]);
Alternatively, you can create and initialize an array using the flower braces ({ }):
Int [] myArray = {10, 20, 30, 40, 50}
Prototype - toObject() Method

This method returns a cloned, vanilla object.
hash.toObject();

Returns a cloned, vanilla object.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var h = new Hash({ a: 'apple', b: 'banana', c: 'coconut' });
            var obj = h.toObject();
            alert( "Object.inspect(h) : " + Object.inspect(h) );
            alert( "Object.inspect(obj) : " + Object.inspect(obj) );
            alert( "h.get('a') : " + h.get('a') );
            alert( "Object.keys(obj) : " + Object.keys(obj) );
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>
Click the button to see the result.

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
How to get items with a specific value from documents using MongoDB shell?

To get items with a specific value, simply use find(). Let us create a collection with documents −
> db.demo563.insertOne({"Name":"Chris","Age":21,"isMarried":true}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f546c54b4472ed3e8e878")
}
> db.demo563.insertOne({"Name":"Bob","Age":23,"isMarried":false}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f547854b4472ed3e8e879")
}
> db.demo563.insertOne({"Name":"Carol","Age":23,"isMarried":true}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f548b54b4472ed3e8e87a")
}
> db.demo563.insertOne({"Name":"Mike","Age":21,"isMarried":true}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f549454b4472ed3e8e87b")
}
Display all documents from a collection with the help of find() method −
> db.demo563.find();
This will produce the following output −
{ "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true }
{ "_id" : ObjectId("5e8f547854b4472ed3e8e879"), "Name" : "Bob", "Age" : 23, "isMarried" : false }
{ "_id" : ObjectId("5e8f548b54b4472ed3e8e87a"), "Name" : "Carol", "Age" : 23, "isMarried" : true }
{ "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }
Following is the query to get items from documents using MongoDB shell
> db.demo563.find({Age:21},{isMarried:true,Name:1,Age:1});
This will produce the following output −
{ "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true }
{ "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }
C library macro - setjmp()

The C library macro int setjmp(jmp_buf environment), saves the current environment into the variable environment for later use by the function longjmp(). If this macro returns directly from the macro invocation, it returns zero but if it returns from a longjmp() function call, then it returns the value passed to longjmp as a second argument.
Following is the declaration for setjmp() macro.
int setjmp(jmp_buf environment)
environment − This is the object of type jmp_buf where the environment information is stored.
environment − This is the object of type jmp_buf where the environment information is stored.
This macro may return more than once. First time, on its direct invocation, it always returns zero. When longjmp is called with the information set to the environment, the macro returns again; now it returns the value passed to longjmp as second argument.
The following example shows the usage of setjmp() macro.
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

int main () {
   int val;
   jmp_buf env_buffer;

   /* save calling environment for longjmp */
   val = setjmp( env_buffer );
   
   if( val != 0 ) {
      printf("Returned from a longjmp() with value = %s\n", val);
      exit(0);
   }
   
   printf("Jump function call\n");
   jmpfunction( env_buffer );
   
   return(0);
}

void jmpfunction(jmp_buf env_buf) {
   longjmp(env_buf, "tutorialspoint.com");
}
Let us compile and run the above program, this will produce the following result −
Jump function call
Returned from a longjmp() with value = tutorialspoint.com


    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