code-rag-bench/online-tutorials huggingface dataset:
LocalDateTime getMonth() method in Java with Examples - GeeksforGeeks

29 Nov, 2018
The getMonth() method of an LocalDateTime class is used to return month-of-year field. This field is returned using the Month enum. The enum can provide the primitive int value.
Syntax:
public Month getMonth()

Parameter: This method does not accept any parameter.
Returns: This method returns the enum Month for the month of this LocalDateTime.
Below programs illustrate the LocalDateTime.getMonth() method:
Program 1:
// Java program to demonstrate// LocalDateTime.getMonth() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDateTime Object        LocalDateTime local            = LocalDateTime.parse("2007-12-02T22:48:29");          // get Month enum value field        Month month = local.getMonth();          // print result        System.out.println("Month: "                           + month);    }}
Month: DECEMBER

Program 2:
// Java program to demonstrate// LocalDateTime.getMonth() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDateTime Object        LocalDateTime local            = LocalDateTime.parse("2017-07-22T09:32:42");          // get Month enum value field        Month month = local.getMonth();          // print result        System.out.println("Month: "                           + month);    }}
Month: JULY

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#getMonth()
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
jQuery - position( ) Method

The position( ) method gets the top and left position of an element relative to its offset parent.
The returned object contains two Integer properties, top and left. For accurate calculations make sure to use pixel values for margins, borders and padding. This method only works with visible elements.
Here is the simple syntax to use this method −
selector.position( )

Here is the description of all the parameters used by this method −
NA
NA
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
			
            $("div").click(function () {
               var position = $(this).position();
               $("#lresult").html("left position: <span>" + position.left + "</span>.");
               $("#tresult").html("top position: <span>" + position.top + "</span>.");
            });
				
         });
      </script>
		
      <style>
         div { width:60px; height:60px; margin:5px; float:left; }
      </style>
   </head>
	
   <body>
      <p>Click on any square:</p>
      <span id = "lresult"> </span>
      <span id = "tresult"> </span>
		
      <div  style = "background-color:blue;"></div>
      <div  style = "background-color:pink;"></div>
      <div  style = "background-color:#123456;"></div>
      <div  style = "background-color:#f11;"></div>
   </body>
</html>
This will produce following result −
Click on any square −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Copy all rows of a table to another table in MySQL?

To copy all rows of a table to another table, use the below syntax −
insert into yourTableName2(yourColumnName1,...N) select yourColumnName1,..N from yourTableName1;
Let us first create a table −
mysql> create table DemoTable1(FirstName varchar(100));
Query OK, 0 rows affected (1.11 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values('Bob');
Query OK, 1 row affected (0.40 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| John      |
| Chris     |
| Bob       |
+-----------+
3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2 (EmployeeName varchar(100));
Query OK, 0 rows affected (0.78 sec)
Following is the query to copy all rows of a table to another table −
mysql> insert into DemoTable2(EmployeeName) select FirstName from DemoTable1;
Query OK, 3 rows affected (0.52 sec)
Records: 3 Duplicates: 0 Warnings: 0
Let us now check the records of the 2nd table, wherein we have set the records of 1st table −
mysql> select *from DemoTable2;
This will produce the following output −
+--------------+
| EmployeeName |
+--------------+
| John         |
| Chris        |
| Bob          |
+--------------+
3 rows in set (0.00 sec)
Binary Heap in Data Structure

Heap or Binary Heap is a special case of balanced binary tree data structure. This is complete binary tree structure. So up to l-1 levels it is full, and at l level, all nodes are from left. Here the root-node key is compared with its children and arranged accordingly. If a has child node b then −
key(a) ≥ key(b)
As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types the Max Heap and the Min Heap.
These are examples of Max and Min Heap respectively −
Bootstrap complex form layout for combined vertical/inline fields with HTML

Bootstrap form for combined vertical/ inline fields −
<div class="row">
   <div class="col-md-8">
      <div class="row">
         <div class="col-md-3">
            Left side
         </div>
         <div class="col-md-9">
            Right side
            <div class="row">
               <div class="col-md-12">
                  longer forms
               </div>
            </div>
            <div class="row">
               <div class="col-md-3">
                  shorter forms
               </div>
               <div class="col-md-3">
                  shorter forms
               </div>
               <div class="col-md-3">
                  shorter forms
               </div>
               <div class="col-md-3">
                  shorter forms
               </div>
            </div>
         </div>
      </div>
   </div>
   <div class="col-md-4">
      Right
   </div>
</div>
Python | Decimal from_float() method

23 May, 2022
Decimal#from_float() : from_float() is a Decimal class method which converts  a float to a decimal number, exactly.
Syntax: Decimal.from_float() Parameter: Decimal values Return: converts  a float to a decimal number, exactly.
Code #1 : Example for from_float() method 
Python3
# Python Program explaining# from_float() method # loading decimal libraryfrom decimal import *  # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)  # Using Decimal.from_float() methodprint ("\n\nDecimal a with from_float() method : ", a.from_float(0.1)) print ("Decimal b with from_float() method : ", b.from_float(float('nan')))
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with from_float() method :  0.1000000000000000055511151231257827021181583404541015625
Decimal b with from_float() method :  NaN
Code #2 : Example for from_float() method 
Python3
# Python Program explaining# from_float() method # loading decimal libraryfrom decimal import *  # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)  # Using Decimal.from_float() methodprint ("\n\nDecimal a with from_float() method : ", a.from_float(0.02)) print ("Decimal b with from_float() method : ", b.from_float(float('-inf')))
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with from_float() method :  0.0200000000000000004163336342344337026588618755340576171875
Decimal b with from_float() method :  -Infinity
sweetyty
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
Create a directory in Python
What does symbol tilde (~) denotes in CSS ?

17 Oct, 2019
In CSS, the symbol tilde(~) is know as Subsequent-sibling Combinator (also known as tilde or squiggle or twiddle or general-sibling selector). As the name suggests it is made of the “tilde” (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree. It is used to select all the second sequences which are preceded by the first sequence (not necessarily immediately) or in simple words selects all elements that are siblings of a specified element.
Syntax:
first-sequence ~ second-sequence {
    /* property:value; */
}

Example:
<!DOCTYPE html><html>  <head>    <title>CSS ~ Selector</title>          <meta charset="utf-8">    <meta name="viewport"        content="width=device-width, initial-scale=1">    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">    <style>        h1{            color:green;            text-align: center;        }        hr ~ p {            text-align: justify;            background-color: powderblue;            font-size: 130%;        }    </style></head>  <body>    <div class="container">          <h1>GeeksforGeeks</h1>                    <p>            Sudo Placement is back to help you this placement            season. Prepare for the Recruitment drive of             product-based companies like Microsoft, Amazon,            Adobe, etc with our free online placement preparation            course. The course focuses on various MCQ's & Coding            question likely to be asked in the interviews & make            your upcoming placement season efficient and successful.        </p>                  <hr/>                  <p>            Sudo Placement is back to help you this placement            season. Prepare for the Recruitment drive of             product-based companies like Microsoft, Amazon,            Adobe, etc with our free online placement preparation            course. The course focuses on various MCQ's & Coding            question likely to be asked in the interviews & make            your upcoming placement season efficient and successful.        </p>    </div></body>  </html>
Output:
shubhamr238
CSS-Selectors
Picked
CSS
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue of Pairs in C++ STL with Examples

28 Jul, 2021
Queue in STL are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement where elements are inserted at the back (end) and are deleted from the front. Queue of pair can be very efficient in designing complex data structures. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).Syntax:  
Queue<pair<datatype, datatype>> queue_of_pair;  
Below are the images to show the working of Queue of Pairs:  
 
Below is an example to show the Queue of Pairs: 
CPP
// C++ program to demonstrate// the working of STL queue of pairs #include <bits/stdc++.h>using namespace std; // Print the current pairvoid printPair(pair<int, int> p){    // Gives first element from queue pair    int f = p.first;     // Gives second element from queue pair    int s = p.second;     cout << "(" << f << ", " << s << ") ";} // Print the Queue of Pairsvoid showQueue(queue<pair<int, int> > gq){    // Print element until the    // queue is not empty    while (!gq.empty()) {        printPair(gq.front());        gq.pop();    }     cout << '\n';} // Driver codeint main(){    queue<pair<int, int> > gq;     // Pushing elements inside    // the queue container    gq.push({ 10, 20 });    gq.push({ 15, 5 });    gq.push({ 1, 5 });    gq.push({ 5, 10 });    gq.push({ 7, 9 });     cout << "Queue of Pairs: ";    showQueue(gq);     // Prints size of queue    cout        << "\nSize of Queue of Pairs: "        << gq.size();     // Prints first element    // of queue container    cout << "\nFront of Queue of Pairs: ";    printPair(gq.front());     // Prints last element    // of queue container    cout << "\nBack of Queue of Pairs: ";    printPair(gq.back());     cout << "\n\nRemoving the Front pair\n";    gq.pop();    cout << "Current Queue of Pairs: ";    showQueue(gq);     return 0;}
Queue of Pairs: (10, 20) (15, 5) (1, 5) (5, 10) (7, 9) 

Size of Queue of Pairs: 5
Front of Queue of Pairs: (10, 20) 
Back of Queue of Pairs: (7, 9) 

Removing the Front pair
Current Queue of Pairs: (15, 5) (1, 5) (5, 10) (7, 9)
 
akshaysingh98088
cpp-pair
STL
C++ Programs
Data Structures
Queue
Data Structures
Queue
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert data in the map of strings?
Passing a function as a parameter in C++
string::npos in C++ with Examples
Reason of runtime error in C/C++
Program to delete Nth digit of a Number
SDE SHEET - A Complete Guide for SDE Preparation
Doubly Linked List | Set 1 (Introduction and Insertion)
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
What is Priority Queue | Introduction to Priority Queue
Python | Numpy numpy.resize()

05 Mar, 2019
With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.
Parameters:new_shape : [tuple of ints, or n ints] Shape of resized arrayrefcheck : [bool, optional] This parameter is used to check the reference counter. By Default it is True.
Returns: None
Most of you are now thinking that what is the difference between reshape and resize. When we talk about reshape then an array changes it’s shape as temporary but when we talk about resize then the changes made permanently.
Example #1:In this example we can see that with the help of .resize() method, we have changed the shape of an array from 1×6 to 2×3.
# importing the python module numpyimport numpy as np  # Making a random arraygfg = np.array([1, 2, 3, 4, 5, 6])  # Reshape the array permanentlygfg.resize(2, 3)  print(gfg)
[[1 2 3]
 [4 5 6]]

Example #2:In this example we can see that, we are trying to resize the array of that shape which is type of out of bound values. But numpy handles this situation to append the zeros when values are not existed in the array.
# importing the python module numpyimport numpy as np  # Making a random arraygfg = np.array([1, 2, 3, 4, 5, 6])  # Required values 12, existing values 6gfg.resize(3, 4)  print(gfg)
[[1 2 3 4]
 [5 6 0 0]
 [0 0 0 0]]

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Programs for printing different patterns in Bash

10 Jun, 2022
Given the number N which represents the number of rows and columns, print the different following patterns in Bash.  
Pattern-1: 
Input: 6
Output:
     #
    ##
   ###
  ####
 #####
######
Use nested loop to print the given pattern. The first loop represents the row and the second loop represents the column. 
BASH
# Program to print the# given pattern # Static input for NN=5 # variable used for# while loopi=0j=0 while [ $i -le `expr $N - 1` ]do    j=0         while [ $j -le `expr $N - 1` ]    do        if [ `expr $N - 1` -le `expr $i + $j` ]        then          # Print the pattern          echo -ne "#"        else          # Print the spaces required          echo -ne " "        fi        j=`expr $j + 1`    done    # For next line    echo                  i=`expr $i + 1`done
Output: 
    #
   ##
  ###
 ####
#####
Pattern-2: 
Input: 3
Output:
    #
   ###
  #####
Use nested loops to print the left part and right part of the pattern. The details are explained in the code: 
BASH
# Program in Bash to# print pyramid # Static input to the# numberp=7; for((m=1; m<=p; m++))do    # This loop print spaces    # required    for((a=m; a<=p; a++))    do      echo -ne " ";    done         # This loop print the left    # side of the pyramid    for((n=1; n<=m; n++))    do      echo -ne "#";    done     # This loop print right    # side of the pyramid.    for((i=1; i<m; i++))    do      echo -ne "#";    done     # New line    echo;done
Output: 
        #
       ###
      #####
     #######
    #########
   ###########
  #############
 
Akanksha_Rai
coderu
simmytarika5
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.dt.dayofweek

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.dayofweek attribute return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6.
Syntax: Series.dt.dayofweek
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',               '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# return the day of weekresult = sr.dt.dayofweek  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.dayofweek attribute has successfully accessed and returned the day of week in the underlying data of the given series object. Example #2 : Use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# return the day of weekresult = sr.dt.dayofweek  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.dayofweek attribute has successfully accessed and returned the day of week in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
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
Using Pylint to write clean Python code | by Vishal Sharma | Towards Data Science

A code linter is basically a program that inspects your code and gives feedback. A linter can tell you the issues in your program and also, a way to resolve them. You can run it anytime to ensure that your code is matching standard quality.
Linters look at aspects of code and detect lints:
Logical Lint: tells about code errors, dangerous code patternsStatistical Lint: looks at formatting issues
Logical Lint: tells about code errors, dangerous code patterns
Statistical Lint: looks at formatting issues
There are many Python linters like Flake8, Pylint, Pylama, and many others. In this article, I will be talking about Pylint because it handles both logical and statistical lint.
Install Pylint
If you want to install Pylint from the terminal, this is a one-line command to do that.
pip install pylint
I have installed Pylint in my code editor, PyCharm. For that, you can go to Preferences > Plugins and search for the “Pylint” plugin. Install and Download it from the window and restart the IDE.
Then you can set up the Exec path for the plugin so that Pycharm can execute Pylint every time user needs to inspect the code. For that, go to Settings/Preferences, click Other Settings, and then Pylint. Enter the PATH environment variable there and you are good to go.
Now, you are done! Every time you run a code now, you can use Pylint to look for refactoring, convention, and other little warning signs.
For my code, you can see I have got many display convention issues. At the lower left, you might see 4 symbols (red, yellow, blue, red ), these symbols tell the user about “Errors”, “Warnings”, “Display Conventions”, and “Refactoring” issues in the code.
I have got many blue ones which means I am having many display convention issues in my code. You can improve the code and then again turn on the linter to look at your code quality.
For people on Terminal
You can simply use the following command to inspect the code.
pylint example.py
Pylint is an amazing linter that you must have in your coding arsenal. Because code quality matters!
For feedbacks and discussions, find me at my Linkedin!
How to create a tree view with CSS and JavaScript?

To create a tree view with CSS and JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   ul, #treeUL {
      list-style-type: none;
   }
   #treeUL {
      margin: 0;
      padding: 0;
   }
   .rootTree {
      cursor: pointer;
      user-select: none;
      font-size: 18px;
      font-weight: bold;
      color: blue;
   }
   li {
      font-size: 16px;
      color: crimson;
      font-weight: 500;
   }
   .rootTree::before {
      content: "\25B6";
      color: black;
      display: inline-block;
      margin-right: 6px;
   }
   .rootTree-down::before {
      transform: rotate(90deg);
   }
   .children {
      display: none;
   }
   .active {
      display: block;
   }
</style>
</head>
<body>
<h1>Tree view example</h1>
<ul id="treeUL">
<li>
<span class="rootTree">Root</span>
<ul class="children">
<li>/bin</li>
<li>/etc</li>
<li>
<span class="rootTree">/home</span>
<ul class="children">
<li>/home/Downloads</li>
<li>/home/Pictures/</li>
<li>
<span class="rootTree">/home/Desktop</span>
<ul class="children">
<li>/home/Desktop/file.txt</li>
<li>/home/Desktop/file1.mp3</li>
<li>/home/Desktop/file1.mp4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
   debugger;
   console.log('wow');
   var toggler = document.querySelectorAll(".rootTree");
   Array.from(toggler).forEach(item => {
      item.addEventListener("click", () => {
         item.parentElement .querySelector(".children") .classList.toggle("active");
         item.classList.toggle("rootTree-down");
      });
   });
</script>
</body>
</html>
The above code will produce the following output −
On expanding the tree by clicking on the caret −
Bayes Theorem for Conditional Probability in C/C++

Conditional probability denoted by P(A|B) is the probability of occurrence of an event ‘A’ given that event ‘B’ has already occurred.
Formula for conditional probability −
P(A|B) = P( A⋂B ) / P(B)
It is the formula that shows the relation between probabilities of occurrences of mutually dependent events i.e. it given the relation between their conditional probabilities.
Given an event A and another event B, according to bayes’ theorem,
P(A/B) = {P(B/A) * P(A)} / P(B)
Lets derive the formula for Bayes’ theorem,
For this we will use the formula for conditional probability,
P(A|B) = P( A?B ) / P(B) —— 1
P(B|A) = P( B?A ) / P(A) —— 2
We know that A⋂B and B⋂A are the same, hence we can substitute the value of B⋂A with A⋂B equation 2.
P(B/A) = P(A⋂B) / P(A)
P(B/A) * P(A) = P(A⋂B) —- 3
Now, using this value for A?B in equation 1, we will get the bayes’ theorem formula.
P(A/B) = {P(B/A) * P(A)} / P(B)
Some derivations for the Bayes’ Theorem,
depicted in equation 3, it says that the probability of both the events to occur in the same trials is equal to the product of conditional probability of the event and the probability of occurrence of evidence event.
P(A?B) = P(A/B) * P(B)
From this rule we can derive two important formulas −
If A⊆B i.e. A is the subset of B which means all the elements of set A are in set B, then
P(A⋂B) = P(A), then P(A/B) = P(A) / P(B)
If B⊆A i.e. B is the subset of A which means all the elements of set B are in set A, then
P(A⋂B) = P(B), then P(A/B) = 1
Bayes’ Theorem form more than three events −
If we have more that three mutually dependent events, their conditional probability will have the following relation,
P(X1/Y) = (P(X1)*P(Y/X1) / [P(X1 * P(Y/X1)) + P(X2 * P(Y/X2)) + P(X3 * P(Y/X3)) + ...]
C# program to generate secure random numbers

For secure random numbers, use the RNGCryptoServiceProvider Class. It implements a cryptographic Random Number Generator.
Using the same class, we have found some random values using the following −
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {
   byte[] val = new byte[6];
   crypto.GetBytes(val);
   randomvalue = BitConverter.ToInt32(val, 1);
}
To generate random secure numbers, you can try to run the following code.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
public class Demo {
   public static void Main(string[] args) {
      for (int i = 0; i <= 5; i++) {
         Console.WriteLine(randomFunc());
      }
   }
   private static double randomFunc() {
      string n = "";
      int randomvalue;
      double n2;
      using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {
         byte[] val = new byte[6];
         crypto.GetBytes(val);
         randomvalue = BitConverter.ToInt32(val, 1);
      }
      n += randomvalue.ToString().Substring(1, 1)[0];
      n += randomvalue.ToString().Substring(2, 1)[0];
      n += randomvalue.ToString().Substring(3, 1)[0];
      n += randomvalue.ToString().Substring(4, 1)[0];
      n += randomvalue.ToString().Substring(5, 1)[0];
      double.TryParse(n, out n2);
      n2 = n2 / 100000;
      return n2;
   }
}
0.13559
0.0465
0.18058
0.26494
0.52231
0.78927
times() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint

clock_t times(struct tms *buf); 


struct tms {
clock_t tms_utime;  /* user time */
clock_t tms_stime;  /* system time */
clock_t tms_cutime; /* user time of children */
clock_t tms_cstime; /* system time of children */
};


The
tms_utime field contains the CPU time spent executing instructions
of the calling process.
The
tms_stime field contains the CPU time spent in the system while
executing tasks on behalf of the calling process.
The
tms_cutime field contains the sum of the
tms_utime and
tms_cutime values for all waited-for terminated children.
The
tms_cstime field contains the sum of the
tms_stime and
tms_cstime values for all waited-for terminated children.


Times for terminated children (and their descendants)
is added in at the moment
wait(2)
or
waitpid(2)
returns their process ID. In particular, times of grandchildren
that the children did not wait for are never seen.


All times reported are in clock ticks.


In Linux kernel versions before 2.6.9,
if the disposition of
SIGCHLD is set to
SIG_IGN then the times of terminated children
are automatically included in the
tms_cstime and
tms_cutime fields, although POSIX.1-2001 says that this should only happen
if the calling process
wait()s on its children.
This non-conformance is rectified in Linux 2.6.9 and later.


On Linux, the
buf argument can be specified as NULL, with the result that
times() just returns a function result.
However, POSIX does not specify this behaviour, and most
other Unix implementations require a non-NULL value for
buf. 

Note that
clock(3)
returns values of type
clock_t that are not measured in clock ticks
but in
CLOCKS_PER_SEC. 

On older systems the number of clock ticks per second is given
by the variable HZ.

time (1)
time (1)
getrusage (2)
getrusage (2)
wait (2)
wait (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
p5.js | isPlaying() Function

18 Nov, 2021
The isPlaying() function is an inbuilt function of p5.sound library that verifies that the play() function performed successfully, if that play was successful then this function will return true else false. That means it returns a Boolean value.Syntax: 
isPlaying()
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameters: This function does not accept any parameter.Return Values: This function return the Boolean value of play true or false, true means audio is playing and false means not.Below examples illustrates the p5.isPlaying() function in JavaScript: Example 1: Before the play() function will calling isPlaying() function. 
javascript
var sound;var ply;function preload() {      // Initialize sound    sound = loadSound("pfivesound.mp3");}  function setup() {              //Checking playing or not    var ply = sound.isPlaying();    console.log(ply);         // Playing the preloaded sound    sound.play();}
Output: 
false
Example 2: After the play() function will calling isPlaying() function.  
javascript
var sound;var ply;function preload() {      // Initialize sound    sound = loadSound("pfivesound.mp3");}  function setup() {         // Playing the preloaded sound    sound.play();     //Checking playing or not    var ply = sound.isPlaying();    console.log(ply);}
Output: 
true
Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Supported Browsers: The browsers supported by p5.isPlaying() function are listed below:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera 
kashishsoda
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the owner of a directory using Python?

You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner:
import pwd
import grp
import os
uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = 'my_folder'
os.chown(path, uid, gid)
How to display the count over the bar in Matplotlib histogram?

To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches.
Set the figure size and adjust the padding between and around the subplots.
Make a list of numbers to make a histogram plot.
Use hist() method to make histograms.
Iterate the patches and calculate the mid-values of each patch and height of the patch to place a text.
To display the figure, use show() method.
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [3, 5, 1, 7, 9, 5, 3, 7, 5]
_, _, patches = plt.hist(data, align="mid")

for pp in patches:
   x = (pp._x0 + pp._x1)/2
   y = pp._y1 + 0.05
   plt.text(x, y, pp._y1)

plt.show()
Laravel - Ajax

Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications. Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function.
json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)

Step 1 − Create a view file called resources/views/message.php and copy the following code in that file.
<html>
   <head>
      <title>Ajax Example</title>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
      
      <script>
         function getMessage() {
            $.ajax({
               type:'POST',
               url:'/getmsg',
               data:'_token = <?php echo csrf_token() ?>',
               success:function(data) {
                  $("#msg").html(data.msg);
               }
            });
         }
      </script>
   </head>
   
   <body>
      <div id = 'msg'>This message will be replaced using Ajax. 
         Click the button to replace the message.</div>
      <?php
         echo Form::button('Replace Message',['onClick'=>'getMessage()']);
      ?>
   </body>

</html>
Step 2 − Create a controller called AjaxController by executing the following command.
php artisan make:controller AjaxController --plain

Step 3 − After successful execution, you will receive the following output −
Step 4 − Copy the following code in
app/Http/Controllers/AjaxController.php file.
app/Http/Controllers/AjaxController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AjaxController extends Controller {
   public function index() {
      $msg = "This is a simple message.";
      return response()->json(array('msg'=> $msg), 200);
   }
}
Step 5 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('ajax',function() {
   return view('message');
});
Route::post('/getmsg','AjaxController@index');

Step 6 − Visit the following URL to test the Ajax functionality.
http://localhost:8000/ajax

Step 7 − You will be redirected to a page where you will see a message as shown in the following image.
Step 8 − The output will appear as shown in the following image after clicking the button.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
Get count of array elements from a specific field in MongoDB documents?

To count array elements from a specific field, use $size in MongoDB. Let us create a collection with documents −
> db.demo723.insertOne({"Subject":["MySQL","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab094d43417811278f588a")
}
> db.demo723.insertOne({"Subject":["C"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab095243417811278f588b")
}
> db.demo723.insertOne({"Subject":["C++","Java","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab095f43417811278f588c")
}
Display all documents from a collection with the help of find() method −
> db.demo723.find();
This will produce the following output −
{ "_id" : ObjectId("5eab094d43417811278f588a"), "Subject" : [ "MySQL", "MongoDB" ] }
{ "_id" : ObjectId("5eab095243417811278f588b"), "Subject" : [ "C" ] }
{ "_id" : ObjectId("5eab095f43417811278f588c"), "Subject" : [ "C++", "Java", "Python" ] }
Following is the query to count array elements in MongoDB −
> db.demo723.aggregate([
...    { $project: { count: { $size: '$Subject' } } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5eab094d43417811278f588a"), "count" : 2 }
{ "_id" : ObjectId("5eab095243417811278f588b"), "count" : 1 }
{ "_id" : ObjectId("5eab095f43417811278f588c"), "count" : 3 }
How To Delete A Column In Pandas | Towards Data Science

Deleting columns from pandas DataFrames is a fairly common task. In today’s short guide we are going to explore how you can delete specific column(s) by name. More specifically, we are going to discuss how to delete columns using:
del command
drop() method
pop() method
Additionally, we will discuss how to delete columns by specified their index rather than their name.
First, let’s create an example pandas DataFrame that we’ll use throughout this guide in order to demonstrate a few concepts.
import pandas as pddf = pd.DataFrame({    'colA':[1, 2, 3],     'colB': ['a', 'b', 'c'],    'colC': [True, False, False],})print(df)#    colA colB   colC# 0     1    a   True# 1     2    b  False# 2     3    c  False
If you want to delete a specific column the first option you have is to call del as shown below:
del df['colC']print(df)#    colA colB# 0     1    a# 1     2    b# 2     3    c
This approach will only work only if you wish to delete a single column. If you need to delete multiple column in one go, read the following section.
Additionally, it’s important to note that del df.colC won’t work! The syntax must be identical to the one shown in the example above.
pandas.DataFrame.drop method is used to delete the specified labels from either rows or columns.
In order to delete columns, you need to specify axis=1 as shown below:
df = df.drop(['colA', 'colC'], axis=1)print(df)#   colB# 0    a# 1    b# 2    c
Note that if you want to delete the columns without having to re-assign the result back to df, all you need to do is specify inplace to True :
df.drop(['colA', 'colC'], axis=1, inplace=True)
Another option is pandas.DataFrame.pop that returns the deleted column and finally deletes it from the original DataFrame.
df.pop('colB')
will return column colB that we want to get deleted from the DataFrame:
0    a1    b2    c
and we can verify that the column has indeed been deleted from the original frame:
print(df)   colA   colC0     1   True1     2  False2     3  False
In the sections above, we explored how to delete specific columns by their name. However, you may also need to delete a particular column by referencing its index instead.
To do so, you can use pandas.DataFrame.drop method. Assuming that we want to drop columns colA and colC with indices 0 and 2 respectively, we can do so as shown below:
df.drop(df.columns[[0, 2]], axis=1, inplace=True)
In today’s short guide we explored how to delete specific column(s) in a pandas DataFrame in various ways either by name or by index.
You may also be interested in reading about how to rename columns of pandas DataFrames. If so make sure not to miss the article below.
towardsdatascience.com
Moreover, the article below discusses how to perform proper row selection based on specific conditions.
How to add table row in jQuery?

To add table row in jQuery, use the append() method to add table tags.
You can try to run the following code to learn how to add table row in jQuery:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>jQuery Add Table Rows</title>
      <style>
         table{
           width: 100%;
           margin: 25px 0;
           border-collapse: collapse;
         }
         table, th, td{
           border: 1px solid #6C220B;
         }
         table th, table td{
           padding: 8px;
           text-align: left;
         }
      </style>
      <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
      <script>
         $(document).ready(function(){
             $(".row").click(function(){
                 var name = $("#name").val();
                 var subject = $("#subject").val();
                 var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + subject + "</td></tr>";
                 $("table tbody").append(markup);
             });        
         });    
      </script>
   </head>
   <body>
      <form>
         <input type="text" id="name" placeholder="Enter Name">
         <input type="text" id="subject" placeholder="Enter Subject">
         <input type="button" class="row" value="Click to Add Row">
      </form>
      <table>
         <thead>
            <tr>
               <th>Choose</th>
               <th>Name</th>
               <th>Subject</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td><input type="checkbox" name="result"></td>
               <td>Amit</td>
               <td>Java</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
How to change the Azure tag value using PowerShell?

To change the azure value using PowerShell we need to use the Update-AZTag command with the merge property.
For example, we have the Azure VM TestMachine2k16 and we have its tags as shown below.
PS C:\> $vm = Get-AzVM -VMName TestMachine2k16
PS C:\> $vm | Select -ExpandProperty Tags
Key          Value
---          -----
Owner        Chirag
For Ansible
Patching_Day Sunday
Application SecretTag
We need to change the Patching_Day from Sunday to Wednesday. We will use the below command.
$tag = @{Patching_Day='Wednesday'}
Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Merge -Verbose
Name           Value
============   =========
Patching_Day   Wednesday
For            Ansible
Application    SecretTag
Owner          Chirag
There is also property Replace available in Update-AZTag but please be cautious while using the Replace parameter because once you apply it, the current tag will be changed but other tags will be erased.
Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Replace -Verbose
Properties :
Name          Value
============  =========
Patching_Day  Wednesday
C++ Program for Gnome Sort?

Here we will see how the gnome sort works. This is another sorting algorithm. In this approach if the list is already sorted it will take O(n) time. So best case time complexity is O(n). But average case and worst case complexity is O(n^2). Now let us see the algorithm to get the idea about this sorting technique.
begin
   index := 0
   while index < n, do
      if index is 0, then
         index := index + 1
      end if
      if arr[index] >= arr[index -1], then
         index := index + 1
      else
         exchange arr[index] and arr[index - 1]
         index := index - 1
      end if
   done
end
 Live Demo
#include<iostream>
using namespace std;
void gnomeSort(int arr[], int n){
   int index = 0;
   while(index < n){
      if(index == 0) index++;
      if(arr[index] >= arr[index - 1]){ //if the element is greater than previous one
         index++;
      } else {
         swap(arr[index], arr[index - 1]);
         index--;
      }
   }
}
main() {
   int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   gnomeSort(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}
Sorted Sequence 13 20 32 35 40 54 74 98 98 154
How can we convert a map to the JSON object in Java?

The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. An object is an unordered collection of key/value pairs and an array is an ordered sequence of values. 
We can convert a Map to JSON object using the toJSONString() method(static) of org.json.simple.JSONValue. It has two important static methods: writeJSONString() method to encode an object into JSON text and write it out, escape() method to escape the special characters and escape quotes, \, /, \r, \n, \b, \f, \t.
import java.util.*;
import org.json.simple.JSONValue;
public class ConvertMapJSONTest {
   public static void main(String[] args) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("1", "India");
      map.put("2", "Australia");
      map.put("3", "England");
      map.put("4", "South Africa");
      String jsonStr = JSONValue.toJSONString(map); // converts Map to JSON
      System.out.println(jsonStr);
   }
}
{"1":"India","2":"Australia","3":"England","4":"South Africa"}
Print Single and Multiple variable in Python?

In this section, we are going to check printing single and multiple variable output in two different python version.
>>> #Python 2.7
>>> #Print single variable
>>> print 27
27
>>> print "Rahul"
Rahul
>>> #Print single variable, single brackets
>>> print(27)
27
>>> print("Rahul")
Rahul
>>> #Python 3.6
>>> #Print single variable without brackets
>>> print 27
SyntaxError: Missing parentheses in call to 'print'
>>> print "Rahul"
SyntaxError: Missing parentheses in call to 'print'
Above syntax in 3.6, is due to: In python 3.x, print is not a statement but a function (print()). So print is changed to print().
>>> print (27)
27
>>> print("Rahul")
Rahul
Python 2.x (for e.g: python 2.7)
>>> #Python 2.7
>>> #Print multiple variables
>>> print 27, 54, 81
27 54 81
>>> #Print multiple variables inside brackets
>>> print (27, 54, 81)
(27, 54, 81)
>>> #With () brackets, above is treating it as a tuple, and hence generating the
>>> #tuple of 3 variables
>>> print ("Rahul", "Raj", "Rajesh")
('Rahul', 'Raj', 'Rajesh')
>>>
So from above output, we can see in python 2.x, passing multiple variables inside the brackets (), will treat it as tuple of multiple items
#Python 3.6
#Print multiple variables
>>> print(27, 54, 81)
27 54 81
>>> print ("Rahul", "Raj", "Rajesh")
Rahul Raj Rajesh
Let’s take another example of multiple statements in python 2.x and python 3.x