code-rag-bench/online-tutorials huggingface dataset:
PyQt5 QSpinBox - Setting single step size - GeeksforGeeks

06 May, 2020
In this article we will see how we can set the single step size of the spin box, by default when we create a spin box it step size is 1. Step size is basically the incremental or decrement size.
In order to do this we will use setSingleStep method.
Syntax : spin_box.setSingleStep(step)
Argument : It takes integer as argument
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys  class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 150, 40)          # setting single step size        self.spin.setSingleStep(5)              # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Difference between Super Key and Candidate Key - GeeksforGeeks

07 Jun, 2021
Prerequisite – Keys in Relational Model Super Key: Super Key is an attribute (or set of attributes) that is used to uniquely identifies all attributes in a relation. All super keys can’t be candidate keys but its reverse is true. In a relation, number of super keys are more than number of candidate keys. 
Example: We have a given relation R(A, B, C, D, E, F) and we shall check for being super keys by following given dependencies:  
Functional dependencies         Super key
AB->CDEF                         YES
CD->ABEF                         YES
CB->DF                           NO
D->BC                            NO 
By Using key AB we can identify rest of the attributes (CDEF) of the table. Similarly, Key CD. But, by using key CB we can only identifies D and F not A and E. Similarly key D. 
Candidate Key: Candidate key is a set of attributes (or attribute) which uniquely identify the tuples in a relation or table. As we know that Primary key is a minimal super key, so there is one and only one primary key in any relation but there is more than one candidate key can take place. Candidate key’s attributes can contain NULL value which oppose to the primary key.  
Example:  
Student{ID, First_name, Last_name, Age, Sex, Phone_no} 
Here we can see the two candidate keys ID and {First_name, Last_name, DOB, Phone_no}. So here, there are present more than one candidate keys, which can uniquely identifies a tuple in a relation. 
Difference between Super Key and Candidate Key:  
Kumarsuraj
jaffreyjoy
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Introduction of Relational Algebra in DBMS
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Pointer vs Array in C - GeeksforGeeks

21 Oct, 2021
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 
1) the sizeof operator o sizeof(array) returns the amount of memory used by all elements in array o sizeof(pointer) only returns the amount of memory used by the pointer variable itself 
2) the & operator o array is an alias for &array[0] and returns the address of the first element in array o &pointer returns the address of pointer 
3) a string literal initialization of a character array o char array[] = “abc” sets the first four elements in array to ‘a’, ‘b’, ‘c’, and ‘\0’ o char *pointer = “abc” sets pointer to the address of the “abc” string (which may be stored in read-only memory and thus unchangeable) 
4) Pointer variable can be assigned a value whereas array variable cannot be.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
int a[10];
int *p; 
p=a; /*legal*/
a=p; /*illegal*/ 
5) Arithmetic on pointer variable is allowed. 
p++; /*Legal*/
a++; /*illegal*/ 
Please refer Difference between pointer and array in C? for more details. 
References: http://icecube.wisc.edu/~dglo/c_class/array_ptr.html 
shengzhao91
C-Pointers
cpp-array
cpp-pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Substring in C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Converting Strings to Numbers in C/C++
Enumeration (or enum) in C
Command line arguments in C/C++
deque::begin() and deque::end in C++ STL - GeeksforGeeks

21 Nov, 2018
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed.
begin() function is used to return an iterator pointing to the first element of the deque container. begin() function returns a bidirectional iterator to the first element of the container.
Syntax :
dequename.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.

Examples:
Input  : mydeque{1, 2, 3, 4, 5};
         mydeque.begin();
Output : returns an iterator to the element 1

Input  : mydeque{8, 7};
         mydeque.begin();
Output : returns an iterator to the element 8

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// CPP program to illustrate// Implementation of begin() function#include <deque>#include <iostream>using namespace std;  int main(){    // declaration of deque container    deque<int> mydeque{ 1, 2, 3, 4, 5 };      // using begin() to print deque    for (auto it = mydeque.begin(); it != mydeque.end(); ++it)        cout << ' ' << *it;    return 0;}
Output:
1 2 3 4 5

Time Complexity : O(1)
end() function is used to return an iterator pointing to the last element of the deque container. end() function returns a bidirectional iterator to the last element of the container.Note : The last element of any container is considered as the theoretical element next to the last value stored in the container.
Syntax :
dequename.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the last element.

Examples:
Input  : mydeque{1, 2, 3, 4, 5};
         mydeque.end();
Output : returns an iterator to the element next to the element 5

Input  : mydeque{8, 7};
         mydeque.end();
Output : returns an iterator to the element next to the element 7

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// CPP program to illustrate// Implementation of end() function#include <deque>#include <iostream>using namespace std;  int main(){    // declaration of deque container    deque<int> mydeque{ 1, 2, 3, 4, 5 };      // using end() to print deque    for (auto it = mydeque.begin(); it != mydeque.end(); ++it)        cout << ' ' << *it;    return 0;}
Output:
1 2 3 4 5

Time Complexity : O(1)
Harshit Singhal 2
cpp-deque
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Constructors in C++
Socket Programming in C/C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Precedence Graph in Operating System - GeeksforGeeks

05 Jun, 2020
Prerequisite – Process SynchronizationPrecedence Graph is a directed acyclic graph which is used to show the execution level of several processes in operating system. It consists of nodes and edges. Nodes represent the processes and the edges represent the flow of execution.
Properties of Precedence Graph :Following are the properties of Precedence Graph:
It is a directed graph.
It is an acyclic graph.
Nodes of graph correspond to individual statements of program code.
Edge between two nodes represents the execution order.
A directed edge from node A to node B shows that statement A executes first and then Statement B executes.
Consider he following code:
S1 : a = x + y;
S2 : b = z + 1;
S3 : c = a - b;
S4 : w = c + 1;

If above code is executed concurrently, the following precedence relations exist:
c = a – b cannot be executed before both a and b have been assigned values.
w = c + 1 cannot be executed before the new values of c has been computed.
The statements a = x + y and b = z + 1 could be executed concurrently.
Example:Consider the following precedence relations of a program:
S2 and S3 can be executed after S1 completes.S4 can be executed after S2 completes.S5 and S6 can be executed after S4 completes.S7 can be executed after S5, S6 and S3 complete.
S2 and S3 can be executed after S1 completes.
S4 can be executed after S2 completes.
S5 and S6 can be executed after S4 completes.
S7 can be executed after S5, S6 and S3 complete.
Solution:
Process Synchronization
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1
Paging in Operating System
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Class with a constructor to initialize instance variables in Java

A class contains a constructor to initialize instance variables in Java. This constructor is called when the class object is created.
A program that demonstrates this is given as follows −
 Live Demo
class Student {
   private int rno;
   private String name;
   public Student(int r, String n) {
      rno = r;
      name = n;
   }
   public void display() {
      System.out.println("Roll Number: " + rno);
      System.out.println("Name: " + name);
   }
}
public class Demo {
   public static void main(String[] args) {
      Student s = new Student(173, "Susan");
      s.display();
   }
}
The output of the above program is as follows −
Roll Number: 173
Name: Susan
Now let us understand the above program.
The Student class is created with data members rno, name. The constructor Student() initializes rno and name. The member function display() displays the values of rno and name. A code snippet which demonstrates this is as follows:
class Student {
   private int rno;
   private String name;
   public Student(int r, String n) {
      rno = r;
      name = n;
   }
   public void display() {
      System.out.println("Roll Number: " + rno);
      System.out.println("Name: " + name);
   }
}
In the main() method, an object s of class Student is created with values 101 and “John”. Then the display() method is called. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String[] args) {
      Student s = new Student(173, "Susan");
      s.display();
   }
}
Fixing data files — adding a missing date column | by Dawn Moyer | Towards Data Science

You have an entire folder of files ready for analysis. Looking closer, you see that each file name has a date, but there is no corresponding date on the records. To load the data into a data frame or table, you will need some date or timestamp to maintain the records' order. Inwardly, you groan. What to do?
You can use python to read in the file and add a new column based on the filename date.
You need to create a visualization of the candy sales for the first week of October 2020.
The files are created daily and contain different candies and the amount sold.
The files are found within a single folder. The file names vary by sale date.
4 Steps to add the date columns to all the files if missing
Using the same python glob as I did for a text scraping task earlier, I create a list of all of the files in the folder.Iterate through that list of files. Get the date from the filename.Next, open the file and read it into a data frame. Add (or update if it already exists) a date column.Write the updated data back to the file.
Using the same python glob as I did for a text scraping task earlier, I create a list of all of the files in the folder.
Iterate through that list of files. Get the date from the filename.
Next, open the file and read it into a data frame. Add (or update if it already exists) a date column.
Write the updated data back to the file.
After running this simple script, the files are now updated:
Now it is much easier to pull those files into a single file. I have included that in the script as well.
# import required packagesimport pandas as pdimport globimport osimport reimport sys# where is your folder?folderPath  = '<path to your top folder>'# Find the candy sales filesfiles = glob.glob(folderPath + '/**/*candy_sales*',recursive=True)viz_df = pd.DataFrame()"""Loop through all the files , remove punctuationn, split each line into elements and match the elements to the list of words"""for file in files:    basic_file_name = file.replace(folderPath,'')        basic_file_date = basic_file_name[14:22]        # yyyy-mm-dd    #file_date = str(basic_file_name[14:18]) + '-' + str(basic_file_name[18:20])  + '-' + str(basic_file_name[20:22])       # mm/dd/yyyy    file_date = str(basic_file_name[18:20])  + '-' + str(basic_file_name[20:22]) + '-' + str(basic_file_name[14:18])df = pd.DataFrame()    df = pd.read_excel(file, header=0)       df['date'] = file_datedf.to_excel(file, header=True, index=False)            print('Done updating files')# Create a viz filefor file in files:    df = pd.DataFrame()    df = pd.read_excel(file, header=0)    viz_df = viz_df.append(df)        viz_df.to_excel(folderPath + '/viz_file.xlsx', header=True, index=False)print('Done printing viz file')
Once you have the final file, pull it into a Viz tool — such as Tableau Public.
In just minutes, you’ve gone from an unusable pile of undated records to a file of timestamped rows ready for analysis.
Select query with regular expression in MySQL

Let us first create a table −
mysql> create table DemoTable1573
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentCode varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1573(StudentCode) values('STU_774');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1573(StudentCode) values('909_Sam');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1573(StudentCode) values('3_Carol_455');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1573(StudentCode) values('David_903');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1573;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentCode |
+-----------+-------------+
|         1 | STU_774     |
|         2 | 909_Sam     |
|         3 | 3_Carol_455 |
|         4 | David_903   |
+-----------+-------------+
4 rows in set (0.00 sec)
Here is the query to implement select query with regular expression −
mysql> select * from DemoTable1573 where StudentCode regexp '\land[0-9]';
This will produce the following output −
+-----------+-------------+
| StudentId | StudentCode |
+-----------+-------------+
|         2 | 909_Sam     |
|         3 | 3_Carol_455 |
+-----------+-------------+
2 rows in set (0.14 sec)
JavaScript | Program to generate one-time password (OTP)

08 Dec, 2020
One-time Passwords (OTP) is a password that is valid for only one login session or transaction on a computer or a digital device. Nowadays OTP’s are used in almost every service like Internet Banking, online transactions, etc. They are generally a combination of 4 or 6 numeric digits or a 6-digit alphanumeric. The random function is used to generate random OTP which is predefined in the Math library. This article describes how to generate OTP using JavaScript.
Used Function:
Math.random(): This function returns any random number between 0 to 1.
Math.floor(): It returns floor of any floating number to a integer value.
Using the above function pick a random index of string array which contains all the possible candidates of a particular digit of the OTP.
Example 1: This example generates 4 digit Numeric OTP:
<script>  // Function to generate OTPfunction generateOTP() {              // Declare a digits variable     // which stores all digits    var digits = '0123456789';    let OTP = '';    for (let i = 0; i < 4; i++ ) {        OTP += digits[Math.floor(Math.random() * 10)];    }    return OTP;}  document.write("OTP of 4 digits: ")document.write( generateOTP() );</script>                    
Output:
OTP of 4 digits: 2229
Example 2: This example generates 6 digit Numeric OTP:
<script>  // Function to generate OTPfunction generateOTP() {              // Declare a digits variable     // which stores all digits    var digits = '0123456789';    let OTP = '';    for (let i = 0; i < 6; i++ ) {        OTP += digits[Math.floor(Math.random() * 10)];    }    return OTP;}  document.write("OTP of 6 digits: ")document.write( generateOTP() );</script>                    
Output:
OTP of 6 digits: 216664
Example 3: This example generates alphanumeric OTP of length 6:
<script>  // Function to generate OTPfunction generateOTP() {              // Declare a string variable     // which stores all string    var string = '0123456789abcdefghijklmnopqrs    tuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';    let OTP = '';          // Find the length of string    var len = string.length;    for (let i = 0; i < 6; i++ ) {        OTP += string[Math.floor(Math.random() * len)];    }    return OTP;}  document.write("OTP of 6 length: ")document.write( generateOTP() );</script>                    
Output:
OTP of 6 length: rab0Tj
soham_de_roy
Technical Scripter 2018
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Get a list as input from user

08 Jul, 2022
We often encounter a situation when we need to take number/string as input from the user. In this article, we will see how to get as input a list from the user. 
Examples:  
Input : n = 4,  ele = 1 2 3 4
Output :  [1, 2, 3, 4]

Input : n = 6, ele = 3 4 1 7 9 6
Output : [3, 4, 1, 7, 9, 6]
Code #1: Basic example  
Python3
# creating an empty listlst = []  # number of elements as inputn = int(input("Enter number of elements : "))  # iterating till the rangefor i in range(0, n):    ele = int(input())      lst.append(ele) # adding the element      print(lst)
Output:  
  Code #2: With handling exception  
Python3
# try block to handle the exceptiontry:    my_list = []          while True:        my_list.append(int(input()))          # if the input is not-integer, just print the listexcept:    print(my_list)
Output:  
  Code #3: Using map()  
Python3
# number of elementsn = int(input("Enter number of elements : "))  # Below line read inputs from user using map() function a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n]  print("\nList is - ", a)
Output:  
  Code #4: List of lists as input  
Python3
lst = [ ]n = int(input("Enter number of elements : "))  for i in range(0, n):    ele = [input(), int(input())]    lst.append(ele)      print(lst)
Output:  
Code #5: Using List Comprehension and Typecasting  
Python3
# For list of integerslst1 = []    # For list of strings/charslst2 = []    lst1 = [int(item) for item in input("Enter the list items : ").split()]  lst2 = [item for item in input("Enter the list items : ").split()]  print(lst1)print(lst2)
Output:  
 
rahulsrivastava7
sooda367
Python list-programs
python-list
Python
python-list
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
Getting the absolute value of a number in Julia – abs() Method

21 Apr, 2020
The abs() is an inbuilt function in julia which is used to return the absolute value of the specified number x.
Syntax: abs(x)
Parameters:
x: Specified value.
Returns: It returns the absolute value of the specified number x.
Example 1:
# Julia program to illustrate # the use of abs() method  # Getting absolute value of the # specified number xprintln(abs(0))println(abs(-2.7))println(abs(2))
Output:
0
2.7
2

Example 2:
# Julia program to illustrate # the use of abs() method  # Getting absolute value of the # specified number xprintln(abs(0))println(abs(-2.7))println(abs(-2.9))println(abs(0.7))println(abs(-0.2))println(abs(-22))
Output:
0
2.7
2.9
0.7
0.2
22

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Exception handling in Julia
Formatting of Strings in Julia
Creating array with repeated elements in Julia - repeat() Method
Tuples in Julia
while loop in Julia
Python EasyGUI - Button Box - GeeksforGeeks

05 Sep, 2020
EasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from other GUI generators in that EasyGUI is NOT event-driven. Instead, all GUI interactions are invoked by simple function calls. Unlike other complicated GUI’s EasyGUI is the simplest GUI till now.
Button Box : It is used to display a window having multiple buttons in EasyGUI, it can be used where there is condition to select one among lot of buttons for example buttons in lift at a time user can opt only one option, below is how the normal button box looks like
In order to do this we will use buttonbox method
Syntax : buttonbox(text, title, button_list)
Argument : It takes 3 arguments, first string i.e text to be displayed, second string i.e title of the window and third list of button(strings)
Return : It returns the text of the button that the user selected
Example :In this we will create a button box windows having a three buttons which user can select and selected button text will get printed, below is the implementation
# importing easygui modulefrom easygui import *  # message to be displayed text = "Message to be displayed on the window GfG"  # window titletitle = "Window Title GfG"  # button listbutton_list = []  # button 1button1 = "First"  # second buttonbutton2 = "Second"  # third buttonbutton3 = "Third"  # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3)    # creating a button boxoutput = buttonbox(text, title, button_list)  # printing the button pressed by the userprint("User selected option : ", end = " ")print(output)
Output :
User selected option :  Second

Another example :
# importing easygui modulefrom easygui import *  # message to be displayed text = "Message to be displayed on the window GfG"  # window titletitle = "Window Title GfG"  # creating a button boxoutput = buttonbox(text, title)  # printing the button pressed by the userprint("User selected option : ", end = " ")print(output)
Output :
User selected option :  Button[3]

Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
How to shuffle an array using JavaScript ? - GeeksforGeeks

16 Jul, 2021
Shuffling an array or a list means that we randomly re-arranging the content of that structure. To shuffle an array we will use the following algorithms:
Algorithm 1: 
javascript
function shuffleArray(array) {   for (var i = array.length - 1; i > 0; i--) {          // Generate random number       var j = Math.floor(Math.random() * (i + 1));                          var temp = array[i];       array[i] = array[j];       array[j] = temp;   }          return array;}
Example: 
html
<!DOCTYPE html><html> <head>    <title>Shuffle array</title></head> <body>      <p>Array is=[1, 2, 3, 4, 5, 6, 7]</p>           <button onclick="show()">        click    </button>         <script>         // Function to shuffle the array content        function shuffleArray(array) {            for (var i = array.length - 1; i > 0; i--) {                 // Generate random number                var j = Math.floor(Math.random() * (i + 1));                 var temp = array[i];                array[i] = array[j];                array[j] = temp;            }             return array;        }         // Function to show the result        function show() {            var arr = [1, 2, 3, 4, 5, 6, 7]            var arr1 = shuffleArray(arr)             document.write("After shuffling: ", arr1)        }    </script></body> </html>
Output:  
Before Clicking the Button:  
After Clicking the button:  
Algorithm 2:
Passing a function that returns (random value – 0.5 ) as comparator to sort function, so as to sort elements on random basis. 
Javascript
function shuffleArray(array) {    return array.sort( ()=>Math.random()-0.5 ); }
Example: 
HTML
<!DOCTYPE html><html> <head>    <title>Shuffle array</title></head> <body>      <p>Array is=[1, 2, 3, 4, 5, 6, 7]</p>            <button onclick="show()">        click    </button>         <script>         // Function to shuffle the array content        function shuffleArray(array) {           return array.sort( ()=>Math.random()-0.5 );        }         // Function to show the result        function show() {            var arr = [1, 2, 3, 4, 5, 6, 7]            var arr1 = shuffleArray(arr)             document.write("After shuffling: ", arr1)        }    </script></body> </html>
 Output:  
Before Clicking the Button: 
After Clicking the button: 
 
omkarphansopkar
anikakapoor
JavaScript-Questions
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
C# Program to Demonstrate the Array of Structures - GeeksforGeeks

29 Oct, 2021
An array of structures means each array index contains structure as a value. In this article, we will create the array of structure and access structure members using an array with a specific index.
Syntax
array[index].Structure(Details);
where index specifies the particular position to be inserted and details are the values in the structure
Example:
Input:
Insert three values in an array
Student[] student = { new Student(), new Student(), new Student() };
student[0].SetStudent(1, "ojaswi", 20);
student[1].SetStudent(2, "rohith", 21);
student[2].SetStudent(3, "rohith", 21);

Output:
(1, "ojaswi", 20)
(2, "rohith", 21)
(3, "rohith", 21)
Approach:
Declare three variables id , name and age.Set the details in the SetStudent() method.Create array of structure for three students.Pass the structure to array index for three students separately.Display the students by calling DisplayStudent() method
Declare three variables id , name and age.
Set the details in the SetStudent() method.
Create array of structure for three students.
Pass the structure to array index for three students separately.
Display the students by calling DisplayStudent() method
Example:
C#
// C# program to display the array of structureusing System; public struct Employee{         // Declare three variables    // id, name and age    public int Id;    public string Name;    public int Age;         // Set the employee details    public void SetEmployee(int id, string name, int age)    {        Id = id;        Name = name;        Age = age;    }         // Display employee details    public void DisplayEmployee()    {        Console.WriteLine("Employee:");        Console.WriteLine("\tId    : " + Id);        Console.WriteLine("\tName   : " + Name);        Console.WriteLine("\tAge   : " + Age);        Console.WriteLine("\n");    }} class GFG{ // Driver codestatic void Main(string[] args){         // Create array of structure    Employee[] emp = { new Employee(),                       new Employee(),                       new Employee() };         // Pass the array indexes with values as structures    emp[0].SetEmployee(1, "Ojaswi", 20);    emp[1].SetEmployee(2, "Rohit", 21);    emp[2].SetEmployee(3, "Mohit", 23);     // Call the display method    emp[0].DisplayEmployee();    emp[1].DisplayEmployee();    emp[2].DisplayEmployee();}}
Output:
Employee:
    Id    : 1
    Name   : Ojaswi
    Age   : 20


Employee:
    Id    : 2
    Name   : Rohit
    Age   : 21


Employee:
    Id    : 3
    Name   : Mohit
    Age   : 23
surindertarika1234
CSharp-Arrays
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
Set toArray() method in Java with Example - GeeksforGeeks

24 Aug, 2021
The toArray() method of Java Set is used to form an array of the same elements as that of the Set. Basically, it copies all the element from a Set to a new array.Syntax:  
Object[] toArray()
Parameters: The method takes optional parameter. If we provide the type of Object array we want we can pass it as an argument. for ex: set.toArray(new Integer[0]) returns an array of type Integer, we can also do it as set.toArray(new Integer[size]) where size is the size of the resultant array. Doing it in the former way works as the required size is allocated internally. Return Value: The method returns an array containing the elements similar to the Set.Below programs illustrate the Set.toArray() method:Program 1: 
Java
// Java code to illustrate toArray() import java.util.*; public class SetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<String> abs_col = new HashSet<String>();         // Use add() method to add        // elements into the Set        abs_col.add("Welcome");        abs_col.add("To");        abs_col.add("Geeks");        abs_col.add("For");        abs_col.add("Geeks");         // Displaying the Set        System.out.println("The Set: "                           + abs_col);         // Creating the array and using toArray()        Object[] arr = abs_col.toArray();         System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The Set: [Geeks, For, Welcome, To]
The array is:
Geeks
For
Welcome
To
 
Program 2: 
Java
// Java code to illustrate toArray() import java.util.*; public class SetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<Integer> abs_col = new HashSet<Integer>();         // Use add() method to add        // elements into the Set        abs_col.add(10);        abs_col.add(15);        abs_col.add(30);        abs_col.add(20);        abs_col.add(5);        abs_col.add(25);         // Displaying the Set        System.out.println("The Set: " + abs_col);         // Creating the array and using toArray()        Integer[] arr = abs_col.toArray(new Integer[0]);         System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The Set: [20, 5, 25, 10, 30, 15]
The array is:
20
5
25
10
30
15
 
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray() 
shubho2001g
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
For loop in Julia - GeeksforGeeks

19 Feb, 2020
For loops are used to iterate over a set of values and perform a set of operations that are given in the body of the loop. For loops are used for sequential traversal. In Julia, there is no C style for loop, i.e., for (i = 0; i < n; i++). There is a "for in" loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals.
 
 
Syntax:
for iterator in range
    statements(s)
end

Here, ‘for‘ is the keyword stating for loop, ‘in‘ keyword is used to define a range in which to iterate, ‘end‘ keyword is used to denote the end of for loop.
Example:
# Julia program to illustrate # the use of For loop  print("List Iteration\n") l = ["geeks", "for", "geeks"] for i in l    println(i) end  # Iterating over a tuple (immutable) print("\nTuple Iteration\n") t = ("geeks", "for", "geeks") for i in t    println(i) end  # Iterating over a String print("\nString Iteration\n")     s = "Geeks"for i in s     println(i) end
Output: Nested for-loop: Julia programming language allows to use one loop inside another loop. The following section shows an example to illustrate the concept.Syntax:
for iterator in range
    for iterator in range 
        statements(s) 
        statements(s)
    end
end
 
Example:
# Julia program to illustrate # the use of Nested For-Loops  # Outer For-loopfor i in 1:5       # Inner For-loop    for j in 1:i                   # Print statement        print(i, " ")    end    println() end
Output:
Julia-loops
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Taking Input from Users in Julia
Get array dimensions and size of a dimension in Julia - size() Method
numpy.bincount() in Python - GeeksforGeeks

17 Nov, 2020
In an array of +ve integers, the numpy.bincount() method counts the occurrence of each element. Each bin value is the occurrence of its index. One can also set the bin size accordingly.Syntax :
numpy.bincount(arr, weights = None, min_len = 0)
Parameters :
arr     : [array_like, 1D]Input array, having positive numbers
weights : [array_like, optional]same shape as that of arr
min_len : Minimum number of bins we want in the output array

Return :
Output array with no. of occurrence of index value of bin in input - arr. 
Output array, by default is of the length max element of arr + 1. 
Here size of the output array would be max(input_arr)+1.

Code 1 : Working of bincount() in NumPy
# Python Program explaining # working of numpy.bincount() method  import numpy as geek  # 1D array with +ve integersarray1 = [1, 6, 1, 1, 1, 2, 2]bin = geek.bincount(array1)print("Bincount output  : \n ", bin)print("size of bin : ", len(bin), "\n")  array2 = [1, 5, 5, 5, 4, 5, 5, 2, 2, 2]bin = geek.bincount(array2)print("Bincount output  : \n ", bin)print("size of bin : ", len(bin), "\n")  # using min_length attributelength = 10bin1 = geek.bincount(array2, None, length)print("Bincount output  : \n ", bin1)  print("size of bin : ", len(bin1), "\n")
Output :
Bincount output  : 
  [0 4 2 0 0 0 1]
size of bin :  7 

Bincount output  : 
  [0 1 3 0 1 5]
size of bin :  6 

Bincount output  : 
  [0 1 3 0 1 5 0 0 0 0]
size of bin :  10 


Code 2 : We can perform addition as per element with bincount() weight
# Python Program explaining # working of numpy.bincount() method  import numpy as geek  # 1D array with +ve integersarray2 = [10, 11, 4, 6, 2, 1, 9]array1 = [1, 3, 1, 3, 1, 2, 2]  # array2 : weightbin = geek.bincount(array1, array2)print("Summation element-wise : \n", bin)  #index 0 : 0#index 1 : 10 + 4 + 2 = 16#index 2 : 1 + 9 = 10#index 3 : 11 + 6 = 17
Output :
Summation element-wise : 
 [  0.  16.  10.  17.]
References :https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html#numpy.bincount.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
CodeWithPriyansh
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to install the previous version of node.js and npm ? - GeeksforGeeks

20 Mar, 2020
Node.js: It is a JavaScript runtime(server-side) built on V8 JavaScript engine of Google Chrome. It was developed in 2009 by Ryan Dhal. Node.js uses an event-driven, non-blocking input/output model that makes it lightweight and efficient. It is perfect for data-intensive real-time applications. Node is like a wrapper around the V8 with built-in modules providing many features that are easy to use in asynchronous APIs.
NPM: NPM(Node Package Manager) installs and manages version and dependency of packages for Node.js. NPM is installed with Node. The aim of NPM is automated dependency and package management, anytime or anyone needs to get started with the project they can simply rum NPM install and all the dependencies they will have immediately. It is possible to specify which version your project depends upon to save your project from breaking due to updates.
Installing the previous version of Node.js and NPM: To install the previous versions from the latest version, the latest version of Node.js should be installed on your computer or you can install it from the official site of Node.js.
Step 1: Check the installed version of Node and NPM on the computer use the following command respectively
In windows:node -vnpm -v
node -v
npm -v
In linux:node --versionnpm --version
node --version
npm --version
Step 2: For installing the previous version of Node use the following command:
In windows:npm install -g node@versionExample:npm install -g node@10.9.0 
npm install -g node@version
Example:
npm install -g node@10.9.0 
In linux:sudo  apt-get install nodejs=version-1chl1~precise1Example:sudo  apt-get install nodejs=10.9.0-1chl1~precise1
sudo  apt-get install nodejs=version-1chl1~precise1
Example:
sudo  apt-get install nodejs=10.9.0-1chl1~precise1
Step 3: To install previous version of NPM use the following command:
In windows:npm install -g npm@version Example:npm install -g npm@4.0.0
npm install -g npm@version 
Example:
npm install -g npm@4.0.0
In linux:sudo  apt-get install npm=version-1chl1~precise1Example:sudo  apt-get install npm=4.0.0-1chl1~precise1
sudo  apt-get install npm=version-1chl1~precise1
Example:
sudo  apt-get install npm=4.0.0-1chl1~precise1
Node.js
Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Find the unique rows in R DataFrame - GeeksforGeeks

07 Apr, 2021
In an R data frame, a unique row means that none of the elements in that row are replicated in the whole data frame with the same combination. In simple terms, if we have a data frame called df with four columns and five rows, we can assume that none of the values in one row are replicated in every other row.
If we have many redundant rows in our data collection, we can need to look for certain types of rows. We can use the dplyr package’s group_by_all function to achieve this. It will group all the redundant rows and return unique rows with their count.
Example 1:
R
library("dplyr")  df = data.frame(x = as.integer(c(1, 1, 2, 2, 3, 4, 4)),                 y = as.integer(c(1, 1, 2, 2, 3, 4, 4)))  print("dataset is ")print(df)  ans = df%>%group_by_all%>%countprint("unique rows with count are")print(ans)
Output:
Example 2:
R
library("dplyr")  df = data.frame(x = as.integer( c(10,10,20,20,30,40,40) ),                y = c("rahul", "rahul", "mohan","mohan", "rohit", "rohan", "rohan"))  print("dataset is ")print(df)  ans = df%>%group_by_all%>%countprint("unique rows with count are")print(ans)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
Hashtable size() Method in Java - GeeksforGeeks

28 Jun, 2018
The java.util.Hashtable.size() method of Hashtable class is used to get the size of the table which refers to the number of the key-value pair or mappings in the Table.
Syntax:
Hash_Table.size()
Parameters: The method does not take any parameters.
Return Value: The method returns the size of the table which also means the number of key-value pairs present in the table.
Below programs illustrates the working of java.util.Hashtable.size():Program 1:
// Java code to illustrate the size() methodimport java.util.*;  public class Hash_Table_Demo {    public static void main(String[] args)    {          // Creating an empty Hashtable        Hashtable<Integer, String> hash_table =         new Hashtable<Integer, String>();          // Inserting elements into the table        hash_table.put(10, "Geeks");        hash_table.put(15, "4");        hash_table.put(20, "Geeks");        hash_table.put(25, "Welcomes");        hash_table.put(30, "You");          // Displaying the Hashtable        System.out.println("Initial table is: " + hash_table);          // Displaying the size of the table        System.out.println("The size of the table is " +         hash_table.size());    }}
Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The size of the table is 5

Program 2:
// Java code to illustrate the size() methodimport java.util.*;  public class Hash_Table_Demo {    public static void main(String[] args)    {          // Creating an empty Hashtable        Hashtable<String, Integer> hash_table =         new Hashtable<String, Integer>();          // Inserting elements into the table        hash_table.put("Geeks", 10);        hash_table.put("4", 15);        hash_table.put("Geeks", 20);        hash_table.put("Welcomes", 25);        hash_table.put("You", 30);          // Displaying the Hashtable        System.out.println("Initial Table is: " + hash_table);          // Displaying the size of the table        System.out.println("The size of the table is " +         hash_table.size());    }}
Initial Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The size of the table is 4

Note: The same operation can be performed with any type of variation and combination of different data types.
Java-HashTable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java