code-rag-bench/online-tutorials huggingface dataset:
MongoDB aggregation framework to sort by length of array?

To sort by length of array, use aggregate(). Before that, get the count of records in an arrayusing $sum. Let us create a collection with documents
> db.demo33.insertOne({"ListOfStudent":["Chris","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17556ccfb11e5c34d898ca")
}
> db.demo33.insertOne({"ListOfStudent":["David","Adam","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17557acfb11e5c34d898cb")
}
> db.demo33.insertOne({"ListOfStudent":["Carol","Sam","John","Robert"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e1755a3cfb11e5c34d898cc")
}
Display all documents from a collection with the help of find() method −
> db.demo33.find();
This will produce the following output −
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ListOfStudent" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ListOfStudent" : [ "David", "Adam", "Mike" ] }
{ "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ListOfStudent" : [ "Carol", "Sam", "John", "Robert" ] }
Following is the query to sort by length of array −
> db.demo33.aggregate({$unwind:"$ListOfStudent"}, { $group : {_id:'$_id', ct:{$sum:1}}}, { $sort :{ ct: -1}} );
This will produce the following output −
{ "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ct" : 4 }
{ "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ct" : 3 }
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ct" : 2 }
Python Number random() Method

The random() method returns a random floating point number in the range [0.0, 1.0].
Following is the syntax for the random() method −
random ( )

Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using the random static object.
NA
This method returns a random float r, such that 0.0 <= r <= 1.0
The following example shows the usage of the random() method.
#!/usr/bin/python3
import random

# First random number
print ("random() : ", random.random())

# Second random number
print ("random() : ", random.random())
When we run the above program, it produces the following result −
random() :  0.281954791393
random() :  0.309090465205


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How do JavaScript closures work?

In JavaScript, closure is the grouping of a function and where that function declared. In JavaScript, all functions work like closures. A closure is a function uses the scope in which it was declared when invoked. It is not the scope in which it was invoked.
You can try to run the following code to learn how to work with JavaScript closures:
<!DOCTYPE html>
<html>
   <body>
      <h2>Working with JavaScript Closures</h2>
      <script>
         var p = 10;
         function a() {
            var p = 15;
            b(function() {
               alert(p);
            });
         }
         function b(f){
            var p = 30;
            f();
         }
         a();
      </script>
   </body>
</html>
TypeScript - String concat()

This method adds two or more strings and returns a new single string.
string.concat(string2, string3[, ..., stringN]);

string2...stringN − These are the strings to be concatenated.
Returns a single concatenated string.
var str1 = new String( "This is string one" ); 
var str2 = new String( "This is string two" ); 
var str3 = str1.concat(str2.toString());
console.log("str1 + str2 : "+str3)

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
str1 + str2 : This is string oneThis is string two


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
java.time.Duration.ofMillis() Method Example

The java.time.Duration.ofMillis(long millis) method obtains a Duration representing a number of standard milliseconds.
Following is the declaration for java.time.Duration.ofMillis(long millis) method.
public static Duration ofMillis(long millis)

millis − the number of milliseconds, positive or negative.
a Duration, not null.
ArithmeticException − if the input milliseconds exceeds the capacity of Duration.
The following example shows the usage of java.time.Duration.ofMillis(long millis) method.
package com.tutorialspoint;

import java.time.Duration;

public class DurationDemo {
   public static void main(String[] args) {

      Duration duration = Duration.ofMillis(2000);
      System.out.println(duration.getSeconds());      
   }
}
Let us compile and run the above program, this will produce the following result −
2

 Print
 Add Notes
 Bookmark this page
Create User SQL in SAP HANA database

You can achieve this by running the below SQL query −
>CREATE USER TEST password “Welcome1$$”  VALID FROM ‘2017-12-05 11:00:00’
UNTIL ‘2018-12-08 12:00:00’;

CREATE USER DUMMY password “Welcome1$$”  VALID FROM NOW UNTIL FOREVER;
Note that password passed in this SQL should meet password policy of SAP HANA system otherwise user creation will be failed.
Linux Admin - Grep Command

grep is commonly used by administrators to −
Find files with a specific text string
Search for a text string in logs
Filter command out, focusing on a particular string
Following is a list of common switches used with grep.
Search for errors X Server errors in Xorg logs −
[root@centosLocal log]# grep error ./Xorg*.log 
   ./Xorg.0.log:   (WW) warning, (EE) error, (NI) not implemented, (??) unknown. 
   ./Xorg.1.log:   (WW) warning, (EE) error, (NI) not implemented, (??) unknown. 
   ./Xorg.9.log:   (WW) warning, (EE) error, (NI) not implemented, (??) unknown. 
[root@centosLocal log]#

Check for possible RDP attacks on an imported Windows Server firewall log.
[root@centosLocal Documents]# grep 3389 ./pfirewall.log | grep " 146." | wc -l 
326
[root@centosLocal Documents]#

As seen in the above example, we had 326 Remote Desktop login attempts from IPv4 class A range in less than 24 hours. The offending IP Address has been hidden for privacy reasons. These were all from the same IPv4 address. Quick as that, we have tangible evidence to block some IPv4 ranges in firewalls.
grep can be a fairly complex command. However, a Linux administrator needs to get a firm grasp on. In an average day, a Linux System Admin can use a dozen variations of grep.

    57 Lectures 
     7.5 hours 

 Mamta Tripathi

    25 Lectures 
     3 hours 

 Lets Kode It

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    58 Lectures 
     2.5 hours 

 Frahaan Hussain

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    23 Lectures 
     5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Coupling in Java

Coupling refers to the usage of an object by another object. It can also be termed as collaboration. This dependency of one object on another object to get some task done can be classified into the following two types −
Tight coupling - When an object creates the object to be used, then it is a tight coupling situation. As the main object creates the object itself, this object can not be changed from outside world easily marked it as tightly coupled objects.
Tight coupling - When an object creates the object to be used, then it is a tight coupling situation. As the main object creates the object itself, this object can not be changed from outside world easily marked it as tightly coupled objects.
Loose coupling - When an object gets the object to be used from the outside, then it is a loose coupling situation. As the main object is merely using the object, this object can be changed from the outside world easily marked it as loosely coupled objects.
Loose coupling - When an object gets the object to be used from the outside, then it is a loose coupling situation. As the main object is merely using the object, this object can be changed from the outside world easily marked it as loosely coupled objects.
Tester.java
 Live Demo
public class Tester {
   public static void main(String args[]) {
      A a = new A();

      //a.display() will print A and B
      //this implementation can not be changed dynamically
      //being tight coupling
      a.display();
   }
}

class A {
   B b;
   public A() {
      //b is tightly coupled to A
      b = new B();
   }

   public void display() {
      System.out.println("A");
      b.display();
   }
}

class B {    
   public B(){}
   public void display() {
      System.out.println("B");
   }
}
This will produce the following result −
A
B
Tester.java
Live Demo
import java.io.IOException;

public class Tester {
   public static void main(String args[]) throws IOException {
      Show b = new B();
      Show c = new C();

      A a = new A(b);          
      //a.display() will print A and B    
      a.display();

      A a1 = new A(c);
      //a.display() will print A and C    
      a1.display();
   }
}

interface Show {
   public void display();
}

class A {
   Show s;
   public A(Show s) {
      //s is loosely coupled to A
      this.s = s;
   }

   public void display() {
      System.out.println("A");
      s.display();
   }
}

class B implements Show {    
   public B(){}
   public void display() {
      System.out.println("B");
   }
}

class C implements Show {    
   public C(){}
   public void display() {
      System.out.println("C");
   }
}
This will produce the following result −
A
B
A
C
Using interfaces, we achieve the loose coupling by injecting the dependency.
Group Managed Service Accounts

The Managed Service Accounts (MSA) was introduced in Windows Server 2008 R2 to automatically manage (change) passwords of service accounts. Using MSA, you can considerably reduce the risk of system accounts running system services being compromised. MSA has one major problem which is the usage of such service account only on one computer. It means that MSA Service Accounts cannot work with cluster or NLB services, which operate simultaneously on multiple servers and use the same account and password. To fix this, Microsoft added the feature of Group Managed Service Accounts (gMSA) to Windows Server 2012.
To create a gMSA, we should follow the steps given below −
Step 1 − Create the KDS Root Key. This is used by the KDS service on DC to generate passwords.
To use the key immediately in the test environment, you can run the PowerShell command −
Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10)) 

To check whether it creates successfully or not, we run the PowerShell command −
Get-KdsRootKey 

Step 2 − To create and configure gMSA → Open the Powershell terminal and type −
New – ADServiceAccount – name gmsa1 – DNSHostNamedc1.example.com – PrincipalsAllowedToRetrieveManagedPassword "gmsa1Group"
In which,
gmsa1 is the name of the gMSA account to be created.
gmsa1 is the name of the gMSA account to be created.
dc1.example.com is the DNS server Name.
dc1.example.com is the DNS server Name.
gmsa1Group is the active directory group which includes all systems that have to be used. This group should be created before in the Groups.
gmsa1Group is the active directory group which includes all systems that have to be used. This group should be created before in the Groups.
To check it, Go to → Server Manager → Tools → Active Directory Users and Computers → Managed Service Accounts.
Step 3 − To install gMAs on a server → open PowerShell terminal and type in the following commands −
Install − ADServiceAccount – Identity gmsa1
Test − ADServiceAccount gmsa1
The result should come “True” after running the second command, as shown in the screenshot given below.
Step 4 − Go to service properties, specify that the service will be run with a gMSA account. In the This account box in the Log on tab type the name of the service account. At the end of the name use symbol $, the password need not to be specified. After the changes are saved, the service has to be restarted.
The account will get the “Log On as a Service” and the password will be retrieved automatically.

    23 Lectures 
     2 hours 

 Pavan Lalwani

    37 Lectures 
     13 hours 

 Trevoir Williams

    46 Lectures 
     3.5 hours 

 Fettah Ben

    55 Lectures 
     6 hours 

 Total Seminars

    20 Lectures 
     2.5 hours 

 Brandon Dennis

    52 Lectures 
     9 hours 

 Fabrice Chrzanowski
 Print
 Add Notes
 Bookmark this page
Symfony - Internationalization

Internationalization (i18n) and Localization (l10n) help to increase the customer coverage of a web application. Symfony provides an excellent Translation component for this purpose. Let us learn how to use the Translation component in this chapter.
By default, Symfony web framework disables Translation component. To enable it, add the translator section in the configuration file, app/config/config.yml.
framework: translator: { fallbacks: [en] }

Translation component translates the text using the translation resource file. The resource file may be written in PHP, XML, and YAML. The default location of the resource file is app/Resources/translations. It needs one resource file per language. Let us write a resource file, messages.fr.yml for French language.
I love Symfony: J'aime Symfony 
I love %name%: J'aime %name%

The left side text is in English and the right side text is in French. The second line shows the use of a placeholder. The placeholder information can be added dynamically while using translation.
By default, the default locale of the user's system will be set by the Symfony web framework. If the default locale is not configured in the web application, it will fallback to English. The locale can be set in the URL of the web page as well.
http://www.somedomain.com/en/index 
http://www.somedomain.com/fr/index

Let us use URL-based locale in our example to easily understand the translation concept. Create a new function, translationSample with route /{_locale}/translation/sample in DefaultController (src/AppBundle/Controller/DefaultController.php). {_locale} is a special keyword in Symfony to specify the default locale.
/** 
   * @Route("/{_locale}/translation/sample", name="translation_sample") 
*/ 
public function translationSample() { 
   $translated = $this->get('translator')->trans('I love Symfony'); 
   return new Response($translated); 
}
Here, we have used translation method, trans, which translates the content to the current locale. In this case, the current locale is the first part of the URL. Now, run the application and load the page, http://localhost:8000/en/translation/sample in the browser.
The result will be "I love Symfony" in English language. Now, load the page http://localhost:8000/fr/translation/sample in the browser. Now, the text will be translated to French as follows.
Similarly, twig template has {% trans %} block to enable translation feature in views as well. To check it, add a new function, translationTwigSample and the corresponding view at app/Resources/views/translate/index.html.twig.
/** 
   * @Route("/{_locale}/translation/twigsample", name="translation_twig_sample") 
*/ 
public function translationTwigSample() { 
   return $this->render('translate/index.html.twig'); 
} 
{% extends 'base.html.twig' %}  
{% block body %} 
   {% trans with {'%name%': 'Symfony'} from "app" into "fr" %}I love %name% {% endtrans %} 
{% endblock %} 
Here, the trans block specifies the placeholder as well. The page result is as follows.
 Print
 Add Notes
 Bookmark this page
What does "with torch no_grad" do in PyTorch?

The use of "with torch.no_grad()" is like a loop where every tensor inside the loop will have requires_grad set to False. It means any tensor
with gradient currently attached with the current computational graph is now
detached from the current graph. We no longer be able to compute the
gradients with respect to this tensor.
A tensor is detached from the current graph until it is within the loop. As
soon as it is out of the loop, it is again attached to the current graph if the
tensor was defined with gradient.
Let's take a couple of examples for a better understanding of how it works.
In this example, we created a tensor x with requires_grad = true. Next, we define a function y of this tensor x and put the function within the with torch.no_grad() loop. Now x is within the loop, so its requires_grad is set to False.
Within the loop the gradients of y could not be computed with respect to x. So, y.requires_grad returns False.
# import torch library
import torch

# define a torch tensor
x = torch.tensor(2., requires_grad = True)
print("x:", x)

# define a function y
with torch.no_grad():
   y = x ** 2
print("y:", y)

# check gradient for Y
print("y.requires_grad:", y.requires_grad)
x: tensor(2., requires_grad=True)
y: tensor(4.)
y.requires_grad: False
In this example, we have defined the function z out of the loop. So, z.requires_grad returns True.
# import torch library
import torch

# define three tensors
x = torch.tensor(2., requires_grad = False)
w = torch.tensor(3., requires_grad = True)
b = torch.tensor(1., requires_grad = True)

print("x:", x)
print("w:", w)
print("b:", b)

# define a function y
y = w * x + b
print("y:", y)

# define a function z
with torch.no_grad():
   z = w * x + b

print("z:", z)

# check if requires grad is true or not
print("y.requires_grad:", y.requires_grad)
print("z.requires_grad:", z.requires_grad)
x: tensor(2.)
w: tensor(3., requires_grad=True)
b: tensor(1., requires_grad=True)
y: tensor(7., grad_fn=<AddBackward0>)
z: tensor(7.)
y.requires_grad: True
z.requires_grad: False
wxPython - CheckBox Class

A checkbox displays a small labeled rectangular box. When clicked, a checkmark appears inside the rectangle to indicate that a choice is made. Checkboxes are preferred over radio buttons when the user is to be allowed to make more than one choice. In this case, the third state is called mixed or undetermined state, generally used in ‘doesn’t apply’ scenario.
Normally, a checkbox object has two states (checked or unchecked). Tristate checkbox can also be constructed if the appropriate style parameter is given.
wx.CheckBox class constructor takes the following parameters −
Wx.CheckBox(parent, id, label, pos, size, style)

The following style parameter values can be used −
wx.CHK_2STATE
Creates two state checkbox. Default
wx.CHK_3STATE
Creates three state checkbox
wx.ALIGN_RIGHT
Puts a box label to the left of the checkbox
This class has two important methods − GetState() returns true or false depending on if the checkbox is checked or not. SetValue() is used to select a checkbox programmatically.
wx.EVT_CHECKBOX is the only event binder available. Associated event handler will be invoked every time any checkbox on the frame is checked or unchecked.
Following is a simple example demonstrating the use of three checkboxes. Handler function OnChecked() identifies the checkbox, which is responsible for the event and displays its state.
The complete code is −
import wx  
 
class Example(wx.Frame): 
            
   def __init__(self, parent, title): 
      super(Example, self).__init__(parent, title = title,size = (200,200)) 
         
      self.InitUI() 
		
   def InitUI(self):    
             
      pnl = wx.Panel(self) 
		  
      self.cb1 = wx.CheckBox(pnl, label = 'Value A',pos = (10,10)) 
      self.cb2 = wx.CheckBox(pnl, label = 'Value B',pos = (10,40)) 
      self.cb3 = wx.CheckBox(pnl, label = 'Value C',pos = (10,70)) 
		
      self.Bind(wx.EVT_CHECKBOX,self.onChecked) 
      self.Centre() 
      self.Show(True) 
      
   def onChecked(self, e): 
      cb = e.GetEventObject() 
      print cb.GetLabel(),' is clicked',cb.GetValue()
		
ex = wx.App() 
Example(None,'CheckBox') 
ex.MainLoop()
The above code produces the following output −
Value A is clicked True
Value B is clicked True
Value C is clicked True
Value B is clicked False
 Print
 Add Notes
 Bookmark this page
Generate random numbers in Arduino

Generating random numbers is one of the key requirements from microcontrollers. Random numbers have several applications. Let’s not get there. You must have an application in mind, which brought you to this page. Generating random numbers is very easy in Arduino, thanks to the inbuilt random() function.
random(min, max)
OR
random(max)
where min is 0 by default.
Min is inclusive, while max is exclusive. Thus, random(10,50) will return a number integer between 10 and 49 (10 and 49 included). random(100) will return a random number between 0 and 99, both included. Note that the random function’s return type is long.
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   long r1 = random(100);
   Serial.println(r1);
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
Ignore the garbage output. Every time the board is reset, some garbage gets printed. But you can see that the random number printed every time is different.
HashMap clear() Method in Java - GeeksforGeeks

26 Nov, 2018
The java.util.HashMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap.
Syntax:
Hash_Map.clear()
Parameters: The method does not accept any parameters.
Return Value: The method does not return any value.
Below programs are used to illustrate the working of java.util.HashMap.clear() Method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the clear() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();          // Mapping string values to int keys        hash_map.put(10, "Geeks");        hash_map.put(15, "4");        hash_map.put(20, "Geeks");        hash_map.put(25, "Welcomes");        hash_map.put(30, "You");          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Clearing the hash map using clear()        hash_map.clear();          // Displaying the final HashMap        System.out.println("Finally the maps look like this: " + hash_map);    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Finally the maps look like this: {}

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the clear() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Clearing the hash map using clear()        hash_map.clear();          // Displaying the final HashMap        System.out.println("Finally the maps look like this: " + hash_map);    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Finally the maps look like this: {}

Note: The same operation can be performed with any type of Mapping with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Initializing a List in Java
Collections in Java
Last-child and last-of-type selector in SASS - GeeksforGeeks

18 Nov, 2019
SASS is also called Syntactically Awesome Stylesheet. It is a programming language that is interpreted into CSS. The Last Child selector is a selector that allows the user to target the last element inside the containing element. This selector is also known as a Structural Pseudo class which means it is used for styling content on the basis of parent and child content.The Last type of selector is used to match the last occurrence of an element within the container. Both selectors work in the same way but have a slight difference i.e the last type is less specified than the last-child selector.
Syntax:
For Last Child Selector::last-child
:last-child
For the Last of Type::last-of-type
:last-of-type
Example: This example implements the :last-child selector.
<!DOCTYPE html><html lang="en">  <head>    <title></title></head>  <body>    <div>        <h1>Welcome To GeeksForGeeks.</h1>        <p>A Computer Science Portal For geeks!</p>    </div></body>  </html>
Sass Code:
$myColor: lime$bkc: black$pad: 5pxp:last-child   color: $myColor  background-color: $bkc  padding: $pad
Output: After compiling the SASS source code you will get this CSS code.CSS Code:
p:last child {
  color: lime;
  background-color: black;
  padding: 5px;
}
Example: last-of-type A Sample Example Is Shown Below
<!DOCTYPE html><html>   <head>    <title>        :last-of-type selector    </title></head>   <body>    <p>The first paragraph.</p>    <p>The second paragraph.</p>    <p>The third paragraph.</p>    <p>The fourth paragraph.</p>    <p>The fifth paragraph.</p>    <p>The sixth paragraph.</p>    <p>The seventh paragraph.</p>    <p>The eight paragraph.</p>    <p>The ninth paragraph.</p>       <p>        <b>Note:</b> Internet Explorer 8        and earlier versions do not support        the :nth-last-of-type() selector.    </p></body>   </html>
Sass Code:
$bk: yellowp:last-of-type   background-color: $bk
Output:CSS Code:
p:last-of-type {
  background-color: yellow;
}
References:
https://www.geeksforgeeks.org/css-last-child-selector/
https://www.geeksforgeeks.org/css-last-of-type-selector/
Supported Browser: The browsers supported by :last-child and :last-of-type selector in SASS are listed below:
Google Chrome 4.0
Edge 9.0
Firefox 3.5
Safari 3.2
Opera 9.6
CSS-Misc
Picked
SASS
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Making a div vertically scrollable using CSS
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to set alert message on button click in jQuery ? - GeeksforGeeks

28 Jul, 2021
In this article, we will learn how to create an alert message in jQuery when a button gets clicked. For this, we will use the jQuery click() method.
jQuery CDN Link: We have linked the jQuery in our file using the CDN link. 
<script src=”https://code.jquery.com/jquery-3.6.0.min.js” integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”;></script>
Example: Create a new HTML file and add the following code to it. In this method, we have set an alert and linked it to a button so that when that button gets clicked then the alert message will be popping out.
HTML
<!DOCTYPE html><html lang="en">  <head>    <script src=        "https://code.jquery.com/jquery-3.6.0.min.js"        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="         crossorigin="anonymous">    </script></head>  <body>    <button id="btn">Click me!</button>      <script>        $(document).ready(function () {            $("#btn").click(function () {                alert("This is an alert message!");            });        });    </script></body>  </html>
Output:
Alert msg using click method
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
set insert() function in C++ STL - GeeksforGeeks

27 Jan, 2021
The set::insert is a built-in function in C++ STL which insert elements in the set container or inserts the elements from a position to another position in the set to a different set. 
Syntax:  
iterator set_name.insert(element)
Parameters: The function accepts a mandatory parameter element which is to be inserted in the set container. Return Value: The function returns an iterator pointing to the inserted element in the container.Time Complexity: log(N) Where ‘N’ is the number of elements in the set Below program illustrates the above function:  
CPP
// CPP program to demonstrate the// set::insert(element) function#include <bits/stdc++.h>using namespace std;int main(){     set<int> s;     // Function to insert elements    // in the set container    s.insert(1);    s.insert(4);    s.insert(2);    s.insert(5);    s.insert(3);     cout << "The elements in set are: ";    for (auto it = s.begin(); it != s.end(); it++)        cout << *it << " ";     return 0;}
 
The elements in set are: 1 2 3 4 5
 
 
Syntax:  
iterator set_name.insert(iterator position, element)
Parameters: The function accepts two parameter which are described below:  
element: It specifies the element to be inserted in the set container.
position: It does not specify the position where the insertion is to be done, it only points to a position from where the searching operation is to be started for insertion to make the process faster. The insertion is done according to the order which is followed by the set container.
Syntax:  
void set_name.insert(iterator position1, iterator position2)
Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another set container. Return Value: No return type => void. Below program illustrates the above function:  
CPP
// CPP program to demonstrate the// set::insert(iterator1, iterator2) function#include <bits/stdc++.h>using namespace std;int main(){     set<int> s1;     // Function to insert elements    // in the set container    s1.insert(1);    s1.insert(4);    s1.insert(2);    s1.insert(5);    s1.insert(3);     cout << "The elements in set1 are: ";    for (auto it = s1.begin(); it != s1.end(); it++)        cout << *it << " ";     set<int> s2;     // Function to insert one set to another    // all elements from where 3 is to end is    // inserted to set2    s2.insert(s1.find(3), s1.end());     cout << "\nThe elements in set2 are: ";    for (auto it = s2.begin(); it != s2.end(); it++)        cout << *it << " ";     return 0;}
 
The elements in set1 are: 1 2 3 4 5 
The elements in set2 are: 3 4 5
 
 
 
messi10goat
chaitanyasahu
CPP-Functions
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Object Oriented Programming in C++
Put a Shutdown Timer on your Windows Desktop - GeeksforGeeks

12 Mar, 2021
It might be that you often forget to turn off your PC or you have some task running on the system that’s going to take some time to complete, and you want the system to automatically shut down after the task is complete. 
You can tackle this issue without using any third-party software. This article will guide you through the simple process of resolving the same issue. To do so follow the below steps:
Step 1: Click on the Start button, type cmd.exe then press Enter.
Step 2: In the Command Prompt window that appears, type the below command:
shutdown –s -t 300
Note: The ‘300’ indicates 300 seconds, so your computer will shut down in five minutes.
You can adjust the shutdown time. For example, for the seven-hour timer, you’d need to change it to ‘25200’. 
Step 3: Press Enter to start the countdown.
Windows will show a warning when you’re a few minutes from being signed out. If you need more time, return to Command Prompt window and type the below command to abort the process:
shutdown-a 
If you find yourself using this process a lot, it is best to create a desktop shortcut for it. To do follow the below steps:
Step 1: Right-click an empty part of your desktop, select New, then Shortcut.
Step 2: In the ‘Type the location of the item:’ section, add the following:
 C:\windows\System32\cmd.exe” /k shutdown –s –t 25200
 Note: 25200 will set a seven-hour timer.
Step 3: Click Next, give your shortcut a name, then Finish.
You might also want to create a desktop shortcut to abort the shutdown. Repeat the process above and type the following command:
C:\Windows\System32\cmd.exe” /k shutdown –a
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Install Jupyter Notebook on MacOS?
How to Set Git Username and Password in GitBash?
Installing MinGW Tools for C/C++ and Changing Environment Variable
How to Install Metasploit 6 on Android using Termux (No Root)?
Top Programming Languages for Android App Development
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
Micro - Lightweight terminal based text editor - GeeksforGeeks

21 Jul, 2021
Micro is a terminal-based text editor, and it is very easy to install and use. The micro editor is developed to be the successor of nono editor. It has no external decencies and no external files are needed. It is a single program. Now let’s see the features of the micro text editor.
Easy to install and use and easy to configure
No external dependencies
Syntax highlighting for more than 130 languages
Command Keybindings like nano
Plugin system, we can install and use the plugins.
Simple auto-completion
Copy and paste with the system clipboard
Mouse support
Now let’s see how can we install the micro editor on the different systems. There are many ways by which we can install the micro editor on the system.
To install the micro editor, there is one script created by micro. Which download the latest prebuild binary and install it on the system. To use this script to install micro, use the following command:
 curl https://getmic.ro | bash
Then move the micro file to /usr/bin/ folder to execute micro as a command
sudo mv micro /usr/bin/
Now, let’s see how can we install the micro editor using the package managers.
To install the micro editor on Linux distro, use the following command according to your Linux distro:
For Ubuntu:
sudo apt-get install micro
For Fedora:
sudo dnf install micro
For Arch Linux
sudo pacman -S micro
For Solus:
sudo eopkg install micro
To install micro editor on macOS, use the brew package manager :
brew install micro
For windows, we can use Chocolatey and Scoop to install the micro editor:
choco installs micro
or
scoop install micro
Now we have installed the micro editor on the system. Let’s see how can we use it.
To open micro editor use the micro command like:
micro
Then you can see the editor is started
Now to save the file using the ctrl+s key. Then the micro editor will ask you the filename to save the file then write the file name and press enter
Then your file gets saved with a mentioned name. To close the file use cnt+q keys. Then micro will ask you about to save the changes or not. Then simply press y key.
To open the file with micro just mention the file name after the micro command:
micro filename
To know more key-bindings in the micro use the Alt+g keys then you will see all key binding to use 
For help press Ctrl+g. And for more information or with commands:
man micro
Linux-Unix
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
How to set focus on an input field after rendering in ReactJS ? - GeeksforGeeks

05 Jan, 2021
Setting focus on an input field after rendering in ReactJS can be done in the following ways, but before doing that, set up your project structure with the following steps:
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Approach 1: we can do it in componentDidMount() function and refs callback. For example:
componentDidMount() {
  this.nameInput.focus();
}
Filename: App.js
Javascript
import React, { Component } from "react";class App extends Component {    componentDidMount() {    this.nameInput.focus();  }    render() {    return (      <div>        <input          defaultValue="It Won't focus"        />        <input          ref={(input) => { this.nameInput = input; }}          defaultValue="It will focus"        />      </div>    );  }  }  export default App;
Approach 2: If we just want to focus on an element when it mounts (initially renders) a simple use of the autoFocus attribute will do. we can use the autoFocus prop to have an input automatically focus when mounted. 
Filename: App.js
Javascript
import React, { Component } from "react";  class App extends Component  {      render() {    return(    <div>      <input         defaultValue="It Won't focus"       />      <input autoFocus        defaultValue="It will focus"      />    </div>    );  }          }  export default App;
Approach 3: We can use the below syntax using the inline ref property.
<input ref={input => input && input.focus()}/>
Filename: App.js
Javascript
import React, { Component } from "react";  class App extends Component  {      render() {    return(      <div>        <input           defaultValue="It Won't focus"         />        <input           ref={(input) => {input && input.focus() }}           defaultValue="It will focus"        />      </div>    );  }            }  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Lodash _.debounce() Method
Angular File Upload
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
HTTP headers | Digest - GeeksforGeeks

31 Oct, 2019
The Digest HTTP header is a response HTTP header that provides the requested resource with a small value generated by a hash function from a whole message. The Digest HTTP header is a response header that provides a digest of the requested resource. The entire representation is used to calculate the digest. Multiple digest values for a single resource is also possible as the representation depends on Content-Type and Content-Encoding.
Syntax:
Digest:<digest-algorithm>=<digest-value>
Directives: This header accepts two directives as mentioned above and described below:
<digest-algorithm>: It contains defined supported algorithms, example SHA-256 and SHA-512.
<digest-value>: It holds the result of encoding and applying the digest algorithm to the resource representation.
Examples:
It provides the resource with the sha-256 algorithm and also provides the digest value.Digest: sha-256=nOJRJgeeksforgeeksN3OWDUo9DBPE=
Digest: sha-256=nOJRJgeeksforgeeksN3OWDUo9DBPE=
It provides the resource with the sha-512 algorithm and also provides the digest value. In addition to that, it provides UNIX sum algorithm which is subject to collisions.Digest: sha-512=\vdtgeeksforgeeks8nOJRJN3OWDDBPE=, unixsum=69
Digest: sha-512=\vdtgeeksforgeeks8nOJRJN3OWDDBPE=, unixsum=69
Supported Browsers: The browsers are compatible with HTTP Digest header are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
Python - Remove Units from Value List - GeeksforGeeks

11 Jan, 2022
Sometimes, while working with Python value lists, we can have a problem in which we need to perform removal of units that come along with values. This problem can have direct application in day-day programming and data preprocessing. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [“54 cm”, “23 cm”, “12cm”, “19 cm”], unit = “cm”Output : [’54’, ’23’, ’12’, ’19’]
Input : test_list = [“54 cm”], unit = “cm”Output : [’54’]
Method #1 : Using regex() + list comprehensionThe combination of these functions can be used to solve this problem. In this, we approach by extracting just the numbers using regex, and remove rest of string units.
Python3
# Python3 code to demonstrate working of # Remove Units from Value List# Using list comprehension + regex()import re  # initializing listtest_list = ["54 kg", "23 kg", "12kg", "19  kg"]   # printing original listprint("The original list is : " + str(test_list))  # initializing unit unit = "kg"  # Remove Units from Value List# Using list comprehension + regex()res = re.findall('\d+', ' '.join(test_list))  # printing result print("List after unit removal : " + str(res))
The original list is : ['54 kg', '23 kg', '12kg', '19  kg']
List after unit removal : ['54', '23', '12', '19']

 
Method #2 : Using replace() + strip() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of replacing unit with empty string to remove it using replace() and stray spaces are handled using strip().
Python3
# Python3 code to demonstrate working of # Remove Units from Value List# Using replace() + strip() + list comprehensionimport re  # initializing listtest_list = ["54 kg", "23 kg", "12kg", "19  kg"]   # printing original listprint("The original list is : " + str(test_list))  # initializing unit unit = "kg"  # Remove Units from Value List# Using replace() + strip() + list comprehensionres = [sub.replace(unit, "").strip() for sub in test_list]  # printing result print("List after unit removal : " + str(res))
The original list is : ['54 kg', '23 kg', '12kg', '19  kg']
List after unit removal : ['54', '23', '12', '19']

rajeev0719singh
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to Use Do While Loop in Excel VBA? - GeeksforGeeks

30 Jul, 2021
A Do...While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop
The Do While loop is used in two ways:
Do...while loop which checks the condition at the STARTING of the loop.
Do...while loop which checks the condition at the  END of the loop.
Syntax 1:
Do While condition
  [statements]
  [Exit Do]
  [statements]
Loop  
Syntax 2: 
Do While 
 [statements]
[Exit Do]
[statements]
Loop  condition
Follow the below steps to implement a Do-While loop:
Step 1: Define a Macro
Private Sub Demo_Loop()
End Sub
Step 2: Define variables
j=2
i=1
Step 3: Write Do While Loop. You can write condition at the beginning or at the end
Do While i < 5
Step 4: Write statements to be executed in loop
msgbox "Table of 2 is : " & (j*i)
     i=i+1
Step 5: End loop.
Now let’s take a look at some of the examples.
Example 1: Do...while loop which checks the condition at the STARTING of the loop. The below example uses Do...while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True. We will print Table of 2 using Do...while loop;
Private Sub Demo_Loop()
        j=2
       i=1
      Do While i < 5
     msgbox "Table of 2 is : " & (j*i)
      i=i+1
      Loop
End Sub
Output:
Example 2: Do...while loop which checks the condition at the  END of the loop. The below example checks the condition at the end of the loop. The major difference between these two syntax is explained in the following example.
Private Sub Demo_Loop()
      i = 10
     Do
     i = i + 1
     MsgBox "The value of i is : " & i
  Loop While i < 3 'Condition is false.Hence loop is executed once.
End Sub
When the above code is executed, it prints the following output in a message box.
Output:
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Calculate Deciles in Excel?
Apache Pig - ROUND()

The ROUND() function is used to get the value of an expression rounded to an integer (if the result type is float) or rounded to a long (if the result type is double).
grunt> ROUND()

Assume that there is a file named math.txt in the HDFS directory /pig_data/. This file contains integer and floating point values as shown below.
math.txt
5
16 
9 
2.5 
5.9 
3.1 

And, we have loaded this file into Pig with a relation named math_data as shown below.
grunt> math_data = LOAD 'hdfs://localhost:9000/pig_data/math.txt' USING PigStorage(',')
   as (data:float);
Let us now generate round values of the contents of the math.txt file using ROUND() function as shown below.
grunt> round_data = foreach math_data generate (data), ROUND(data);
The above statement stores the result in the relation named round_data. Verify the contents of the relation using the Dump operator as shown below.
grunt> Dump round_data;
 
(5.0,5) 
(16.0,16) 
(9.0,9) 
(2.5,3) 
(5.9,6) 
(3.1,3) 


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page