code-rag-bench/online-tutorials huggingface dataset:
How to change Pagefile settings using PowerShell?

To change the pagefile settings, we will divide this into multiple sections. First, when Pagefile is
automatically managed, we can’t modify the settings so we need to remove that box. In GUI that box
can be unchecked in Virtual memory settings.
Code to uncheck the above box.
$pagefile = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges
$pagefile.AutomaticManagedPagefile = $false
$pagefile.put() | Out-Null
So once the above code is executed, other fields will be enabled. We now need to Customize the size of
the pagefile in the below image by providing Initial and Maximum size using PowerShell.
Here we have already the pagefile on the C: while on the E: there is no pagefile set. First, we will set the pagefile on C Drive.
$pagefileset = Get-WmiObject Win32_pagefilesetting
$pagefileset.InitialSize = 1024
$pagefileset.MaximumSize = 2048
$pagefileset.Put() | Out-Null
Once you run the above command and check the pagefile settings, it will be customized on C Drive. You
may need to reboot the system after setting the pagefile.
PS C:\> Gwmi win32_Pagefilesetting | Select Name, InitialSize, MaximumSize
Name             InitialSize   MaximumSize
----             -----------   -----------
C:\pagefile.sys  1024          2048
If you have another scenario, like setting up pagefile on the different drive for example in the above image we have E: as well. If there is no pagefile set on the drive then we need to set WMI instance for it.
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name="E:\pagefile.sys";
InitialSize = 0; MaximumSize = 0} -EnableAllPrivileges | Out-Null
We have now set the pagefile on E: and it is system managed.
PS C:\> Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}
MaximumSize        Name     Caption
-----------        ----     -------
0 E:\pagefile.sys  E:\ 'pagefile.sys'
If there are multiple pagefiles on the system and if we need to customize the size to the specific drive, we need to filter out the drive. In this case, we need to customize on E: so, we can filter this pagefile and modify settings.
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}
$pagefileset.InitialSize = 1024
$pagefileset.MaximumSize = 2048
$pagefileset.Put() | Out-Null
The size of the pagefile is now customized on E:
Python Program to Convert Celsius To Fahrenheit

24 Oct, 2021
Given the temperature in degree Celsius. the task is to convert the value in the Fahrenheit scale and display it. Examples :  
Input :
37 
Output :
37.00 Celsius is: 98.60 Fahrenheit

Input :
40
Output :
40.00 Celsius is equivalent to: 104.00 Fahrenheit
Approach: Take Celsius temperature as input from the user, apply the conversion formula of Fahrenheit from Celsius, and display it. The relationship between the Celsius scale and the Fahrenheit scale is given by :     Below is the implementation. 
Python3
# Temperature in celsius degreecelsius = 40 # Converting the temperature to# fehrenheit using the above# mentioned formulafahrenheit = (celsius * 1.8) + 32 # printing the resultprint('%.2f Celsius is equivalent to: %.2f Fahrenheit'      %(celsius, fahrenheit))
Output: 
40.00 Celsius is equivalent to: 104.00 Fahrenheit
 
surinderdawra388
school-programming
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to create a hyperlink for values from an array in Angular 8?

11 Sep, 2020
Introduction:In angular 8, we can create hyperlinks for all the values that are present in the array using *ngFor.
Approach:1) First declare and initialize array in .ts file.2) Then use *ngFor directive for iterating through the array.3) Using this *ngFor directive in .html file, we can use it as per the requirement.4) Once the implementation is done then the serve the project.
Syntax:Syntax for starting the project.
ng serve --open
Implementation by code:
app.component.html: 
<div *ngFor = "let item of data">   <a [attr.href]="item.url">   {{item.name}}  </a></div>
app.component.ts: 
import { Component } from '@angular/core';@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [   `a{     text-decoration: none;     color:black;     cursor: pointer     }  `  ]})export class AppComponent  {    data=[    {      name:"GeeksForGeeks",      url:"www.geeksforgeeks.org"    },    {      name:"Google",      url:"www.google.com"    },    {      name:"HackerRank",      url:"www.hackerrank.com"    }  ]    }
Output: 
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced C++ with boost library

C++ boost libraries are widely useful library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++.
Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily.
At first we are multiplying two huge number using boost library.
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int128_t large_product(long long n1, long long n2) {
   int128_t ans = (int128_t) n1 * n2;
   return ans;
}
int main() {
   long long num1 = 98745636214564698;
   long long num2 = 7459874565236544789;
   cout >> "Product of ">> num1 >> " * ">> num2 >> " = " >>
   large_product(num1,num2);
}
Product of 98745636214564698 * 7459874565236544789 =
736630060025131838840151335215258722
Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime.
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
cpp_int large_fact(int num) {
   cpp_int fact = 1;
   for (int i=num; i>1; --i)
      fact *= i;
   return fact;
}
int main() {
   cout >> "Factorial of 50: " >> large_fact(50) >> endl;
}
Factorial of 50:
30414093201713378043612608166064768844377641568960512000000000000
Using multi-precision float, we can get precision up to 50 and 100 decimal places. For this we can use cpp_float_50 or cpp_dec_float_100 respectively. Let us see the example to get the better idea.
#include<iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
using boost::multiprecision::cpp_dec_float_50;
using namespace std;
template<typename T>
inline T circle_area(T r) {
   // pi is predefined constant having value
   using boost::math::constants::pi;
   return pi<T>() * r * r;
}
main() {
   float f_rad = 243.0/ 100;
   float f_area = circle_area(f_rad);
   double d_rad = 243.0 / 100;
   double d_area = circle_area(d_rad);
   cpp_dec_float_50 rad_mp = 243.0 / 100;
   cpp_dec_float_50 area_mp = circle_area(rad_mp);
   cout >> "Float: " >> setprecision(numeric_limits<float>::digits10) >> f_area >>
   endl;
   // Double area
   cout >> "Double: " >>setprecision(numeric_limits<double>::digits10) >> d_area
   >> endl;
   // Area by using Boost Multiprecision
   cout >> "Boost Multiprecision Res: " >>
   setprecision(numeric_limits<cpp_dec_float_50>::digits10) >> area_mp >> endl;
}
Float: 18.5508
Double: 18.5507904601824
Boost Multiprecision Res:
18.550790460182372534747952560288165408707655564121
Adding JSON field in Django models

In this article, we will see how to add JSON fields to our Django models. JSON is a simple format to store data in key and value format. It is written in curly braces. Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases.
First create a Django project and an app. Please do all the basic things, like adding app in INSTALLED_APPS and setting up urls, making a basic model and render its form in an HTML file.
Install the django-jsonfield package −
pip install django-jsonfield
Now, let's create a model in models.py, for example −
import jsonfield
from django.db import models

# Create your models here.

class StudentData(models.Model):
   name=models.CharField(max_length=100)
   standard=models.CharField(max_length=100)
   section=models.CharField(max_length=100)
   the_json = jsonfield.JSONField()
In admin.py, add the following lines −
from django.contrib import admin

from .models import StudentData

admin.site.register(StudentData)
We created a model here which has four fields, one of it is our thirdparty JSON field.
Now, run these commands −
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
These commands will create the table and the last command will create an admin user for you.
Now, you are all done.
Go to http://127.0.0.1/admin/ and go to your model admin, then add an instance, you will see a field like this −
JavaScript Page Refresh

You can refresh a web page using JavaScript location.reload method. This code can be called automatically upon an event or simply when the user clicks on a link. If you want to refresh a web page using a mouse click, then you can use the following code −
<a href="javascript:location.reload(true)">Refresh Page</a>

To understand it in better way you can Refresh Page.
You can also use JavaScript to refresh the page automatically after a given time period. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.
Try the following example. It shows how to refresh a page after every 5 seconds. You can change this time as per your requirement.
<html>
   <head>
      
      <script type = "text/JavaScript">
         <!--
            function AutoRefresh( t ) {
               setTimeout("location.reload(true);", t);
            }
         //-->
      </script>
      
   </head>
   
   <body onload = "JavaScript:AutoRefresh(5000);">
      <p>This page will refresh every 5 seconds.</p>
   </body>
   
</html>
This page will refresh every 5 seconds.


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Counting How Many Numbers Are Smaller Than the Current Number in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers.
The function should construct a new array based on the input array.
Each corresponding element of the new array should be the number of elements that are smaller in the original array than that corresponding element.
For example −
If the input array is −
const arr = [2, 7, 3, 1, 56, 4, 7, 8];
Then the output array should be −
const output = [1, 4, 2, 0, 7, 3, 4, 6 ];
Following is the code −
const arr = [2, 7, 3, 1, 56, 4, 7, 8];
const smallerThanCurrent = (arr = []) => {
   let { length } = arr;
   let res = Array(length).fill(0);
   for (let i = 0; i < length; i++){
      for (let j = 0; j < length; ++j){
         if (i != j && arr[i] > arr[j]){
            ++res[i];
         };
      };
   };
   return res;
};
console.log(smallerThanCurrent(arr));
Following is the console output
[
   1, 4, 2, 0,

   7, 3, 4, 6
]
How to find and replace the word in a text file using PowerShell?

To search for the word in PowerShell and replace it in the file we will use the string operation. In fact, the Get-Content command in PowerShell is used to read almost any type of file content. In this article, we are considering one text file as shown below.
Get-Content C:\Temp\TestFile.txt
PS C:\> Get-Content C:\Temp\TestFile.txt
# In case of linux, networkInterface names are of the form eth*
# In Windows, please use the network full name from Device Manager
networkInterfaces: ["Microsoft Hyper-V Network Adapter"
]

overrideMetricsUsingScriptFile: false

scriptTimeoutInSec: 60

scriptFiles:
- osType: windows
filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat
- osType: unixBase
filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh
The above output is the content of the file and we are going to work with it. We need to find the NetWorkMonitor word and replace it with “Active”. Please note the above file is the text file so we don’t need to convert it to the string but if there are any other extensions you may need to convert the output to a string using .ToString() command or Out-String method before performing any operation.
Now, we will find the requested string first, and let’s check how many lines we need to replace using Select-String cmdlet.
(Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"
PS C:\> (Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"
   filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat
   filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh
We found out there are two lines that have the “NetworkMonitor” word. We need to replace that word with the following command. You can also store Get-Content output in a variable and perform operation on it.
(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"
PS C:\> (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"
# In case of linux, networkInterface names are of the form eth*
# In Windows, please use the network full name from Device Manager
networkInterfaces: ["Microsoft Hyper-V Network Adapter"
]

overrideMetricsUsingScriptFile: false

scriptTimeoutInSec: 60

scriptFiles:
- osType: windows
filePath: monitors/Active/scripts/windows-metrics.bat
- osType: unixBase
filePath: monitors/Active/scripts/unix-base-metrics.sh
The above command replaced the file content but it is not stored yet so to save the updated file, we will use the Set-Content and the final code would be,
(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" | Set-Content
C:\Temp\Testfile.txt -Verbos
You can also choose a different path to save the file. If the file is read-only then use -Force parameter with Set-Content cmdlet.
How can I delete all cookies with JavaScript?

To delete all cookies with JavaScript, you can try to run the following code. Here, we’re using an array and the split() method to get all the cookies and finally delete them
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script>
         var num = 1;
         function addCookie(){
            document.cookie = num+" = "+num;
            num++;
         }
         function listCookies(){
            var result = document.cookie;
            document.getElementById("list").innerHTML = result;
         }
         function removeCookies() {
            var res = document.cookie;
            var multiple = res.split(";");
            for(var i = 0; i < multiple.length; i++) {
               var key = multiple[i].split("=");
               document.cookie = key[0]+" =; expires = Thu, 01 Jan 1970 00:00:00 UTC";
            }
         }
      </script>
   </head>
   <body>
      <button onclick = 'addCookie()'>ADD</button><br>
      <button onclick = 'listCookies()'>LIST COOKIES</button><br>
      <button onclick = 'removeCookies()'>REMOVE</button>
      <h1>Cookies List</h1>
      <p id = "list"></p>
   </body>
</html>
Python - tensorflow.boolean_mask() method - GeeksforGeeks

25 Aug, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. boolean_mask() is method used to apply boolean mask to a Tensor.
Syntax: tensorflow.boolean_mask(tensor, mask, axis, name)
Parameters:
tensor: It’s a N-dimensional input tensor.
mask: It’s a boolean tensor with k-dimensions where k<=N and k  is know statically.
axis: It’s a 0-dimensional tensor which represents the axis from which mask should be applied. Default value for axis is zero and k+axis<=N.
name: It’s an optional parameter that defines the name for the operation.
Return: It returns (N-K+1)-dimensional tensor which have the values that are populated against the True values in mask.  
Example 1: In this example input is 1-D.
Python3
# importing the libraryimport tensorflow as tf # initializing the inputstensor = [1,2,3]mask = [False, True, True] # printing the inputprint('Tensor: ',tensor)print('Mask: ',mask) # applying the maskresult = tf.boolean_mask(tensor, mask) # printing the resultprint('Result: ',result)
Output:
Tensor:  [1, 2, 3]
Mask:  [False, True, True]
Result:  tf.Tensor([2 3], shape=(2,), dtype=int32)
Example 2: In this example 2-D input is taken.
Python3
# importing the libraryimport tensorflow as tf # initializing the inputstensor = [[1, 2], [10, 14], [9, 7]]mask = [False, True, True] # printing the inputprint('Tensor: ',tensor)print('Mask: ',mask) # applying the maskresult = tf.boolean_mask(tensor, mask) # printing the resultprint('Result: ',result)
Output:
Tensor:  [[1, 2], [10, 14], [9, 7]]
Mask:  [False, True, True]
Result:  tf.Tensor(
[[10 14]
 [ 9  7]], shape=(2, 2), dtype=int32)
clintra
Python-Tensorflow
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()
Installation of Wpscan Tool in Kali Linux - GeeksforGeeks

24 Dec, 2020
Wpscan (WordPress vulnerability Scanner) is a black box WordPress vulnerability scanner. Wpscan is used to scan remote WordPress installations or websites to find security issues. WordPress can also be used to enumerate WordPress plugins and themes and brute-force logins. Approximately 35% of the internet runs on WordPress, WordPress is a free content management system. Which is used to build and maintain websites). Making a website using WordPress is very easy and absolutely free of cost, that’s why it is widely used. With the increase in the WordPress market, its security becoming a big concern for creators and users. Over 8% of internet breakability is found on WordPress websites. There are many WordPress vulnerability scanners available in the market like SUCURI(It is a Security website that protects your website from hackers, malware, DDoS, and blacklists), and WPScan(It is the scanner to scan your WordPress websites for vulnerable plugins, themes, and security misconfigurations).
Installation of Wpscan tool: Usually Wpscan tool comes pre-installed with Kali Linux but, if we need to install it we can run the following command :
1. We can install Git in Kali Linux by the below command
sudo apt-get install git
2. Once Git is installed, we need to fix Kali Linux dependencies for the latest Ruby development environment. Type below command in terminal
sudo apt-get install git ruby ruby-dev libcurl4-openssl-dev m
3. Now we can install WPScan tool on Kali Linux, by running the below command in the terminal.
git clone http://github.com/wpscanteam/wpscan.git
4. Once the download is completed, let change our directory to WPscan directory, by following the below command.
cd wpscan
5. Bundler is required to use the WPscan tool. WPScan is a ruby based application that uses ‘Gems’ as part of the programming language. Bundler will help keep WPScan and all of its dependencies updated effectively. We can install bundler in Kali Linux by running the below command in the WPScan directory :
sudo gem install bundler && bundle install --without test
Kali-Linux
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Logger setLevel() method in Java with Examples - GeeksforGeeks

26 Mar, 2019
setLevel() method of a Logger class used to set the log level to describe which message levels will be logged by this logger. The level we want to set is passed as a parameter. Message levels lower than passed log level value will be discarded by the logger. The level value Level.OFF can be used to turn off logging.
Log Levels: The log levels control the logging details. They determine the extent to which depth the log files are generated. Each level is associated with a numeric value and there are 7 basic log levels and 2 special ones. We need to specify the desired level of logging every time, we seek to interact with the log system. To know more about Log Levels, refer this Log Levels in Logging.
Syntax:
public void setLevel(Level newLevel)
              throws SecurityException

Parameters: This method accepts one parameter newLevel which represents the new value for the log level.
Return value: This method returns nothing.
Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”).
Below programs illustrate the setLevel() method:Program 1:
// Java program to demonstrate// Logger.setLevel() method  import java.util.logging.*;  public class GFG {      public static void main(String[] args)        throws SecurityException    {          // Create a logger        Logger logger            = Logger.getLogger(                GFG.class.getName());          // Set log levels        logger.setLevel(Level.FINEST);          // Print log level        System.out.println("Log Level = "                           + logger.getLevel());    }}
Output:The output printed on console of Eclipse is shown below-
Program 2:
// Java program to demonstrate// Logger.setLevel() method  import java.util.logging.*;  public class GFG {      public static void main(String[] args)        throws SecurityException    {          // Create a logger        Logger logger            = Logger.getLogger(                GFG.class.getName());          // Set log levels        logger.setLevel(Level.WARNING);          // Print log level        System.out.println("Log Level = "                           + logger.getLevel());    }}
Output:The output printed on console output is shown below-
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#setLevel(java.util.logging.Level)
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Python Program for nth Catalan Number

13 Jun, 2022
Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like the following.
1) Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).
2) Count the number of possible Binary Search Trees with n keys (See this) 
See this for more applications. 
The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ...
Recursive Solution 
Catalan numbers satisfy the following recursive formula. 
Following is the implementation of above recursive formula.  
Python3
# A recursive function to find nth catalan numberdef catalan(n):    # Base Case    if n <= 1:        return 1     # Catalan(n) is the sum of catalan(i)*catalan(n-i-1)    res = 0    for i in range(n):        res += catalan(i) * catalan(n-i-1)     return res  # Driver Program to test above functionfor i in range(10):    print(catalan(i), end=' ')
1 1 2 5 14 42 132 429 1430 4862
 
Time Complexity: O(2n)
Auxiliary Space:  O(n)
We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing a recursion tree). Since there are overlapping sub-problems, we can use dynamic programming for this. Following is a Dynamic programming-based implementation in Python.  
Python3
# A dynamic programming based function to find nth# Catalan number def catalan(n):    if (n == 0 or n == 1):        return 1     # Table to store results of subproblems    catalan = [0 for i in range(n + 1)]     # Initialize first two values in table    catalan[0] = 1    catalan[1] = 1     # Fill entries in catalan[] using recursive formula    for i in range(2, n + 1):        catalan[i] = 0        for j in range(i):            catalan[i] += catalan[j] * catalan[i-j-1]     # Return last entry    return catalan[n]  # Driver codefor i in range(10):    print(catalan(i))
1
1
2
5
14
42
132
429
1430
4862
 
Time Complexity: O(n^2)Auxiliary Space: O(n) 
Please refer complete article on Program for nth Catalan Number for more details!
cyberkid05
amartyaghoshgfg
chandramauliguptach
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack empty() Method in Java

02 Aug, 2018
The java.util.Stack.empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false.
Syntax:
STACK.empty()
Parameters: The method does not take any parameters.
Return Value: The method returns boolean true if the stack is empty else it returns false.
Below programs illustrate the working of java.util.Stack.empty() method:Program 1:
// Java code to demonstrate empty() methodimport java.util.*;  public class Stack_Demo {    public static void main(String[] args)    {          // Creating an empty Stack        Stack<String> STACK = new Stack<String>();          // Stacking strings        STACK.push("Geeks");        STACK.push("4");        STACK.push("Geeks");        STACK.push("Welcomes");        STACK.push("You");          // Displaying the Stack        System.out.println("The stack is: " + STACK);          // Checking for the emptiness of stack        System.out.println("Is the stack empty? " +                                       STACK.empty());          // Popping out all the elements        STACK.pop();        STACK.pop();        STACK.pop();        STACK.pop();        STACK.pop();          // Checking for the emptiness of stack        System.out.println("Is the stack empty? " +                                      STACK.empty());    }}
The stack is: [Geeks, 4, Geeks, Welcomes, You]
Is the stack empty? false
Is the stack empty? true

Program 2:
// Java code to demonstrate empty() methodimport java.util.*;  public class Stack_Demo {    public static void main(String[] args)    {          // Creating an empty Stack        Stack<Integer> STACK = new Stack<Integer>();          // Stacking int values        STACK.push(8);        STACK.push(5);        STACK.push(9);        STACK.push(2);        STACK.push(4);          // Displaying the Stack        System.out.println("The stack is: " + STACK);          // Checking for the emptiness of stack        System.out.println("Is the stack empty? " +                                       STACK.empty());    }}
The stack is: [8, 5, 9, 2, 4]
Is the stack empty? false

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Variable-length arguments in Python

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.
 Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
groups command in Linux with examples

20 May, 2019
In linux, there can be multiple users(those who use/operate the system), and groups are nothing but the collection of users. Groups make it easy to manage users with the same security and access privileges. A user can be part of different groups.
Important Points:
Groups command prints the names of the primary and any supplementary groups for each given username, or the current process if no names are given.
If more than one name is given, the name of each user is printed before the list of that user’s groups and the username is separated from the group list by a colon.
Syntax:
groups [username]...

Example 1: Provided with a user name
$groups demon

In this example, username demon is passed with groups command and the output shows the groups in which the user demon is present, separated by a colon.
Example 2: No username is passed then this will display group membership for the current user
$groups

Here the current user is demon . So when we give “groups” command only we get groups in which demon is a user.
Example 3: Passing root with groups command
Note: Primary and supplementary groups for a process are normally inherited from its parent and are usually unchanged since login. This means that if you change the group database after logging in, groups will not reflect your changes within your existing login session. The only options are –help and –version.
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
MongoDB – Less than Operator $lt

27 Mar, 2020
MongoDB provides different types of comparison operators and less than operator ( $lt ) is one of them. This operator is used to select those documents where the value of the field is less than (<) the given value. You can use this operator in methods like, find(), update(), etc. as per your requirements.
Syntax:
{field: {$lt: value}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs.
 Example #1:In this example, we are selecting those documents where the value of the salary field is less than 35000.
 Example #2:
In this example, we are selecting only those documents where the age of the employee is less than 24. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation. Example #3:In this example, we are selecting only those documents where the points array is less than the specified array.
 Example #4:In this example, we are updating the salary of those employees whose experience year is less than 2 years. Or in other words, set the value of the salary field to 23000 of those documents whose experienceYear field value is less than 2.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Redis - Sorted Set Zadd Command

Redis ZADD command adds all the specified members with the specified scores to the sorted set stored at the key. It is possible to specify multiple score/member pairs. If a specified member is already a member of the sorted set, the score is updated and the element is reinserted at the right position to ensure correct ordering. If the key does not exist, a new sorted set with the specified members as sole members is created, like if the sorted set was empty. If the key exists but does not hold a sorted set, an error is returned.
Integer reply. The number of elements added to the sorted sets, not including elements already existing for which the score was updated.
Following is the basic syntax of Redis ZADD command.
redis 127.0.0.1:6379> ZADD KEY_NAME SCORE1 VALUE1.. SCOREN VALUEN

redis 127.0.0.1:6379> ZADD myset 1 "hello" 
(integer) 1
redis 127.0.0.1:6379> ZADD myset 1 "foo" 
(integer) 1 
redis 127.0.0.1:6379> ZADD myset 2 "world" 3 "bar" 
(integer) 2 
redis 127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES
Integer floatValue() Method in Java

03 May, 2022
floatValue() method of Integer class present inside java.lang package is used to convert the value of the given Integer to a float type after a widening primitive conversion which in general is mostly applicable when we want to truncate or rounding-off the integer value. The package view is as follows:
--> java.lang Package
    --> Integer Class
        --> floatValue() Method     
Syntax:
public float floatValue()
Return Type: A numeric value represented by this object after converting it to type float.
Note: This method is workable when it is supported by java version 1.2 or onwards, so make sure to update java version if running on older(introductory) java versions.
Example 1:
java
// Java Program to Demonstrate floatValue() Method// of Integer Class // Importing required classesimport java.lang.Integer; // Classclass GFG {     // Main driver method    public static void main(String args[])    {         // Creating a custom integer by        // creating object of Integer class        Integer a = new Integer(28);         // Converting Integer number to float value        // using floatValue() method        float b = a.floatValue();         // Printing the float value        System.out.println(b);    }}
Output:
 
Example 2:
Java
// Java Program to Demonstrate Working of floatValue()// Method of Integer Class // Importing required classimport java.lang.Integer; // Classclass GFG {     // Main driver method    public static void main(String args[])    {        // Creating a custom integer value by        // declaring object of Integer Class        Integer a = new Integer(20);         // Convert Integer number to float value        // using floatValue() method        float b = a.floatValue();         // Printing the float value on console        System.out.println(b);    }}
Output:
 
solankimayank
Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashmap vs WeakHashMap in Java

Details about HashMap and WeakHashMap that help to differentiate them are given as follows −
A HashMap has key-value pairs i.e. keys that are associated with the values and the keys are in arbitrary order. A HashMap object that is specified as a key is not eligible for garbage collection. This means that the HashMap has dominance over the garbage collector.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.*;
class A {
   public String toString() {
      return "A ";
   }
   public void finalize() {
      System.out.println("Finalize method");
   }
}
public class Demo {
   public static void main(String args[])throws Exception {
      HashMap hMap = new HashMap();
      A obj = new A();
      hMap.put(obj, " Apple ");
      System.out.println(hMap);
      obj = null;
      System.gc();
      Thread.sleep(5000);
      System.out.println(hMap);
   }
}
The output of the above program is as follows −
{A = Apple }
{A = Apple }
A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.*;
class A {
   public String toString() {
      return "A ";
   }
   public void finalize() {
      System.out.println("Finalize method");
   }
}
public class Demo {
   public static void main(String args[])throws Exception {
      WeakHashMap whMap = new WeakHashMap();
      A obj = new A();
      whMap.put(obj, " Apple ");
      System.out.println(whMap);
      obj = null;
      System.gc();
      Thread.sleep(5000);
      System.out.println(whMap);
   }
}
The output of the above program is as follows −
{A = Apple }
Finalize method
{}
Dictionary.Clear Method in C#

The Dictionary.Clear() method in C# removes all key/value pairs from the Dictionary<TKey,TValue>.
public void Clear();
Let us now see an example to implement the Dictionary.Clear() method −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Cleared Key/value pairs...
Count of elements now = 0
Let us now see another example to implement the Dictionary.Clear() method −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      dict.Add("Six", "Anne");
      dict.Add("Seven", "Katoe");
      Console.WriteLine("Count of elements (updated) = "+dict.Count);
      Console.WriteLine("Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
   }
}
This will produce the following output −
Count of elements = 5
Count of elements (updated) = 7
Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Key = Six, Value = Anne
Key = Seven, Value = Katoe
Cleared Key/value pairs...
Non-decreasing subsequence | Practice | GeeksforGeeks

Given a sequence of n integers, the task is to find out the non-decreasing subsequence of length k with minimum sum. If no sequence exists output -1.
Example 1:
Input: N = 10, K = 3, arr[] = {58, 12, 
       11, 12, 82, 30, 20, 77, 16, 86}
Output: 39
Explanation: {11 + 12 + 16}
Input: N = 10, K = 4, arr[] = {58, 12,
11, 12, 82, 30, 20, 77, 16, 86}
Output: 120
Explanation: {11 + 12 + 16 + 77}

Your Task:  
You don't need to read input or print anything. Complete the function minSum() which takes N, K and array arr as input parameters and returns the sum.

Expected Time Complexity: O(N*K)
Expected Auxiliary Space: O(N*K)

Constraints:
1 ≤ N, K ≤ 103
1 ≤ arr[i] ≤ 105
0
himanshujain4573 months ago
Simplest Java Solution:Accepted
class Solution{
public int minSum(int arr[], int N, int K) {  int [][]dp=new int[N+1][K+1]; for(int i=0;i<=N;i++) {     for(int j=0;j<=K;j++)     {         dp[i][j]=Integer.MAX_VALUE;         if(i==0||j==0)         dp[i][j]=0;     } } for(int i=1;i<=N;i++) {     dp[i][1]=arr[i-1]; } for(int k=2;k<=K;k++) {     for(int i=2;i<=N;i++)     {     int mn=Integer.MAX_VALUE;         for(int j=1;j<i;j++)         {             if(arr[i-1]>=arr[j-1] &&dp[j][k-1]!=Integer.MAX_VALUE)             {                mn=Math.min(mn,arr[i-1]+dp[j][k-1]) ;             }         }         dp[i][k]=mn;     } } int res=Integer.MAX_VALUE; for(int i=1;i<=N;i++) {     res=Math.min(res,dp[i][K]); } if( res==Integer.MAX_VALUE) return -1; return res;} }
0
Harshvardhan yadav10 months ago
Harshvardhan yadav
use concept of finding min_sum of increasing Or equal subsequence of size k
0
ultraint2 years ago
ultraint
how the output of 5 329 16 20 4 11is 47 it should be -1 ?16,20,11 is not an non-decreasing subsequence..
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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

Vertical bar (|) stands for bitwise or operator. In case of two integer objects, it returns bitwise OR operation of two
>>> a=4
>>> bin(a)
'0b100'
>>> b=5
>>> bin(b)
'0b101'
>>> a|b
5
>>> c=a|b
>>> bin(c)
'0b101'
How to change the background color of a Treeview in Tkinter?

The Treeview widget is designed to display the data in a hierarchical structure. It can be used to display the directories, child directories or files in the form of a list. The items present in the Listbox are called Listbox items.
The treeview widget includes many properties and attributes through which we can change or modify its default properties. We can change the background of a treeview widget by defining the 'background' property in the constructor.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the window
win.geometry("700x350")

# Create a Listbox widget
lb = Listbox(win, width=100, height=10, background="purple4", foreground="white", font=('Times 13'),selectbackground="black")
lb.pack()


# Select the list item and delete the item first
# Once the list item is deleted, we can insert a new item in the listbox
def edit():
   for item in lb.curselection():
      lb.delete(item)
      lb.insert("end", "foo")


# Add items in the Listbox
lb.insert("end", "item1", "item2", "item3", "item4", "item5")

# Add a Button To Edit and Delete the Listbox Item
ttk.Button(win, text="Edit", command=edit).pack()

win.mainloop()
If we run the above code, it will display a window with a treeview widget having a distinct background color and some items in it.
GATE | GATE-CS-2014-(Set-3) | Question 38 - GeeksforGeeks

28 Jun, 2021
An IP router with a Maximum Transmission Unit (MTU) of 1500 bytes has received an IP packet of size 4404 bytes with an IP header of length 20 bytes. The values of the relevant fields in the header of the third IP fragment generated by the router for this packet are
(A) MF bit: 0, Datagram Length: 1444; Offset: 370(B) MF bit: 1, Datagram Length: 1424; Offset: 185(C) MF bit: 1, Datagram Length: 1500; Offset: 37(D) MF bit: 0, Datagram Length: 1424; Offset: 2960Answer: (A)Explanation:
Number of packet fragments = ⌈ (total size of packet)/(MTU) ⌉
                           = ⌈ 4404/1500 ⌉
                           = ⌈ 2.936 ⌉ 
                           = 3

So Datagram with data 4404 byte fragmented into 3 fragments. 
The first frame carries bytes 0 to 1479 (because MTU is 1500 bytes and HLEN is 20 byte so the total bytes in fragments is maximum 1500-20=1480). the offset for this datagram is 0/8 = 0.
The second fragment carries byte 1480 to 2959. The offset for this datagram is 1480/8 = 185.finally the third fragment carries byte 2960 to 4404.the offset is 370.and for all fragments except last one the M bit is 1.so in the third bit M is 0..Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
C++ Vector Library - at() Function

The C++ function std::vector::at() returns reference to the element present at location n in the vector.
Following is the declaration for std::vector::at() function form std::vector header.
reference at (size_type n);
const_reference at (size_type n) const;

n − Position of element from container.
Returns an element from specified location if n is valid vector index.
If vector object is constant qualified then method returns constant reference otherwise it returns non-constant reference.
If n is not valid index out_of_bound exception is thrown.
Constant i.e. O(1)
The following example shows the usage of std::vector::at() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   auto il = {1, 2, 3, 4, 5};
   vector<int> v(il);

   for (int i = 0; i < v.size(); ++i)
      cout << v.at(i) << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page