code-rag-bench/online-tutorials huggingface dataset:
Real, Effective and Saved UserID in Linux

18 Mar, 2021
Every user in Unix like operating system is identified by a different integer number, this unique number is called as UserID. 
There are three types of UID defined for a process, which can be dynamically changed as per the privilege of task. 
The three different types of UIDs defined are : 1. Real UserID 2. Effective UserID 3. Saved UserID 
1. Real UserID : For a process, Real UserId is simply the UserID of the user that has started it. It defines which files that this process has access to. 
2. Effective UserID : It is normally the same as Real UserID, but sometimes it is changed to enable a non-privileged user to access files that can only be accessed by a privileged user like root.
If you see the permission of /usr/bin/passwd file:
-rwsr-xr-x 1 root root 59640 Mar 23  2019 /usr/bin/passwd 
So if a non-root user runs this file, the EUID of the process will be “0” i.e. root and UID remains the same as of original user.
3. Saved UserID : It is used when a process is running with elevated privileges (generally root) needs to do some under-privileged work, this can be achieved by temporarily switching to a non-privileged account. 
While performing under-privileged work, the effective UID is changed to some lower privilege value, and the euid is saved to saved userID(suid), so that it can be used for switching back to a privileged account when the task is completed. 
You can print UID by simply typing id on terminal : 
# id
Output:
uid=1000(mandeep) gid=1000(mandeep) 
groups=1000(mandeep), 4(adm), 24(cdrom), 
27(sudo), 30(dip), 46(plugdev), 113(lpadmin), 
128(sambashare)
id command can be used to print real and effective user and group IDs 
Different options of id:
-g, --group : print only effective group id
-G, --groups : print all group IDs
-r, --real : print only real user id
-u, --user : print only effective user id
For example :  
id -g
Output :  
1000
Note: While you use id command with -r option, you will get error like 
id: cannot print only names or real IDs in default format
To deal with this, use -r option in conjunction with other option, for example, id -rg Now, for setting up real user ID, the effective user ID, and the saved set-user-ID of the calling process, we use setresuid() and setresgid() Syntax :  
int setresuid(uid_t ruid, uid_t euid, uid_t suid); # for specific user
int setresgid(gid_t rgid, gid_t egid, gid_t sgid); # for specific group
Return Value : On success, 0 is returned. On error, -1 is returned. 
For more details : Use Linux manual page (man user id).
mohit singh 1
linux-command
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
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
PHP - empty() Function

The empty() function checks whether a variable is empty.
bool empty ( mixed $var )

var
Variable to be checked.
*mixed: mixed indicates that a parameter may accept multiple (but not necessarily all) types
This function returns −
true − if the variable is empty
true − if the variable is empty
false − if variable exists or has a non-empty or non-zero value
false − if variable exists or has a non-empty or non-zero value
The following values evaluates to empty −
integer − if value is 0 then empty() returns true. For any other value returns false.
integer − if value is 0 then empty() returns true. For any other value returns false.
float − if value is 0.0 then empty() returns true. For any other value returns false.
float − if value is 0.0 then empty() returns true. For any other value returns false.
string − if string value is "0" and null ("") then empty() returns true. For any other value returns false (even "0.0").
string − if string value is "0" and null ("") then empty() returns true. For any other value returns false (even "0.0").
array − if value is empty array() then boolval() returns true. For any other value returns false.
array − if value is empty array() then boolval() returns true. For any other value returns false.
NULL − empty() always returns false when variable is NULL.
NULL − empty() always returns false when variable is NULL.
Boolean − if boolean variable is FALSE then empty() returns true.
Boolean − if boolean variable is FALSE then empty() returns true.
PHP 4.0 and above. Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error.
Following example demonstrates return values with different types of variables −
<?php
   // PHP program demo for empty() function

   echo 'when var is 0 function empty() returns <b>'.( empty( 0 )? 'true' : 'false').'</b>';
   echo 'when var is "0.0" function empty() returns <b>'.( empty( "0.0" )? 'true' : 'false').'</b>';
   echo 'when var is "0" function empty() returns <b>'.( empty( "0" )? 'true' : 'false').'</b>';
   echo 'when var is "" function empty() returns <b>'.( empty( "" )? 'true' : 'false').'</b>';
   echo 'when var is [] function empty() returns <b>'.( empty( [] )? 'true' : 'false').'</b>';
   echo 'when var is NULL function empty() returns <b>'.( empty( NULL )? 'true' : 'false').'</b>';
   echo 'when var is FALSE function empty() returns <b>'.( empty( FALSE )? 'true' : 'false').'</b>';
?>
This will produce following result −
when var is 0 function empty() returns true
when var is "0.0" function empty() returns false
when var is "0" function empty() returns true
when var is "" function empty() returns true
when var is [] function empty() returns true
when var is NULL function empty() returns true
when var is FALSE function empty() returns true


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to sort an HTML list using JavaScript?

To sort an HTML list using JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Sorting list example</h1>
<button>Click to sort</button>
<ul class="animalList">
<li>Giraffe</li>
<li>Camel</li>
<li>Dog</li>
<li>Lion</li>
<li>Cheetah</li>
<li>Cat</li>
</ul>
<script>
   document .getElementsByTagName("button")[0] .addEventListener("click", sortList);
   function sortList() {
      var list, i, sortFlag, LiEle, sorted;
      list = document.querySelector(".animalList");
      sortFlag = true;
      while (sortFlag) {
         sortFlag = false;
         LiEle = list.getElementsByTagName("LI");
         for (i = 0; i < LiEle.length - 1; i++) {
            sorted = false;
            if ( LiEle[i].innerHTML.toLowerCase() > LiEle[i + 1].innerHTML.toLowerCase() ) {
               sorted = true;
               break;
            }
         }
         if (sorted) {
            LiEle[i].parentNode.insertBefore(LiEle[i + 1], LiEle[i]);
            sortFlag = true;
         }
      }
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Click to sort” button −
Are values returned by static method are static in java?

Whenever you return values from a static method they are either static nor instance by default, they are just values.
The user invoking the method can use them as he wants. i.e. you can retrieve the values and declare them static.
But, since you cannot declare variables of a method static if you need to declare the vales returned by a method static you need to invoke it in the class outside the methods.
Assume we have a class with name Demo as −
class Demo{
   int data = 20;
   public Demo(int data){
      this.data = data;
   }
   public int getData(){
      return this.data;
   }
}
In the following Java example, we have two methods getObject() and getInt() returning an object and an integer respectively.
We are invoking these methods twice in the class and within a method. In the class we have declared the values returned by them as static.
And in the method we are using them (values returned by the methods) as local variables (obviously non-static).
public class StaticExample{
   static int data = StaticExample.getInt();
   static Demo obj = StaticExample.getObject();
   public static Demo getObject(){
      Demo obj = new Demo(300);
      return obj;
   }
   public static int getInt(){
      return 20;
   }
   public static void main(String args[]) {
      System.out.println(StaticExample.data);
      System.out.println(StaticExample.obj.data);
      StaticExample obj = new StaticExample();
      System.out.println(obj.getInt());
      Demo demo = obj.getObject();
      System.out.println(demo.data);
   }
}
20
300
20
300
How to retrieve a value from MongoDB by its key name?

To retrieve a value from MongoDB by its key name, use the following syntax −
db.yourCollectionName.find({},{"yourFieldName":1}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163b5a56efcc0f9e69048")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163c4a56efcc0f9e69049")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163d3a56efcc0f9e6904a")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.retrieveValueFromAKeyDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
   "CustomerName" : "Larry",
   "CustomerAge" : 21,
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
   "CustomerName" : "Chris",
   "CustomerAge" : 24,
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
   "CustomerName" : "Mike",
   "CustomerAge" : 26,
   "CustomerCountryName" : "UK"
}
Here is the query to retrieve a value from MongoDB by its key name i.e. we have considered the key ‘CustomerCountryName’ −
> db.retrieveValueFromAKeyDemo.find({},{"CustomerCountryName":1}).pretty();
The following is the output:
{
   "_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
   "CustomerCountryName" : "UK"
}
How to create transparent bar plot using ggplot2 in R?

To create transparent barplot using ggplot2, we can use alpha argument inside geom_bar function. For example, if we have a data frame called df that contains a categorical column say x and a numerical column say count then the bar plot with transparency can be created by using the command ggplot(df,aes(x,y))+geom_bar(alpha=0.1,stat="identity")
Consider the below data frame −
 Live Demo
x<-c("A","B","C")
y<-c(24,21,26)
df<-data.frame(x,y)
df
   x  y
1  A  24
2  B  21
3  C  26
Loading ggplot2 package and creating bar plot for data in df −
library(ggplot2)
ggplot(df,aes(x,y))+geom_bar(stat="identity")
Creating bar plot for data in df with transparent bars −
ggplot(df,aes(x,y))+geom_bar(alpha=0.1,stat="identity")
What is CommonModule in Angular 10 ?

30 Apr, 2021
In this article, we are going to see what is CommonModule in Angular 10 and how to use it.
CommonModule is used to export all the basic Angular directives and pipes. It is re-exported when we import BrowserModule into our angular application, BrowserModule is automatically imported into our application when we create our Angular application using ‘ng new’ command
Syntax: CommonModule is automatically imported by BrowserModule when the app is created.
 import { BrowserModule } from '@angular/platform-browser';
 
 @NgModule({

  imports: [
    BrowserModule,
  ]
})
export class AppModule { }
Directives Imported:
NgClass
NgComponentOutlet
NgForOf
NgIf
NgPluralCase:
NgStyle
NgSwitch
NgSwitchCase
NgSwitchDefault
NgTemplateOutlet
Pipes Imported:
AsyncPipe
CurrencyPipe
DatePipe
DecimalPipe
I18nPluralPipe
I18nSelectPipe
JsonPipe
KeyValuePipe
LowerCasePipe
PercentPipe
SlicePipe
TitleCasePipe
UpperCasePipe
Approach: 
Create the Angular app to be used
There is no need for any import for the CommonModule to be used
In app.module.ts CommonModule is imported through BrowserModule.
Pipes and directives will be imported automatically, so we can use them easily.
Make the necessary files for desired output.
Serve the angular app using ng serve to see the output.
Example 1:
app.module.ts
import { NgModule } from '@angular/core';// BrowserModule automatically imports all CommonModule Dependencies  import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component';  @NgModule({  declarations: [    AppComponent  ],  imports: [    // Adding Imports    BrowserModule,  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
app.component.ts
import { Component, OnInit } from '@angular/core';  @Component({    selector: 'app-root',    templateUrl: './app.component.html'})export class AppComponent {    geek = "GeekClass";    g = document.getElementsByClassName(this.geek);}
app.component.html
<!-- use of ngClass directive --><h1 [ngClass] = "geek">  GeeksforGeeks</h1>  Upper Heading's class is : "{{ g[0].className }}"
Output:
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to setup 404 page in angular routing ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to overwrite a file to hide file contents, and make original contents unrecoverable in Linux?

To overwrite and file contents in the Linux system, we use the shred command using the terminal.
shred – The shred command is used to securely delete files and devices. This command overwrites a file to hide file contents, and optionally delete the file so that it is very difficult to recover the file for any software in the Linux/Unix system.
As usual, to remove files from the system, we use the rm command using the terminal. After removal files through the rm command, it may be recoverable using the software whereas after removing files through the shred command files are unrecoverable because the shred command overwrites the files three times with multiple patterns.
The general syntax of the shred command is as follows −
shred [OPTION]... FILE...
Brief description of option available in the shred command.
Overwrite the contents of the file and make it unrecoverable in the Linux system.
To overwrite the contents of the file and make it unrecoverable, we use the shred command in the Linux/Unix system using the terminal as shown below.
$ shred file.txt
After executing this command, the file ‘file.txt’ is unrecoverable.
Overwrite the contents of the file and print what is being done in the Linux system.
To overwrite the contents of the file and print what is being done, we use --verbose option with the shred command in the Linux/Unix system using the terminal as shown in below.
vikash@tutorialspoint:~/shadow$ shred --verbose file.txt
shred: file.txt: pass 1/3 (random)...
shred: file.txt: pass 2/3 (random)...
shred: file.txt: pass 3/3 (random)...
Overwrite only specific byte of the file in the Linux system.
To overwrite only specific byte of the file, we use -s option with the shred command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~/shadow$ cat file.txt
Hey, welcome to tutorialspoint...
vikash@tutorialspoint:~/shadow$ shred -s 2 file.txt
vikash@tutorialspoint:~/shadow$ cat file.txt
y, welcome to tutorialspoint...
Display the help of the shred command and exit.
To check more information about the shred command, we use the –help option with the shred command in the Linux system as shown below.
$ shred --help
Conclusion – In this article, we learned to overwrite a file to hide its contents and optionally delete it using the shred command with available options and suitable examples. The rm command also used toremove the file in the Linux system.
Generate a random array of integers in Java

In order to generate random array of integers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence.
Declaration − The java.util.Random.nextInt() method is declared as follows −
public int nextInt()
Let us see a program to generate a random array of integers in Java −
 Live Demo
import java.util.Random;
public class Example {
   public static void main(String[] args) {
      Random rd = new Random(); // creating Random object
      int[] arr = new int[5];
      for (int i = 0; i < arr.length; i++) {
         arr[i] = rd.nextInt(); // storing random integers in an array
         System.out.println(arr[i]); // printing each array element
      }
   }
}
-1848681552
39846826
858647196
1805220077
-360491047
Note − The output might vary on Online Compilers.
Here we use the nextInt() method in a loop to get a random integer for each element.
for (int i = 0; i < arr.length; i++)
arr[i] = rd.nextInt();
vector max_size() function in C++ STL

09 Jun, 2022
The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container. Syntax:
vector_name.max_size()
Parameters: The function does not accept any parameters. Return value: The function returns the maximum numbers that can fit into the vector container. Time Complexity – Constant O(1) 
Program below illustrates the above function: 
CPP
// C++ program to illustrate the// vector::max_size() function#include <bits/stdc++.h>using namespace std; int main(){    // initialize a vector    vector<int> vec;     // returns the max_size of vector    cout << "max_size of vector 1 = " << vec.max_size() << endl;     vector<int> vec1;     // returns the max_size of vector    cout << "max_size of vector 2 = " << vec1.max_size() << endl;    return 0;}
max_size of vector 1 = 4611686018427387903
max_size of vector 2 = 4611686018427387903
utkarshgupta110092
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Array filter() Method

27 May, 2022
The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. 
Syntax: 
array.filter(callback(element, index, arr), thisValue)
Parameters: This method accepts five parameter as mentioned above and described below: 
callback: This parameter holds the function to be called for each element of the array.
element: The parameter holds the value of the elements being processed currently.
index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
arr: This parameter is optional, it holds the complete array on which Array.every is called.
thisValue: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Return value: This method returns a new array consisting of only those elements that satisfied the condition of the arg_function. 
Example1:  In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by canVote() function.
JavaScript
<script>    // JavaScript to illustrate findIndex() method    function canVote(age) {        return age >= 18;    }     function func() {        var filtered = [24, 33, 16, 40].filter(canVote);        document.write(filtered);    }    func();</script>                   
Output:  
[24,33,40]
Example 2: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isPositive() function. 
Javascript
function isPositive(value) {  return value > 0;} var filtered = [112, 52, 0, -1, 944].filter(isPositive);print(filtered);
Output:  
[112,52,944]
Example 3: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isEven() function. 
Javascript
function isEven(value) {  return value % 2 == 0;} var filtered = [11, 98, 31, 23, 944].filter(isEven);print(filtered);
Output: 
[98,944]
Supported Browsers: The browsers supported by JavaScript Array filter() method are listed below:  
Google Chrome
Microsoft Edge 9.0
Mozilla Firefox 1.5
Safari
Opera
 
jain_chirag
arorakashish0911
surbhikumaridav
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python OpenCV | cv2.arrowedLine() method

23 Nov, 2021
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.arrowedLine() method is used to draw arrow segment pointing from the start point to the end point. 
Syntax: cv2.arrowedLine(image, start_point, end_point, color, thickness, line_type, shift, tipLength)Parameters: image: It is the image on which line is to be drawn. start_point: It is the starting coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). end_point: It is the ending coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). color: It is the color of line to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color. thickness: It is the thickness of the line in px. line_type: It denotes the type of the line for drawing. shift: It denotes number of fractional bits in the point coordinates. tipLength: It denotes the length of the arrow tip in relation to the arrow length. Return Value: It returns an image.  
Image used for all the below examples:  
Example #1:  
Python3
# Python program to explain cv2.arrowedLine() method # importing cv2import cv2 # pathpath = r'C:\Users\Atomix\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Start coordinate, here (0, 0)# represents the top left corner of imagestart_point = (0, 0) # End coordinateend_point = (200, 200) # Green color in BGRcolor = (0, 255, 0) # Line thickness of 9 pxthickness = 9 # Using cv2.arrowedLine() method# Draw a diagonal green arrow line# with thickness of 9 pximage = cv2.arrowedLine(image, start_point, end_point,                                     color, thickness) # Displaying the imagecv2.imshow(window_name, image)
Output:  
Example #2:  
Python3
# Python program to explain cv2.arrowedLine() method # importing cv2import cv2 # pathpath = r'C:\Users\Atomix\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Start coordinate, here (225, 0)# represents the top right corner of imagestart_point = (225, 0) # End coordinateend_point = (0, 90) # Red color in BGRcolor = (0, 0, 255) # Line thickness of 9 pxthickness = 9 # Using cv2.arrowedLine() method# Draw a red arrow line# with thickness of 9 px and tipLength = 0.5image = cv2.arrowedLine(image, start_point, end_point,                    color, thickness, tipLength = 0.5) # Displaying the imagecv2.imshow(window_name, image)
Output:  
 
ritvikcodes23
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hazelcast - Setup

Hazelcast requires Java 1.6 or above. Hazelcast can also be used with .NET, C++, or other JVM based languages like Scala and Clojure. However, for this tutorial, we are going to use Java 8.
Before we move on, following is the project setup that we will use for this tutorial.
hazelcast/
├── com.example.demo/
│ ├── SingleInstanceHazelcastExample.java
│ ├── MultiInstanceHazelcastExample.java
│ ├── Server.java
│ └── ....
├── pom.xml
├── target/
├── hazelcast.xml
├── hazelcast-multicast.xml
├── ...

For now, we can just create the package, i.e., com.example.demo inside the hazelcast directory. Then, just cd to that directory. We will look at other files in the upcoming sections.
Installing Hazelcast simply involves adding a JAR file to your build file. POM file or build.gradle based on whether you are using Maven or Gradle respectively.
If you are using Gradle, adding the following to build.gradle file would be enough −
dependencies {
   compile "com.hazelcast:hazelcast:3.12.12”
}
We will use the following POM for our tutorial −
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>1.0.0</modelVersion>
   <groupId>com.example</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Hazelcast</description>

   <properties>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</maven.compiler.target>
   </properties>

   <dependencies>
      <dependency>
         <groupId>com.hazelcast</groupId>
         <artifactId>hazelcast</artifactId>
         <version>3.12.12</version>
      </dependency>
   </dependencies>

   <!-- Below build plugin is not needed for Hazelcast, it is being used only to created a shaded JAR so that -->
   <!-- using the output i.e. the JAR becomes simple for testing snippets in the tutorial-->
   <build>
      <plugins>
         <plugin>
            <!-- Create a shaded JAR and specify the entry point class-->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.4</version>
            <executions>
               <execution>
                  <phase>package</phase>
                     <goals>
                     <goal>shade</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>
 Print
 Add Notes
 Bookmark this page
Python - Convert a set into dictionary

Python provides lot of flexibility to handle different types of data structures. There may be a need when you have to convert one Data Structure to another for a better use or better analysis of the data. In this article we will see how to convert a Python set to a Python dictionary.
The dict() can be used to take input parameters and convert them to a dictionary. We also use the zip function to group the keys and values together which finally become the key value pair in the dictionary.
 Live Demo
list_keys = {1,2,3,4}
list_values = {'Mon','Tue','Wed','Thu'}
new_dict = dict(zip(list_keys, list_values))
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Mon', 2: 'Tue', 3: 'Thu', 4: 'Wed'}
<class 'dict'>
When we need a dictionary with different keys but the value of each key is same, we can use this method as shown below.
 Live Demo
list_keys = {1,2,3,4}
new_dict = dict.fromkeys(list_keys,'Mon')
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Mon', 2: 'Mon', 3: 'Mon', 4: 'Mon'}
<class 'dict'>
We use a similar method as the previous approach except that in this case we have dictionary comprehension.
 Live Demo
list_keys = {1,2,3,4}
new_dict = {element:'Tue' for element in list_keys}
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Tue', 2: 'Tue', 3: 'Tue', 4: 'Tue'}
<class 'dict'>
Numpy | Data Type Objects - GeeksforGeeks

15 Nov, 2018
Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about :
Type of the data (integer, float, Python object etc.)
Size of the data (number of bytes)
Byte order of the data (little-endian or big-endian)
If the data type is a sub-array, what is its shape and data type.
The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes. So how these bytes will be interpreted is given by the dtype object.  
Constructing a data type (dtype) object : Data type object is an instance of numpy.dtype class and it can be created using numpy.dtype.
Parameters:
obj: Object to be converted to a data type object.align : [bool, optional] Add padding to the fields to match what a C compiler would output for a similar C-struct.copy : [bool, optional] Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object.
Output:
int16
Output:
Byte order is: >
Size is: 4
Name of data type is: int32

The type specifier (i4 in above case) can take different forms:
b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a (representing bytes, ints, unsigned ints, floats, complex and fixed length strings of specified byte lengths)
int8,...,uint8,...,float16, float32, float64, complex64, complex128 (this time with bit sizes)
Note : dtype is different from type. 
Output:
type is:    
dtype is:  int32

 Data type Objects with Structured Arrays : Data type objects are useful for creating structured arrays. A structured array is the one which contains different types of data. Structured arrays can be accessed with the help of fields.
A field is like specifying a name to the object. In case of structured arrays, the dtype object will also be structured. 
Output:
('<f8', (2,))
Output:
('John', [ 6.,  7.])
Grades of John are:  [ 6.  7.]
Names are:  ['Sarah' 'John']

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Python Program for Breadth First Search or BFS for a Graph
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
Axios in React: A Guide for Beginners
C++ Program For Inserting A Node In A Linked List
How to create a Blog app using ReactJS ?
Implementation of Bit Stuffing and Bit Destuffing
How to set background images in ReactJS ?
Tailwind CSS vs Bootstrap
Image Sharpening Using Laplacian Filter and High Boost Filtering in MATLAB
Drop MySQL Database

You would need special privileges to create or to delete a MySQL database. So, assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.
Be careful while deleting any database because you will lose your all the data available in your database.
Here is an example to delete a database(TUTORIALS) created in the previous chapter −
[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******

This will give you a warning and it will confirm if you really want to delete this database or not.
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'TUTORIALS' database [y/N] y
Database "TUTORIALS" dropped

PHP uses mysqli query() or mysql_query() function to drop a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)

$sql
Required - SQL query to drop a MySQL database.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to drop a database −
Copy and paste the following example as mysql_example.php −
<html>
   <head><title>Dropping MySQL Database</title></head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');

         if ($mysqli->query("Drop DATABASE TUTORIALS")) {
            printf("Database TUTORIALS dropped successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not drop database: %s<br />", $mysqli->error);
         }
         $mysqli->close();
      ?>
   </body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Database TUTORIALS dropped successfully.


    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
C Program for replacing one digit with other

Given a number n, we have to replace a digit x from that number with another given number m. we have to look for the number whether the number is present in the given number or not, if it is present in the given number then replace that particular number x with another number m.
Like we are given with a number “123” and m as 5 and the number to be replaced i.e. x as “2”, so the result should be “153”.
Input: n = 983, digit = 9, replace = 6
Output: 683
Explanation: digit 9 is the first digit in 983 and we have to replace the digit 9 with 6 so the result will be 683.
Input: n = 123, digit = 5, replace = 4
Output: 123
Explanation: There is not digit 5 in the given number n so the result will be same as the number n.
The approach used below is as follows −
We will look up for the number by starting from the unit place
When we found the digit which we want to replace then add result to the (replace * d) where d should be equal to 1.
If we don’t found the number just simply keep the number as it is.
In function int digitreplace(int n, int digit, int replace)
   Step 1-> Declare and initialize res=0 and d=1, rem
   Step 2-> Loop While(n)
      Set rem as n%10
      If rem == digit then,
         Set res as res + replace * d
      Else
         Set res as res + rem * d
         d *= 10;
         n /= 10;
      End Loop
   Step 3-> Print res
      End function
In function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize n = 983, digit = 9, replace = 7
   Step 2-> Call Function digitreplace(n, digit, replace);
Stop
 Live Demo
#include <stdio.h>
int digitreplace(int n, int digit, int replace) {
   int res=0, d=1;
   int rem;
   while(n) {
      //finding the remainder from the back
      rem = n%10;
      //Checking whether the remainder equal to the
      //digit we want to replace. If yes then replace.
      if(rem == digit)
         res = res + replace * d;
      //Else dont replace just store the same in res.
      else
         res = res + rem * d;
         d *= 10;
         n /= 10;
   }
   printf("%d\n", res);
      return 0;
}
//main function
int main(int argc, char const *argv[]) {
   int n = 983;
   int digit = 9;
   int replace = 7;
   digitreplace(n, digit, replace);
   return 0;
}
If run the above code it will generate the following output −
783
Top K Frequent Elements in Python

Suppose we have a non-empty array of integer numbers. we have to return the kth most frequent elements. So if the elements are [1,1,1,1,2,2,3,3,3] and k = 2, then the result will be
Formally the function should −
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
To solve this, we will follow these steps −
num_freq = an empty map, freq_list := an empty map
for each element i in numsif i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1
if i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1
for each key-value pair in num_freq mapif value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array
if value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array
res := empty list
for i := length of numbers down to 0if i in freq_list, then add elements of freq_list[i] into resif length of res >= k, then break
if i in freq_list, then add elements of freq_list[i] into res
if length of res >= k, then break
return result
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def topKFrequent(self, nums, k):
      number_frequency = {}
      frequency_list ={}
      for i in nums:
         if i not in number_frequency:
            number_frequency[i] = 1
         else:
            number_frequency[i] += 1
      for key,value in number_frequency.items():
         if value not in frequency_list:
            frequency_list[value] = [key]
         else:
            frequency_list[value].append(key)
      result = []
      for i in range(len(nums),0,-1):
         if i in frequency_list:
            result.extend(frequency_list[i])
         if len(result) >=k:
            break
      return result
ob1 = Solution()
print(ob1.topKFrequent([1,1,1,1,2,2,3,3,3], 2))
[1,1,1,1,2,2,3,3,3]
2
[1, 3]
How to disable Bluetooth in android?

This example demonstrates How to disable Bluetooth in android.
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"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show Bluetooth status.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Bundle;
import android.os.health.SystemHealthManager;
import android.provider.Telephony;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setText("disable");
      final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
      textView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            manager.getAdapter().disable();
         }
      });
   }
   @Override
   protected void onStop() {
      super.onStop();
   }
   @Override
   protected void onResume() {
      super.onResume();
   }
}
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 –
Click here to download the project code
C/C++ Program to Count set bits in an integer?

Here we will see how we can check number of set bits in an integer number. The set bits are 1’s in the binary representation of a number. For an example the number 13 has three set bits 1101. So the count will be 3.
To solve this problem, we will shift the number to the right, and if the LSb is 1, then increase count. Until the number becomes 0, it will run.
begin
   count := 0
   while count is not 0, do
      if LSb of n is set, then
         count := count + 1
      end if
         n := n after shifting 1 bit to right
   done
   return count
end
 Live Demo
#include<iostream>
using namespace std;
int count_set_bit(int n) {
   int count = 0;
   while(n != 0) {
      if(n & 1 == 1) {
         count++;
      }
      n = n >> 1; //right shift 1 bit
   }
   return count;
}
int main() {
   int n;
   cout << "Enter a number: ";
   cin >> n;
   cout << "Number of set bits: " << count_set_bit(n);
}
Enter a number: 29
Number of set bits: 4
This program will run in C and generates output, but when we want to compile in C++, it will return an error during compile time. It will say there are too many arguments are passed.
How to match a range of characters using Java regex

To match a range of characters i.e. to match all the characters between two specified characters in a sequence you can use the character class as 
[a-z]
The expression “[a-zA-Z]” accepts any English alphabet.
The expression “[a-zA-Z]” accepts any English alphabet.
The expression “[0-9&&[^35]]” accepts numbers except 3 and 5.
The expression “[0-9&&[^35]]” accepts numbers except 3 and 5.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^[a-zA-Z0-9]*$";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}
Enter a String
Hello
Match occurred
Enter a String
sample#
Match not occurred
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "[0-9&&[^35]]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Occurrences :"+count);
   }
}
Enter a String
111223333555689
Occurrences :8
Character.valueOf() in Java with examples - GeeksforGeeks

06 Dec, 2018
Java.lang.Character.valueOf() is an inbuilt method in Java that returns a Character instance representing the specified char value. If a new Character instance is not required, this method is generally used in preference to the constructor Character(char), since this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values range [‘\u0000’ to ‘\u007F’] inclusive and may cache other values outside of this range.
Syntax:
public static Character valueOf(char ch)

Parameter: 
ch- this parameter specifies the character.

Returns: This method returns a Character instance representing ch.
The program below demonstrates the Java.lang.Character.valueOf() function:
Program 1:
// Java program to demonstrate the// Java.lang.Character.valueOf() method// when the assigned char is a character  import java.lang.*;  public class Gfg {      public static void main(String[] args)    {        // Create a character object        Character c = new Character('z');          // assign the primitive value to a character        char ch = c.charValue();          System.out.println("Character value of " + ch + " is " + c);    }}
Character value of z is z

Program 2:
// Java program to demonstrate the// Java.lang.Character.valueOf() method// when the assigned char is a number  import java.lang.*;  public class Gfg {      public static void main(String[] args)    {        // Create a character object        Character c = new Character('5');          // assign the primitive value to a character        char ch = c.charValue();          System.out.println("Character value of " + ch + " is " + c);    }}
Character value of 5 is 5

Java-Character
Java-Functions
Java-lang package
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
How to use waiter functionality for bucket_not_exists using Boto3 and AWS Client?

Problem Statement − Use boto3 library in Python to check whether a bucket does not exist using waiter functionality. For example, use waiters to check whether Bucket_2 does not exist in S3.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − Use bucket_name as the parameter in the function.
Step 3 − Create an AWS session using boto3 library.
Step 4 − Create an AWS client for S3.
Step 5 − Now create the wait object for bucket_not_exists using get_waiter function.
Step 6 − Now, use the wait object to validate whether the bucket does not exist. By default, it checks in every 5 seconds until a successful state is reached. Here successful state means bucket should not be present in S3. An error is returned after 20 failed checks. However, the user can define polling time and max attempts.
Step 7 − It returns None.
Step 8 − Handle the generic exception if something went wrong while checking the bucket.
Use the following code to use waiter to check whether bucket_not_exists −
import boto3
from botocore.exceptions import ClientError

def use_waiters_check_bucket_not_exists(bucket_name):
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
      waiter = s3_client.get_waiter('bucket_not_exists')
      waiter.wait(Bucket=bucket_name,
                  WaiterConfig={
                     'Delay': 2, 'MaxAttempts': 5})
      print('Bucket not exist: ' + bucket_name)
   except ClientError as e:
      raise Exception( "boto3 client error in use_waiters_check_bucket_not_exists: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in use_waiters_check_bucket_not_exists: " + e.__str__())

print(use_waiters_check_bucket_not_exists("Bucket_2"))
print(use_waiters_check_bucket_not_exists("Bucket_1"))
Bucket not exist: Bucket_2
None

botocore.exceptions.WaiterError: Waiter BucketNotExists failed: Max
attempts exceeded
"Unexpected error in use_waiters_check_bucket_not_exists: " +
e.__str__())
Exception: Unexpected error in use_waiters_check_bucket_not_exists:
Waiter BucketNotExists failed: Max attempts exceed


For Bucket_2, the output is print statement and None. Since the response doesn’t return anything, it prints None.
For Bucket_1, the output is an exception, since this bucket exists even after max attempts to check.
In exception, it can be read that Max attempts exceeded.