code-rag-bench/online-tutorials huggingface dataset:
Node.js fs.mkdir() Method

12 Oct, 2021
The fs.mkdir() method i Node.js is used to create a directory asynchronously.
Syntax
fs.mkdir(path, mode, callback)
Parameters: This method accept three parameters as mentioned above and described below:
path: This parameter holds the path of the directory has to be created.
mode: This parameter holds the recursive boolean value. The mode option is used to set the directory permission, by default it is 0777.
callback: This parameter holds the callback function that contains error. The recursive option if set to true will not give an error message if the directory to be created already exists.
Below examples illustrate the use of fs.mkdir() method in Node.js:
Example 1:
// Node.js program to demonstrate the   // fs.mkdir() Method  // Include fs and path moduleconst fs = require('fs');const path = require('path');   fs.mkdir(path.join(__dirname, 'test'), (err) => {    if (err) {        return console.error(err);    }    console.log('Directory created successfully!');});
Output:
Directory created successfully!
Directory Structure Before running the code:
Directory Structure After running the code:
Note: If you will run this program again, then it will display an error message as the directory already exists. To overcome this error we will use the recursive option.
Example 2: This example illustrate the use to recursive option.
// Node.js program to demonstrate the   // fs.mkdir() Method  // Include fs and path moduleconst fs = require('fs');const path = require('path');  fs.mkdir(path.join(__dirname, 'test'),  { recursive: true }, (err) => {    if (err) {      return console.error(err);    }    console.log('Directory created successfully!');  });
Output:
Directory created successfully!
Reference: https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Flatten given list of dictionaries

12 Jan, 2022
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries.
Given below are a few methods to solve the given task.
Method #1: Using Naive Method
Python3
# Python code to demonstrate# to flatten list of dictionaries  # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]  # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # code to flatten list of dictionaryres = {}for d in ini_dict:    res.update(d)      # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'b': 2, 'a': 1, 'c': 3}

 
Method #2: Using dict comprehension
Python3
# Python code to demonstrate# to flatten list of dictionaries  # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]  # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # code to flatten list of dictionaryres = {k: v for d in ini_dict for k, v in d.items()}      # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'a': 1, 'c': 3, 'b': 2}

 Method #3: Using reduce
Python3
# Python code to demonstrate# to flatten list of dictionariesfrom functools import reduce   # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]  # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # code to flatten list of dictionaryres = reduce(lambda d, src: d.update(src) or d, ini_dict, {})      # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'a': 1, 'c': 3, 'b': 2}

 Method #4: Using collections.ChainMap
Python3
# Python code to demonstrate# to flatten list of # dictionaries  from collections import ChainMap  # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]  # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # code to flatten list of dictionaryres = ChainMap(*ini_dict)      # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result ChainMap({'a': 1}, {'b': 2}, {'c': 3})

rajeev0719singh
Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
semanage - Unix, Linux Command

# View SELinux user mappings
$ semanage user -l
# Allow joe to login as staff_u
$ semanage login -a -s staff_u joe
# Add file-context for everything under /web (used by restorecon)
$ semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
# Allow Apache to listen on port 81
$ semanage port -a -t http_port_t -p tcp 81
LinkedList size() Method in Java

10 Dec, 2018
The Java.util.LinkedList.size() method is used to get the size of the Linked list or the number of elements present in the linked list.
Syntax:
LinkedList.size()

Parameters: This method does not take any parameter.
Return Value: This method returns the size or the number of elements present in the LinkedList.
Below program illustrate the Java.util.LinkedList.size() method:
// Java code to illustrate size()import java.io.*;import java.util.LinkedList;  public class LinkedListDemo {    public static void main(String args[])    {          // Creating an empty LinkedList        LinkedList<String> list = new LinkedList<String>();          // Using add() method to add elements in the list        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");          // Displaying the linkedlist        System.out.println("LinkedList:" + list);                  // Displaying the size of the list        System.out.println("The size of the linked list is: "                                                 + list.size());    }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The size of the linked list is: 5

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
The most occurring number in a string using Regex in python

29 Dec, 2020
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python.
It is guaranteed that no two element have the same frequency
Input :geek55of55geeks4abc3dr2 
Output :55

Input :abcd1def2high2bnasvd3vjhd44
Output :2

Approach:Extract all the numbers from a string str using re.findall() function from regex library in python, and with the use of Counter function from collection library we can get the most occurred element.
Below is the Python implementation of above approach
# your code goes here# Python program to # find the most occurring element import re from collections import Counter   def most_occr_element(word):          # re.findall will extract all the elements     # from the string and make a list    arr = re.findall(r'[0-9]+', word)              # to store maxm frequency    maxm = 0        # to store maxm element of most frequency    max_elem = 0          # counter will store all the number with     # their frequencies    # c = counter((55, 2), (2, 1), (3, 1), (4, 1))        c = Counter(arr)        # Store all the keys of counter in a list in    # which first would we our required element        for x in list(c.keys()):          if c[x]>= maxm:            maxm = c[x]            max_elem = int(x)                      return max_elem  # Driver program if __name__ == "__main__":     word = 'geek55of55gee4ksabc3dr2x'    print(most_occr_element(word))
55

Python Regex-programs
Python string-programs
python-regex
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize a static Map using Java 9 Map.of()

14 Jul, 2022
In this article, a static map is created and initialised in Java using Java 9.
Static Map in JavaA static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.
Java 9 feature – Map.of() methodIn Java 9, Map.of() was introduced which is a convenient way to create instances of Map interface. It can hold up to 10 key-value pairs.
Approach:
Pass the map values as Key and Value pair in the Map.of() method.
A static factory Map instance is returned.
Store it in Map and use.
Below is the implementation of the above approach:
Example 1:
// Java program to create a static map using Java 9  import java.util.*;  class GFG {      // Declaring and instantiating the static map    private static Map<String, String> map        = Map.of("1", "GFG",                 "2", "Geek",                 "3", "GeeksForGeeks");      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}
Output:
{3=GeeksForGeeks, 2=Geek, 1=GFG}

Example 2: To show the error when 10 key-value pairs are given
// Java program to create a static map using Java 9  import java.util.*;  class GFG {      // Declaring and instantiating the static map    private static Map<String, String> map        = Map.of("1", "GFG",                 "2", "Geek",                 "3", "GeeksForGeeks",                 "4", "G",                 "5", "e",                 "6", "e",                 "7", "k",                 "8", "s",                 "9", "f",                 "10", "o");      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}
Output:
{10=o, 9=f, 8=s, 7=k, 6=e, 5=e, 4=G, 3=GeeksForGeeks, 2=Geek, 1=GFG}

Example 3: To show the error when more than 10 key-value pairs are given
// Java program to create a static map using Java 9  import java.util.*;  class GFG {      // Declaring and instantiating the static map    private static Map<String, String> map        = Map.of("1", "GFG",                 "2", "Geek",                 "3", "GeeksForGeeks",                 "4", "G",                 "5", "e",                 "6", "e",                 "7", "k",                 "8", "s",                 "9", "f",                 "10", "o",                 "11", "r");      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}
Compilation Error:
Main.java:12: error: no suitable method found for
 of(String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String)
        
1 error

Related Articles:
Initialize a static map in Java with Examples
Initialize a static Map using Stream in Java
java-map
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Arrays and Collection in Java - GeeksforGeeks

29 Dec, 2021
An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. On the other hand, any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it.
The most essential thing while dealing Collection is to have super strong grasp of Collection framework which in one go is depicted via below image as follows:
Example
Java
// Java Program to Illustrate Difference// Between Arrays and Collection // Importing required classesimport java.util.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Arrays        String[] gfg            = new String[] { "G", "E", "E", "K", "S" };         // Trying printing the above array        System.out.print(gfg);         // New Line        System.out.println();         // Collection        // Let us arbitarly create an empty ArrayList        // of string type        ArrayList<String> al = new ArrayList<String>();         // Adding elements to above List        // using add() method        al.add("g");        al.add("e");        al.add("e");        al.add("k");        al.add("s");         // Printing all elements of Collection (ArrayList)        System.out.println(al);    }}
[Ljava.lang.String;@3d075dc0
[g, e, e, k, s]
Now after having understanding of Arrays and Collection, let us now tabulate differences between them which is as follows:
mohddanishsajid
nitinagrawalup
sagartomar9927
sumitgumber28
rkbhola5
Java-Arrays
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
How do I convert a datetime to a UTC timestamp in Python?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object. If you have the datetime object in local timezone, first replace the timezone info and then fetch the time. 
from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)
This will give the output −
1445212800.0
If you're on Python 2, then you can use the total_seconds function to get the total seconds since epoch. And if you want to get rid of the timestamp, you can first subtract time from 1 Jan 1970. 
from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
print(timestamp)
This will give the output −
1445212800.0
How to make page links in HTML Page?

With HTML, easily add page links to an HTML page. Link contact us, about, home or any other external website page using the page links, which gets added inside an HTML document. To make page links in an HTML page, use the <a> and </a> tags, which are the tags used to define the links.
The <a> tag indicates where the link starts and the </a> tag indicates where it ends. Whatever text gets added inside these tags, will work as a link. Add the URL for the link in the <a href=” ”>. Just keep in mind that you should use the <a>...</a> tags inside <body>...</body> tags.
You can try the following code to make page links in an HTML page:
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Links</title>
   </head>

   <body>
      <h1>Reach us here</h1>
      <a href="https://www.tutorialspoint.com/about/contact_us.htm">Contact</a>
   </body>
</html>
How to create a 3D outset and inset border using CSS ? - GeeksforGeeks

21 May, 2021
In this article, we will create a 3D outset and inset border using CSS. Inset border property makes the content appear embedded (inside the surface) and on the other hand, the outset property makes the content appear embossed (outside the surface). You can achieve this task by using the border-style property that is used to decorate the border.
3D inset border: It is used to define a 3D inset border and its effect depends on the border-color value.
Syntax:
element_name(or selector).inset {border-style: inset;}
Example 1:
HTML
<!DOCTYPE html><html> <head>    <style>        body {            text-align: center;        }                 p {            font-size: 30px;            margin-top: -50px;        }                 p.inset {            border-style: inset;             /* Inset style property */            font-size: 40px;            margin-top: 30px;        }                 h2 {            color: green;            font-size: 50px;        }    </style></head> <body>    <h2>GeeksForGeeks</h2>      <p>A computer science portal for geeks</p>      <p class="inset">        The content of this paragraph is        styled using inset property    </p> </body> </html>
   
Output:
 
 
3D outset border: It is used to define a 3D outset border and its effect depends on the border-color value.
 
Syntax:
 
element_name(or selector).outset {border-style: outset;}
 
Example 2:
 
HTML
<!DOCTYPE html><html> <head>    <style>        body {            text-align: center;        }                 p {            font-size: 30px;            margin-top: -50px;        }                 p.outset {            border-style: outset;             /* outset style property */            font-size: 40px;            margin-top: 30px;        }                 h2 {            color: green;            font-size: 50px;        }    </style></head> <body>    <h2>GeeksForGeeks</h2>      <p>A computer science portal for geeks</p>      <p class="outset">        The content of this paragraph is        styled using outset property    </p> </body> </html>
Output:
akshaysingh98088
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Distinguish between Finite Automata and Turing Machine

Before understanding the differences between the finite automata (FA) and the turing machine (TM), let us learn about these concepts.
Finite automata is an abstract computing device
It is a mathematical model of a system with discrete inputs, outputs, states and set of transitions from state to state that occurs on input symbol from alphabet Σ
FA can be represented as following in the theory of computation (TOC) −
Graphical (Transition diagram)
Graphical (Transition diagram)
Tabular (Transition table)
Tabular (Transition table)
Mathematical (Transition function)
Mathematical (Transition function)
A Finite automata is a five tuples
M=(Q, Σ, δ,q0,F)
Where,
Q − Finite set called states
Q − Finite set called states
Σ − Finite set called alphabets
Σ − Finite set called alphabets
δ − Q × Σ → Q is the transition function
δ − Q × Σ → Q is the transition function
q0 ε Q is the start or initial state
q0 ε Q is the start or initial state
F − Final or accept state
F − Final or accept state
Turing machines are more powerful than both finite automata and pushdown automata. They are as powerful as any computer we have ever built.
A Turing machine can be formally described as seven tuples ( Q,X, Σ,δ,q0,B,F)
Where,
Q is a finite set of states
Q is a finite set of states
X is the tape alphabet
X is the tape alphabet
Σ is the input alphabet
Σ is the input alphabet
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
q0 is the initial state
q0 is the initial state
B is the blank symbol
B is the blank symbol
F is the final state.
F is the final state.
The major differences between Finite automata and Turing machine are given below −
Tk - Canvas Bitmap Widget

Bitmap widget is used to add bitmap to canvas. The syntax for bitmap widget is shown below −
canvasName create bitmap x y options

x and y set the location of bitmap −
The options available for the bitmap widget are listed below in the following table −
-anchor position
The bitmap will be positioned relative to the x and y locations. Center is default an other options are n, s, e, w, ne, se, sw, and nw.
-bitmap name
Defines the bitmap to display. The available bitmaps in Tk include warning, question, questhead, info, hourglass, error, gray12, gray25, gray50, and gray75.
A simple example for bitmap widget is shown below −
#!/usr/bin/wish

canvas .myCanvas -background red -width 100 -height 100 
pack .myCanvas
.myCanvas create bitmap 50 50 -bitmap info
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
Date Formatting Using printf

Date and time formatting can be done very easily using the printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code.
Live Demo
import java.util.Date;
public class DateDemo {

   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display time and date
      String str = String.format("Current Date/Time : %tc", date );

      System.out.printf(str);
   }
}
This will produce the following result −
Current Date/Time : Sat Dec 15 16:37:57 MST 2012
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted.
The index must immediately follow the % and it must be terminated by a $.
Live Demo
import java.util.Date;
public class DateDemo {

   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display time and date
      System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
   }
}
This will produce the following result −
Due date: February 09, 2004
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.
Live Demo
import java.util.Date;
public class DateDemo {

   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display formatted date
      System.out.printf("%s %tB %<te, %<tY", "Due date:", date);
   }
}
This will produce the following result −
Due date: February 09, 2004
How do I declare a two-dimensional array in C++ using new?

A dynamic 2D array is basically an array of pointers to arrays. So you first need to initialize the array of pointers to pointers and then initialize each 1d array in a loop.
#include<iostream>
using namespace std;

int main() {
   int rows = 3, cols = 4;
   int** arr = new int*[rows];
   for(int i = 0; i < rows; ++i)
   arr[i] = new int[cols];
   return 0;
}

This will create an 2D array of size 3x4. Be vary of clearing the memory in such cases as you'll need to delete the memory in the same way you allocated it but in reverse order, ie, you'll need to first delete 1D arrays then the array of pointers.
Insecure Direct Object References

A direct object reference is likely to occur when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key without any validation mechanism which allows attackers to manipulate these references to access unauthorized data.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
The App uses unverified data in a SQL call that is accessing account information.
String sqlquery = "SELECT * FROM useraccounts WHERE account = ?";
PreparedStatement st = connection.prepareStatement(sqlquery, ??);
st.setString( 1, request.getParameter("acct"));
ResultSet results = st.executeQuery( );
The attacker modifies the query parameter in their browser to point to Admin.
http://webapp.com/app/accountInfo?acct=admin

Step 1 − Login to Webgoat and navigate to access control flaws Section. The goal is to retrieve the tomcat-users.xml by navigating to the path where it is located. Below is the snapshot of the scenario.
Step 2 − The path of the file is displayed in 'the current directory is' field - C:\Users\userName$\.extract\webapps\WebGoat\lesson_plans\en and we also know that the tomcat-users.xml file is kept under C:\xampp\tomcat\conf
Step 3 − We need to traverse all the way out of the current directory and navigate from C:\ Drive. We can perform the same by intercepting the traffic using Burp Suite.
Step 4 − If the attempt is successful, it displays the tomcat-users.xml with the message "Congratulations. You have successfully completed this lesson."
Developers can use the following resources/points as a guide to prevent insecure direct object reference during development phase itself.
Developers should use only one user or session for indirect object references.
Developers should use only one user or session for indirect object references.
It is also recommended to check the access before using a direct object reference from an untrusted source.
It is also recommended to check the access before using a direct object reference from an untrusted source.

    36 Lectures 
     5 hours 

 Sharad Kumar

    26 Lectures 
     2.5 hours 

 Harshit Srivastava

    47 Lectures 
     2 hours 

 Dhabaleshwar Das

    14 Lectures 
     1.5 hours 

 Harshit Srivastava

    38 Lectures 
     3 hours 

 Harshit Srivastava

    32 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Python | Pandas Index.to_series() - GeeksforGeeks

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.to_series() function create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index. It is possible to set a new index label for the newly created Series by passing the list of new index labels.
Syntax: Index.to_series(index=None, name=None)
Parameters :index : index of resulting Series. If None, defaults to original indexname : name of resulting Series. If None, defaults to name of original index
Returns : Series : dtype will be based on the type of the Index values.
Example #1: Use Index.to_series() function to convert the index into a Series.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'],                                   name ='Student')  # Print the Indexprint(idx)
Output :
Let’s convert the index into a Series.
# convert the index into a seriesidx.to_series()
Output :The function has converted the index into a series. By default, the function has created the index of the series using the values of the original Index. Example #2: Use Index.to_series() function to convert the index into a series such that the series created uses new index value.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Alice', 'Bob', 'Rachel', 'Tyler', 'Louis'],                                            name ='Winners')  # Print the Indexprint(idx)
Output :
Let’s convert the index into a series.
# convert the index into a seriesidx.to_series(index =['Student 1', 'Student 2', 'Student 3',                                  'Student 4', 'Student 5'])
Output :The function has converted the index into a series. We have passed a list of index labels to be used for the newly created Series.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Arduino - delayMicroseconds () function

The delayMicroseconds() function accepts a single integer (or number) argument. This number represents the time and is measured in microseconds. There are a thousand microseconds in a millisecond, and a million microseconds in a second.
Currently, the largest value that can produce an accurate delay is 16383. This may change in future Arduino releases. For delays longer than a few thousand microseconds, you should use the delay() function instead.
delayMicroseconds (us) ;

where, us is the number of microseconds to pause (unsigned int)
/* Flashing LED
   * ------------
   * Turns on and off a light emitting diode(LED) connected to a digital
   * pin, in intervals of 1 seconds. *
*/

int ledPin = 13; // LED connected to digital pin 13

void setup() {
   pinMode(ledPin, OUTPUT); // sets the digital pin as output
}

void loop() {
   digitalWrite(ledPin, HIGH); // sets the LED on
   delayMicroseconds(1000); // waits for a second
   digitalWrite(ledPin, LOW); // sets the LED off
   delayMicroseconds(1000); // waits for a second
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Python | Compare tuples

21 Nov, 2019
Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it’s corresponding index in other tuple. This can have many possible applications. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using all() + generator expression + zip()The combination of above functionalities can be used to perform this task. In this, we just compare all elements using all(). The cross tuple access is done by zip() and generator expression gives us the logic to compare.
# Python3 code to demonstrate working of# Comparing tuples# using generator expression + all() + zip()  # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (13, 5, 18)  # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Comparing tuples# using generator expression + all() + zip()res = all(x < y for x, y in zip(test_tup1, test_tup2))  # printing resultprint("Are all elements in second tuple greater than first ? : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (13, 5, 18)
Are all elements in second tuple greater than first ? : True

 
Method #2 : Using all() + map() + lambdaThe combination of above functionalities can be used to perform this particular task. In this, we perform extension of logic to each element using map() and logic generation by lambda function.
# Python3 code to demonstrate working of# Comparing tuples# using all() + lambda + map()  # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (13, 5, 18)  # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Comparing tuples# using all() + lambda + map()res = all(map(lambda i, j: i < j, test_tup1, test_tup2))  # printing resultprint("Are all elements in second tuple greater than first ? : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (13, 5, 18)
Are all elements in second tuple greater than first ? : True

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python | Repeat each element K times in list

08 Apr, 2019
Many times we have this particular use-case in which we need to repeat each element of list K times. The problems of making a double clone have been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehensionThis particular task requires generally 2 loops and list comprehension can perform this particular task in one line and hence reduce the lines of codes and improving code readability.
# Python3 code to demonstrate # repeat element K times# using list comprehension  # initializing list of liststest_list = [4, 5, 6]  # printing original list print("The original list : " +  str(test_list))  # declaring magnitude of repetitionK = 3  # using list comprehension# repeat elements K timesres =  [ele for ele in test_list for i in range(K)]  # printing result print("The list after adding elements :  " + str(res))
The original list : [4, 5, 6]
The list after adding elements :  [4, 4, 4, 5, 5, 5, 6, 6, 6]

 
Method #2 : Using itertools.chain.from_iterable() + itertools.repeat()This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as name suggests does the task of repetition and grouping into a list is done by the from_iterable function.
# Python3 code to demonstrate # repeat element K times# using itertools.chain.from_iterable() + itertools.repeat()import itertools  # initializing list of liststest_list = [4, 5, 6]  # printing original list print("The original list : " +  str(test_list))  # declaring magnitude of repetitionK = 3  # using itertools.chain.from_iterable() # + itertools.repeat() repeat elements K timesres = list(itertools.chain.from_iterable(itertools.repeat(i, K)                                           for i in test_list))  # printing result print("The list after adding elements :  " + str(res))
The original list : [4, 5, 6]
The list after adding elements :  [4, 4, 4, 5, 5, 5, 6, 6, 6]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Perform Debouncing in ReactJS ?

29 Jun, 2021
A Debouncing Events in ReactJS will allow you to call a function that ensures that a time-consuming task does not fire so often. It’s a function that takes a function as a parameter and wraps that function in a closure and returns it so this new function displays the “wait for a bit” behavior.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app react-debouncing    
Step 2: After creating your project folder i.e. react-debouncing, move to it using the following command:
cd react-debouncing
 
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install lodash
Project Structure: It will look like the following.
Project Directory
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { Component } from "react";import { debounce } from "lodash";  class WidgetText extends Component {    state = { text: "" };    handleChange = (e) => {    this.setState({ text: e.target.value });  };    render() {    return (      <div>        <input onChange={this.handleChange} />        <textarea value={this.state.text} />      </div>    );  }}  class App extends Component {    state = { show: true };    handleToggle = debounce(() => {    this.setState(prevState => ({ show: !prevState.show }));  }, 500);    render() {    return (      <div>        <button onClick={this.handleToggle}>Toggle</button>        {this.state.show ? <WidgetText /> : null}      </div>    );  }}  export default App;
Explanation:
Have a simple page with a toggle button, if we click it the input fields go away and click it again to get the input field back and if we type in the input box the text will immediately mirror in the text area below.
We have a React WidgetText component, and it essentially just has the input and text area and then the app component itself has the toggle button.
Conditionally so if we click the toggle button it will come in into the handler grab, the previous state look at it shows bool off of the state and flip it, So if it was true then it will render the WidgetText if it is false we do not render the WidgetText.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NLP | Singularizing Plural Nouns and Swapping Infinite Phrases

26 Feb, 2019
Let’s understand this with an example :
Is our child training enough?Is are our child training enough?
Is our child training enough?
Is are our child training enough?
The verb ‘is’ can only be used with singular nouns. For plural nouns, we use ‘are’. This problem is very common in the real world and we can correct this mistake by creating verb correction mappings that are used depending on whether there’s plural or singular noun in the chunk.
Code #1 : singularize_plural_noun() class
def singularize_plural_noun(chunk):          nnsidx = first_chunk_index(chunk, tag_equals('NNS'))          if nnsidx is not None and     nnsidx + 1 < len(chunk) and     chunk[nnsidx + 1][1][:2] == 'NN':                  noun, nnstag = chunk[nnsidx]        chunk[nnsidx] = (noun.rstrip('s'), nnstag.rstrip('S'))              return chunk
 Code #2 : Singularizing Plurals
singularize_plural_noun([('recipes', 'NNS'), ('book', 'NN')])
Output :
[('recipe', 'NN'), ('book', 'NN')]

The code above looks for the tag NNS to look for Plural Noun. After founding it, if the next word is a noun (determined by making sure the tag starts with NN), then we depluralize the plural noun by removing ‘s’ from the right side of both the tag and the word.
Swapping Infinite PhrasesAn infinitive phrase is of the form A of B, such as ‘world of movies’. On can transform this to ‘movies world’ and it still holds the same meaning.
Code #3 : Let’s understand the swap_infinitive_phrase() class
def swap_infinitive_phrase(chunk):    def inpred(wt):        word, tag = wt        return tag == 'IN' and word != 'like'        inidx = first_chunk_index(chunk, inpred)          if inidx is None:        return chunk          nnidx = first_chunk_index(chunk,                               tag_startswith('NN'),                               start = inidx, step =-1) or 0                                    return chunk[:nnidx] + chunk[inidx + 1:] + chunk[nnidx:inidx]
 Code #4 : Let’s evaluate swap_infinitive_phrase
from transforms import swap_infinitive_phrase  swap_infinitive_phrase([('book', 'NN'),                         ('of', 'IN'), ('recipes', 'NNS')])
Output :
[('recipes', 'NNS'), ('book', 'NN')]

Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Creating an ArrayList with Multiple Object Types in Java

22 Oct, 2021
ArrayList class Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java.util package. 
Syntax: To create an ArrayList of Integer type is mentioned below.
List<Integer> list = new ArrayList <Integer>();
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. 
We will discuss how we can use the Object class to create an ArrayList.
Object class is the root of the class hierarchy. It is being extended by every class in Java either directly or indirectly. If a class doesn’t inherit from any other class then it extends the Object class directly otherwise if it extends any class then it extends the Object class indirectly from its base class. We can use the Object class to declare our ArrayList using the syntax mentioned below. 
ArrayList<Object> list = new ArrayList<Object>();
The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types.
Java
// Java program to create an ArrayList with// Multiple Object Types in Java import java.util.ArrayList; public class GFG {    public static void main(String[] args)    {         // Creating an ArrayList of Object type        ArrayList<Object> arr = new ArrayList<Object>();         // Inserting String value in arr        arr.add("GeeksForGeeks");         //  Inserting Integer value in arr        arr.add(14);         //  Inserting Long value in arr        arr.add(1800L);         // Inserting Double value in arr        arr.add(6.0D);         //  Inserting Float value in arr        arr.add(1.99F);         // arr after all insertions: ["GeeksForGeeks", 14,        // 1800L, 6.0D, 1.99F]         System.out.print(            "ArrayList after all insertions: ");        display(arr);         // Replacing element at index 0 (i.e. an String)        // with an Integer type value 50        arr.set(0, 50);         // Replacing element at index 1 (Integer value)        // with a Double type value        arr.set(1, 10.0D);         // arr after modifications: [50, 10.0D,        // 1800L, 6.0D, 1.99F]         System.out.print("ArrayList after modifications: ");         display(arr);    }     // Function to display elements of the ArrayList    public static void display(ArrayList<Object> arr)    {        for (int i = 0; i < arr.size(); i++) {            System.out.print(arr.get(i) + " ");        }        System.out.println();    }}
  
ArrayList after all insertions: GeeksForGeeks 14 1800 6.0 1.99 
ArrayList after modifications: 50 10.0 1800 6.0 1.99
 
ruhelaa48
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
R - Break Statement

The break statement in R programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
It can be used to terminate a case in the switch statement (covered in the next chapter).
The basic syntax for creating a break statement in R is −
break

v <- c("Hello","loop")
cnt <- 2

repeat {
   print(v)
   cnt <- cnt + 1
	
   if(cnt > 5) {
      break
   }
}
When the above code is compiled and executed, it produces the following result −
[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
numpy.hstack() in Python - GeeksforGeeks

06 Jan, 2019
numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array.
Syntax : numpy.hstack(tup)
Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.
Return : [stacked ndarray] The stacked array of the input arrays.
Code #1 :
# Python program explaining# hstack() function  import numpy as geek  # input arrayin_arr1 = geek.array([ 1, 2, 3] )print ("1st Input array : \n", in_arr1)   in_arr2 = geek.array([ 4, 5, 6] )print ("2nd Input array : \n", in_arr2)   # Stacking the two arrays horizontallyout_arr = geek.hstack((in_arr1, in_arr2))print ("Output horizontally stacked array:\n ", out_arr)
1st Input array : 
 [1 2 3]
2nd Input array : 
 [4 5 6]
Output horizontally stacked array:
  [1 2 3 4 5 6]

 Code #2 :
# Python program explaining# hstack() function  import numpy as geek  # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print ("1st Input array : \n", in_arr1)   in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print ("2nd Input array : \n", in_arr2)   # Stacking the two arrays horizontallyout_arr = geek.hstack((in_arr1, in_arr2))print ("Output stacked array :\n ", out_arr)
1st Input array : 
 [[ 1  2  3]
 [-1 -2 -3]]
2nd Input array : 
 [[ 4  5  6]
 [-4 -5 -6]]
Output stacked array :
  [[ 1  2  3  4  5  6]
 [-1 -2 -3 -4 -5 -6]]

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Retrieve MIN and MAX date in a single MySQL query from a column with date values

For this, you can use aggregate function MIN() and MAX(). Let us first create a table −
mysql> create table DemoTable(AdmissionDate date);
Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-21');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('2018-12-31');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2016-11-01');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('2019-04-11');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2016-02-01');
Query OK, 1 row affected (0.28 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 2019-01-21    |
| 2018-12-31    |
| 2016-11-01    |
| 2019-04-11    |
| 2016-02-01    |
+---------------+
5 rows in set (0.00 sec)
Following is the query to retrieve MIN and MAX date in a single query −
mysql> select MIN(AdmissionDate) AS MinDate,MAX(AdmissionDate) AS MaxDate from DemoTable;
This will produce the following output −
+------------+------------+
| MinDate    | MaxDate    |
+------------+------------+
| 2016-02-01 | 2019-04-11 |
+------------+------------+
1 row in set (0.00 sec)