code-rag-bench/online-tutorials huggingface dataset:
Hashcat Tool in Kali Linux - GeeksforGeeks

25 Jan, 2021
Hashcat is famous as the fastest password cracker and password recovery utility. Hashcat is designed to break or crack even the most complex passwords in a very less amount of time.
Features of hashcat:
The 90+ Algorithm can be implemented with performance and optimization in mind.
The number of threads can be configured.
Hashcat is a multi-algorithm based ( MD5, MD4, MySQL, SHA1, NTLM, DCC, etc.).
All attacks can be extended by specialized rules.
It is multi-hash and multi-OS based (Windows and Linux).
It supports both hex-charset and hex-salt files.
Installation: Usually Hashcat tool comes pre-installed with Kali Linux but if we need to install it write down the given command in the terminal.
sudo apt-get install hashcat
Now, you can find the hashcat Tool in Password Cracking Tools :
We are going to perform Dictionary Attack to crack Password in this article.
1. Creating Hash Entries
These entries will then be outputted to a file called “Dictionary_hashes”. 
-n: This option removes the new line added to the end of entries as we don’t want the newline characters to be hashed with our entries.
tr -d: This option removes any characters that are a space or hyphen from the output.
2. Checking the stored Hashes
We can check the stored hashes with the help of the below command :
cat Dictionary_hashes.txt
Some password hashes that can be cracked with hashcat can be seen below :
3.  Choose the wordlists
We are going to use the “rockyou” wordlist.
4. Cracking the Hashes
Now we can crack the hashes that we stored in Dictionary_hashes.txt and we will store the result in the Done.txt file.
5. Results
Now we can see the results stored in the Done.txt file by the below command:
cat Done.txt
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
How to get substring of a string in jQuery?

To get substring of a string in jQuery, use the substring() method. It has the following two parameters:
from: The from parameter specifies the index where to start the substring.
to: The to parameter is optional. It specifies the index where to stop the extraction. This is an optional parameter, which extracts the remaining string, when nothing is mentioned.
You can try to run the following code to learn how to get substring of a string in jQuery:
Live Demo
<html>

   <head>
      <title>jQuery subtring</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
            $("#button1").click(function(){
              var str1 = "Hello World!";
              var subStr = str1.substring(0, 5);
              alert(subStr);
            });
         });
      </script>
       
   </head>
   
   <body>
     <p>Hello World!</p>
     <button id="button1">Get substring</button>        
   </body>
   
</html>
SAS - IF-THEN-DELETE Statement

An IF-THEN-DELETE statement consists of a boolean expression followed by SAS THEN DELETE statement.
The basic syntax for creating an if statement in SAS is −
IF (condition ) THEN DELETE;
If the condition evaluates to be true, then the respective observation is processed.
DATA EMPDAT;
INPUT   EMPID ENAME $ SALARY DEPT $ DOJ DATE9.;
LABEL ID = 'Employee ID';
FORMAT DOJ DATE9.;
DATALINES;
1 Rick 623.3 IT 02APR2001
2 Dan 515.2 OPS 11JUL2012
3 Mike 611.5 IT 21OCT2000
4 Ryan 729.1 HR 30JUL2012
5 Gary 843.2 FIN 06AUG2000
6 Tusar 578.6 IT 01MAR2009
7 Pranab 632.8 OPS 16AUG1998
8 Rasmi 722.5 FIN 13SEP2014
;
Data EMPDAT1;
Set EMPDAT;
IF SALARY > 700 THEN DELETE;
PROC PRINT DATA = EMPDAT1;
run; 
When the above code is executed, it produces the following result −

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
C# - For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in C# is −
for ( init; condition; increment ) {
   statement(s);
}

Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates.
using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         
         /* for loop execution */
         for (int a = 10; a < 20; a = a + 1) {
            Console.WriteLine("value of a: {0}", a);
         }
         Console.ReadLine();
      }
   }
} 
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
How to create a CSV file manually in PowerShell?

There are few methods to create a CSV file in the PowerShell, but we will use the best easy method
to create it.
First, to create a CSV file in PowerShell, we need to create headers for it. But before it, we need
output file name along with its path.
$outfile = "C:\temp\Outfile.csv"
Here we have given output file name Outfile.csv in the path C:\temp.
Now we will create headers,
$newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile
Here, we have created a CSV file and exported a file to the newly created file.
We will now import this file to check if the headers are created.
Import-Csv $outfile
EMP_Name EMP_ID CITY
-------- ------ ----
So, in the above output, we can see the headers are created.
Now we need to insert the data inside the CSV file, for that we first import CSV file into a variable
and then we will insert data.
$csvfile = Import-Csv $outfile
$csvfile.Emp_Name = "Charles"
$csvfile.EMP_ID = "2000"
$csvfile.CITY = "New York"
Check the output of the above-inserted data.
PS C:\WINDOWS\system32> $csvfile
EMP_Name    EMP_ID    CITY
--------    ------    ----
Charles     2000      New York
Overall commands to create a script −
$outfile = "C:\temp\Outfile.csv"
$newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile
$csvfile = Import-Csv $outfile
$csvfile.Emp_Name = "Charles"
$csvfile.EMP_ID = "2000"
$csvfile.CITY = "New York"
This output is stored into the variable, to store this output into the created CSV file, you need to
export CSV file to the output file again as shown in the below example.
$csvfile | Export-CSV $outfile
Import-Csv $outfile
EMP_Name    EMP_ID       CITY
--------    ------       ----
Charles     2000 New     York
find_elements_by_xpath() driver method - Selenium Python - GeeksforGeeks

14 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.
This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_xpath() is discussed in this article. This method returns a list with type of elements specified. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications.To grab a single first element, checkout – find_element_by_xpath() driver method – Selenium Python
driver.find_elements_by_xpath("xpath")

Example –For instance, consider this page source:
<html> <body>  <form id="loginForm">   <input name="username" type="text" />   <input name="password" type="password" />   <input name="submit" type="submit" value="Login" />  </form> </body><html>
Now after you have created a driver, you can grab an element using –
login_form = driver.find_elements_by_xpath('//input[@name='username']')

Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “articleTitle”.Create a file called run.py to demonstrate find_elements_by_xpath method –
# Python program to demonstrate# selenium  # import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # enter keyword to searchkeyword = "geeksforgeeks"  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get elementselements = driver.find_elements_by_xpath("//div[@name ='articlePath']")  # print complete elements listprint(element)
Now run using –
Python run.py
First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below.Browser Output –Terminal Output –
Python-selenium
selenium
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
sciPy stats.zmap() function | Python - GeeksforGeeks

20 Feb, 2019
scipy.stats.zmap(scores, compare, axis=0, ddof=0) function computes the relative Z-score of the input data. The scores that are standardized to zero mean and unit variance, where mean and variance are calculated from the comparison array.
Its formula:
Parameters :scores : [array_like]Input array or object for which Z-score is to calculate.compare : [array_like]Input array or object for which the mean and standard deviation of the normalization are takenaxis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation.
Results : Z-score of the input data.
Code #1: Working
# stats.zmap() method   import numpy as npfrom scipy import stats    arr1 = [[20, 2, 7, 1, 34],        [50, 12, 12, 34, 4]]  arr2 = [[50, 12, 12, 34, 4],         [12, 11, 10, 34, 21]]  print ("\narr1 : ", arr1)print ("\narr2 : ", arr2)  print ("\nZ-score : \n", stats.zmap(arr1, arr2))
Output :
arr1 :  [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]]

arr2 :  [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]]

Z-score : 
 [[ -0.57894737 -19.          -4.                 -inf   2.52941176]
 [  1.           1.           1.                  nan  -1.        ]]

 Code #2 : Z-score
# stats.zmap() method   import numpy as npfrom scipy import stats    arr1 = [[20, 2, 7, 1, 34],        [50, 12, 12, 34, 4]]  arr2 = [[50, 12, 12, 34, 4],         [12, 11, 10, 34, 21]]  print ("\nZ-score : \n", stats.zmap(arr1, arr2, axis = 1))
Output :
sem ratio for arr1 : 
 [[-0.14087457 -1.19743386 -0.90394517 -1.2561316   0.68089376]
 [ 3.5640998  -0.61601725 -0.61601725  1.80405051 -1.49604189]]

Python scipy-stats-functions
Python-scipy
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
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Java Program to check whether two Strings are an anagram or not.

According to wiki “An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.”
To compare whether two strings are anagrams check if their lengths are equal? If so, convert these two strings into character arrays then, sort them and compare them using the sort() method of the Arrays class, if both are equal then given two strings are anagrams.
Live Demo
import java.util.Arrays;
public class AnagramSample  {
   public static void main(String args[]) {
      String str1 = "recitals";
      String str2 = "articles";

      if (str1.length()==str2.length()) {
         char[] arr1 = str1.toCharArray();
         Arrays.sort(arr1);
         System.out.println(Arrays.toString(arr1));
         char[] arr2 = str2.toCharArray();
         Arrays.sort(arr2);
         System.out.println(Arrays.toString(arr2));
         System.out.println(Arrays.equals(arr1, arr2));
         if(arr1.equals(arr2)) {
            System.out.println("Given strings are anagrams");
         } else {
            System.out.println("Given strings are not anagrams");
         }
      }
   }
}
[a, c, e, i, l, r, s, t]
[a, c, e, i, l, r, s, t]
true
Given strings are not anagrams
PyQt - QDialog Class

A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed).
PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc.
In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key.
A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar.
The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal.
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Hello World!")
   b.move(50,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt Dialog demo")
   w.show()
   sys.exit(app.exec_())
	
def showdialog():
   d = QDialog()
   b1 = QPushButton("ok",d)
   b1.move(50,50)
   d.setWindowTitle("Dialog")
   d.setWindowModality(Qt.ApplicationModal)
   d.exec_()
	
if __name__ == '__main__':
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Nagios - NRPE

The Nagios daemon which run checks on remote machines in NRPE (Nagios Remote Plugin Executor). It allows you to run Nagios plugins on other machines remotely. You can monitor remote machine metrics such as disk usage, CPU load etc. It can also check metrics of remote windows machines through some windows agent addons.
Let us see how to install and configure NRPE step by step on client machine which needs to be monitored.
Step 1 − Run below command to install NRPE on the remote linux machine to be monitored.
sudo apt-get install nagios-nrpe-server nagios-plugins

Step 2 − Now, create a host file inside the server directory, and put all the necessary definitions for the host.
sudo gedit /usr/local/nagios/etc/servers/ubuntu_host.cfg

# Ubuntu Host configuration file

define host {
   use linux-server
   host_name ubuntu_host
   alias Ubuntu Host
   address 192.168.1.10
   register 1
}

define service {
   host_name ubuntu_host
   service_description PING
   check_command check_ping!100.0,20%!500.0,60%
   max_check_attempts 2
   check_interval 2
   retry_interval 2
   check_period 24x7
   check_freshness 1
   contact_groups admins
   notification_interval 2
   notification_period 24x7
   notifications_enabled 1
   register 1
}

define service {
   host_name ubuntu_host
   service_description Check Users
   check_command check_local_users!20!50
   max_check_attempts 2
   check_interval 2
   retry_interval 2
   check_period 24x7
   check_freshness 1
   contact_groups admins
   notification_interval 2
   notification_period 24x7
   notifications_enabled 1
   register 1
}

define service {
   host_name ubuntu_host
   service_description Local Disk
   check_command check_local_disk!20%!10%!/
   max_check_attempts 2
   check_interval 2
   retry_interval 2
   check_period 24x7
   check_freshness 1
   groups admins
   notification_interval 2
   notification_period 24x7
   notifications_enabled 1
   register 1
}

define service {
   host_name ubuntu_host
   service_description Check SSH
   check_command check_ssh
   max_check_attempts 2
   check_interval 2
   retry_interval 2
   check_period 24x7
   check_freshness 1
   contact_groups admins
   notification_interval 2
   notification_period 24x7
   notifications_enabled 1
   register 1
}

define service {
   host_name ubuntu_host
   service_description Total Process
   check_command check_local_procs!250!400!RSZDT
   max_check_attempts 2
   check_interval 2
   retry_interval 2
   check_period 24x7
   check_freshness 1
   contact_groups admins
   notification_interval 2
   notification_period 24x7
   notifications_enabled 1
   register 1
}
Step 3 − Run the command shown below for the verification of configuration file.
sudo /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

Step 4 − Restart NRPE, Apache and Nagios if there are no errors.
service nagios-nrpe-server restart
service apache2 restart
service nagios restart

Step 5 − Open your browser and go to Nagios web interface. You can see the host which needs to be monitored has been added to Nagios core service. Similarly, you can add more hosts to be monitored by Nagios.
 Print
 Add Notes
 Bookmark this page
Python | Multiple indices Replace in String - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python Stings, we can have a problem, in which we need to perform the replace of characters based on several indices of String. This kind of problem can have applications in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + join()This is brute force way in which this task can be performed. In this, we iterate for each character and substitute with replace character if that is one.
# Python3 code to demonstrate working of # Multiple indices Replace in String# Using loop + join()  # initializing stringtest_str = 'geeksforgeeks is best'  # printing original stringprint("The original string is : " + test_str)  # initializing list test_list = [2, 4, 7, 10]  # initializing repl charrepl_char = '*'  # Multiple indices Replace in String# Using loop + join()temp = list(test_str)for idx in test_list:    temp[idx] = repl_charres = ''.join(temp)  # printing result print("The String after performing replace : " + str(res)) 
The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best

 
Method #2 : Using list comprehension + join()The combination of above functions can also be used to perform this task. In this, we perform similar task as above, just in one liner format using list comprehension.
# Python3 code to demonstrate working of # Multiple indices Replace in String# Using list comprehension + join()  # initializing stringtest_str = 'geeksforgeeks is best'  # printing original stringprint("The original string is : " + test_str)  # initializing list test_list = [2, 4, 7, 10]  # initializing repl charrepl_char = '*'  # Multiple indices Replace in String# Using list comprehension + join()temp = list(test_str)res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]res = ''.join(res)  # printing result print("The String after performing replace : " + str(res)) 
The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Pafy - Getting Watch URL for Each Item of Playlist - GeeksforGeeks

20 Jul, 2020
In this article we will see how we can get the watch URLfrom playlist items in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A playlist in YouTube is a list, or group, of videos that plays in order, one video after the other. Watch URL is basically youtube actual URL for each item i.e each playlist video.
We can get the playlist from youtube in pafy with the help of get_playlist method, below is the command given to do this
 pafy.get_playlist(url)
The playlist url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform.
Steps to get the playlist ID1. Import the pafy module2. Get the playlist with the help of URL of playlist3. Return play list work as dictionary so use ‘items’ as key with the return playlist4. Store the result in variable and from the items select the single item5. With the single item use ‘pafy’ key with it6. Use watchv_url attribute with this pafy object to get the url
In order to do this we use watchv_url attribute with the playlist item’s pafy object
Syntax : playlist_pafy.watchv_url
Argument : It takes no argument
Return : It returns string
Below is the implementation
# importing pafyimport pafy     # url of playlisturl = "https://www.youtube.com / playlist?list = PLqM7alHXFySGqCvcwfqqMrteqWukz9ZoE"  # getting playlistplaylist = pafy.get_playlist(url)  # getting playlist itemsitems = playlist["items"]  # selecting single itemitem = items[1]  # getting pafy objecti_pafy = item['pafy']      # getting watch urly_url = i_pafy.watchv_url  # printing urlprint(y_url)
Output :
http://www.youtube.com/watch?v=AfxHGNRtFac
Another example
# importing pafyimport pafy     # url of playlisturl = "https://www.youtube.com / playlist?list = PLqM7alHXFySE71A2bQdYp37vYr0aReknt"    # getting playlistplaylist = pafy.get_playlist(url)  # getting playlist itemsitems = playlist["items"]  # selecting single itemitem = items[1]  # getting pafy objecti_pafy = item['pafy']            # getting watch urly_url = i_pafy.watchv_url  # printing urlprint(y_url)
Output :
http://www.youtube.com/watch?v=WdgAKCnWnwA
Python-Pafy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
NumPy Array Copy vs View

The main difference between a copy and a view of an array is that
the copy is a new array, and the view is just a view of the original array.
The copy owns the data and any changes made to the copy will not 
affect original array, and any changes made to the original array will not 
affect the copy.
The view does not own the data and any changes made to the view will 
affect the original array, and any changes made to the original array will 
affect the view.
Make a copy, change the original array, and display both arrays:
The copy SHOULD NOT be affected by the changes made to the original array.
Make a view, change the original array, and display both arrays:
The view SHOULD be affected by the changes made to the original array.
Make a view, change the view, and display both arrays:
The original array SHOULD be affected by the changes made to the view.
As mentioned above, copies owns the data, and views does not own 
the data, but how can we check this?
Every NumPy array has the attribute base that 
returns None if the array owns the data.
Otherwise, the base  attribute refers to the original object.


Print the value of the base attribute to check if an array owns it's data or 
not:
The copy returns None.The view returns the original array.
Use the correct method to make a copy of the array.
arr = np.array([1, 2, 3, 4, 5])

x = arr.

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
C Program for Counting Sort - GeeksforGeeks

10 Oct, 2021
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.  
C
// C Program for counting sort#include <stdio.h>#include <string.h>#define RANGE 255 // The main function that sort the given string arr[] in// alphabetical ordervoid countSort(char arr[]){    // The output character array that will have sorted arr    char output[strlen(arr)];     // Create a count array to store count of individual    // characters and initialize count array as 0    int count[RANGE + 1], i;    memset(count, 0, sizeof(count));     // Store count of each character    for(i = 0; arr[i]; ++i)        ++count[arr[i]];     // Change count[i] so that count[i] now contains actual    // position of this character in output array    for (i = 1; i <= RANGE; ++i)        count[i] += count[i-1];     // Build the output character array    for (i = 0; arr[i]; ++i)    {        output[count[arr[i]]-1] = arr[i];        --count[arr[i]];    }     // Copy the output array to arr, so that arr now    // contains sorted characters    for (i = 0; arr[i]; ++i)        arr[i] = output[i];} // Driver program to test above functionint main(){    char arr[] = "geeksforgeeks";//"applepp";     countSort(arr);     printf("Sorted character array is %sn", arr);    return 0;}
Sorted character array is eeeefggkkorssn
 
Please refer complete article on Counting Sort for more details! 
simmytarika5
surinderdawra388
counting-sort
C Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to Append a Character to a String in C
Program to find Prime Numbers Between given Interval
time() function in C
Bubble Sort
Selection Sort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Merge two sorted arrays
C++ Program to Find Factorial of a Number using Iteration

Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n.
For example: The factorial of 6 is 720.
6! = 6 * 5 * 4 * 3 * 2 *1
6! = 720
The factorial of an integer can be found using a recursive program or an iterative program.
A for loop can be used to find the factorial of a number using an iterative program. This is demonstrated as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int n = 6, fact = 1, i;
   for(i=1; i<=n; i++)
   fact = fact * i;
   cout<<"Factorial of "<< n <<" is "<<fact;
   return 0;
}
Factorial of 6 is 720
In the above program, the for loop runs from 1 to n. For each iteration of the loop, fact is multiplied with i. The final value of fact is the product of all numbers from 1 to n. This is demonstrated using the following code snippet.
for(i=1; i<=n; i++)
fact = fact * i;
multiset count() function in C++ STL

06 Oct, 2021
The multiset::count() function is a built-in function in C++ STL that searches for a specific element in the multiset container and returns the number of occurrences of that element. 
Syntax:  
multiset_name.count(val)
Parameters: The function accepts a single parameter val which specifies the element to be searched in the multiset container. 
Return Value: The function returns the count of elements which is equal to val in the multiset container. 
Below programs illustrates the multiset::count() function: 
Program 1:  
C++
// C++ program to demonstrate the// multiset::count() function#include <bits/stdc++.h>using namespace std;int main(){     int arr[] = { 15, 10, 15, 11, 10, 18, 18, 20, 20 };     // initializes the set from an array    multiset<int> s(arr, arr + 9);     cout << "15 occurs " << s.count(15)         << " times in container";     return 0;}
15 occurs 2 times in container
 
Program 2: 
C++
// C++ program to demonstrate the// multiset::count() function#include <bits/stdc++.h>using namespace std;int main(){     int arr[] = { 15, 10, 15, 11, 10, 18, 18, 18, 18 };     // initializes the set from an array    multiset<int> s(arr, arr + 9);     cout << "18 occurs " << s.count(18)         << " times in container";     return 0;}
18 occurs 4 times in container
 
The time complexity of the multiset::count() function is O(K + log(N)), where K is the total count of integers of the value passed.
arorakashish0911
kartikmodi
CPP-Functions
cpp-multiset
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Multiple User Accounts in Linux?

Adding a single new user to a Linux system can be achieved through the useradd command. But system admins often get request to add many users. So Linux provides a different to do a bulk addition of many users to a system.This is the newusers command.
sudo newusers user_deatils.txt
user_details.txt is the file containing the details of all the usernames to be added.
Below we see the structure of user_details.txt file.
UserName:Password:UID:GID:comments:HomeDirectory:UserShell
So we create a file with below details to add many usres.
~$ cat MoreUsers.txt
uname1:pwd#@1:2112:3421:storefront:/home/uname1:/bin/bash
uname3:pwd#!@3:2112:3525:backend:/home/uname3:/bin/bash
uname4:pwd#$$9:9002:4721:HR:/home/uname4:/bin/bash
Before we sue the user details file to add new users, we should give permission to it to be read by other processes.
sudo chmod 0600 MoreUsers.txt
Lets verify the existing users in the system by going to the /etc/passwd file.
ubuntu@ubuntu:~$ tail -5 /etc/passwd
Running the above code gives us the following result −
pulse:x:117:124:PulseAudio daemon,,,:/var/run/pulse:/bin/false
rtkit:x:118:126:RealtimeKit,,,:/proc:/bin/false
saned:x:119:127::/var/lib/saned:/bin/false
usbmux:x:120:46:usbmux daemon,,,:/var/lib/usbmux:/bin/false
ubuntu:x:1000:1000:ubuntu16LTS,,,:/home/ubuntu:/bin/bash
next we run the newusers command to add these usernames.
sudo newusers MoreUsers.txt
Now we verify that indeed those users are added , by going again to the /etc/passwd file.
cat /etc/passwd
Running the above code gives us the following result −
...........
.............
ubuntu:x:1000:1000:ubuntu16LTS,,,:/home/ubuntu:/bin/bash
uname1:x:2112:3421:storefront:/home/uname1:/bin/bash
uname3:x:2112:3525:backend:/home/uname3:/bin/bash
uname4:x:9002:4721:HR:/home/uname4:/bin/bash
Check If It Is a Straight Line in C++

Suppose we have a list of data-points consisting of (x, y) coordinates, we have to check whether the data-points are forming straight line or not. So if the points are like [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)], then they are forming straight line.
To solve this, we will take the differences between each consecutive datapoints, and find the slope. For the first one find the slope. For all other points check whether the slope is same or not. if they are same, then simply return true, otherwise false
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int gcd(int a, int b){
      return !b?a:gcd(b,a%b);
   }
   bool checkStraightLine(vector<vector<int>>& c) {
      bool ans =true;
      bool samex = true;
      bool samey = true;
      int a = c[1][0]-c[0][0];
      int b = c[1][1]-c[0][1];
      int cc = gcd(a,b);
      a/=cc;
      b/=cc;
      for(int i =1;i<c.size();i++){
         int x = c[i][0]-c[i-1][0];
         int y = c[i][1]-c[i-1][1];
         int z = gcd(x,y);
         x/=z;
         y/=z;
         ans =ans &&(x == a )&& (y == b );
      }
      return ans;
   }
};
main(){
Solution ob;
vector<vector<int>> c = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}};
cout << ob.checkStraightLine(c);
}
[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
1
(1 indicates true)
Python - Change column names and row indexes in Pandas DataFrame

Pandas is a python library offering many features for data analysis which is not available in python standard library. One such feature is the use of Data Frames. They are rectangular grids representing columns and rows. While creating a Data frame, we decide on the names of the columns and refer them in subsequent data manipulation. But there may be a situation when we need to change the name of the columns after the data frame has been created. In this article, we will see how to achieve that.
This is the most preferred method as we can change both the column and row index using this method. We just pass in the old and new values as a dictionary of key-value pairs to this method and save the data frame with a new name.
 Live Demo
import pandas as pd

df = pd.DataFrame({
   'ColumnA': [23, 92, 32],
   'ColumnB': [54, 76, 43],
   'ColumnC': [16, 45, 10]
},
index=['10-20', '20-30', '30-40'])

df_renamed = df.rename(columns={'ColumnA': 'Col1', 'ColumnB': 'Col2', 'ColumnC': 'Col3'},
index={'10-20': '1', '20-30': '2', '30-40': '3'})
print(df)
print("\n",df_renamed)
Running the above code gives us the following result:
            ColumnA    ColumnB    ColumnC
10-20            23         54         16
20-30            92         76         45
30-40            32         43         10

           Col1      Col2        Col3
1          23         54          16
2          92         76          45
3          32         43          10
The df.columns can be assigned new column names directly. When the Data frame is used again, the new column names are referred.
 Live Demo
import pandas as pd

df = pd.DataFrame({
   'ColumnA': [23, 92, 32],
   'ColumnB': [54, 76, 43],
   'ColumnC': [16, 45, 10]
},
index=['10-20', '20-30', '30-40'])

df.columns=["Length","Breadth","Depth"]
print(df)
Running the above code gives us the following result:
          Length      Breadth Depth
10-20 23 54 16
20-30 92 76 45
30-40 32 43 10
Pandas dataframe provides methods for adding prefix and suffix to the column names. We simply use this method to add the desired prefix which gets appended to each column names.
 Live Demo
import pandas as pd

df = pd.DataFrame({
   'ColA': [23, 92, 32],
   'ColB': [54, 76, 43],
   'ColC': [16, 45, 10]
},
index=['10-20', '20-30', '30-40'])

print(df.add_prefix('Jan-'))
Running the above code gives us the following result:
         Jan-ColA    Jan-ColB    Jan-ColC
10-20          23          54          16
20-30          92          76          45
30-40          32          43          10
C program to check if a given string is Keyword or not - GeeksforGeeks

06 Feb, 2019
Given a string, the task is to write a program that checks if the given string is a keyword or not.
Keywords are reserved words which cannot be used as variable names.
There are 32 keywords in C programming language.
Examples:
Input: str = "geeks"
Output: geeks is not a keyword

Input: str = "for"
Output: for is a keyword

// C program to check whether a given// string is a keyword or not#include <stdbool.h>#include <stdio.h>#include <string.h>  // Function to check whether the given// string is a keyword or not// Returns 'true' if the string is a KEYWORD.bool isKeyword(char* str){    if (!strcmp(str, "auto") || !strcmp(str, "default")         || !strcmp(str, "signed") || !strcmp(str, "enum")         ||!strcmp(str, "extern") || !strcmp(str, "for")         || !strcmp(str, "register") || !strcmp(str, "if")         || !strcmp(str, "else")  || !strcmp(str, "int")        || !strcmp(str, "while") || !strcmp(str, "do")        || !strcmp(str, "break") || !strcmp(str, "continue")         || !strcmp(str, "double") || !strcmp(str, "float")        || !strcmp(str, "return") || !strcmp(str, "char")        || !strcmp(str, "case") || !strcmp(str, "const")        || !strcmp(str, "sizeof") || !strcmp(str, "long")        || !strcmp(str, "short") || !strcmp(str, "typedef")        || !strcmp(str, "switch") || !strcmp(str, "unsigned")        || !strcmp(str, "void") || !strcmp(str, "static")        || !strcmp(str, "struct") || !strcmp(str, "goto")        || !strcmp(str, "union") || !strcmp(str, "volatile"))        return (true);    return (false);}  // Driver codeint main(){    isKeyword("geeks") ? printf("Yes\n")                       : printf("No\n");    isKeyword("for") ? printf("Yes\n")                     : printf("No\n");    return 0;}
No
Yes

C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
Python Program for Find minimum sum of factors of number

In this article, we will learn about the solution to the problem statement given below −
Given a number input , find the minimum sum of factors of the given number.
Here we will compute all the factors and their corresponding sum and then find the minimum among them.
So to find the minimum sum of the product of number, we find the sum of prime factors of the product.
Here is the iterative implementation for the problem −
 Live Demo
#iterative approach
def findMinSum(num):
   sum_ = 0
   # Find factors of number and add to the sum
   i = 2
   while(i * i <= num):
      while(num % i == 0):
         sum_ += i
         num /= i
      i += 1
   sum_ += num
   return sum_
# Driver Code
num = 12
print (findMinSum(num))
7
All the variables are declared in the global frame as shown in the figure given below −
In this article, we learned about the approach to Find the minimum sum of factors of a number.
How to display a bold text inside the JTextArea in Java?


A JTextArea class can extend JTextComponent and allow a user to enter multiple lines of text inside it. A JTextArea can generate a CaretListener interface, which can listen to caret update events. We can set a font to a text inside the JTextArea by using setFont() method.
import java.awt.*;
import javax.swing.*;
public class JTextAreaTextBoldTest extends JFrame {
   private JTextArea textArea;
   public JTextAreaTextBoldTest() {
      setTitle("JTextAreaTextBold Test");
      setLayout(new BorderLayout());
      textArea= new JTextArea();
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);
      Font boldFont=new Font(textArea.getFont().getName(), Font.BOLD, textArea.getFont().getSize());
      textArea.setFont(boldFont); // bold text 
      add(textArea);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[]args) {
      new JTextAreaTextBoldTest();
   }
}
How to handle exception inside a Python for loop?

You can handle exception inside a Python for loop just like you would in a normal code block. This doesn't cause any issues. For example,
for i in range(5):
   try:
      if i % 2 == 0:
         raise ValueError("some error")
      print(i)
except ValueError as e:
   print(e)
This will give the output
some error
1
some error
3
some error
Tryit Editor v3.7

HTML id attribute
Tryit: id as bookmark
What are cin, cout and cerr streams in C++?

cin, cout, cerr, and clog are streams that handle standard inputs and standard outputs. These are stream objects defined in iostream header file.
std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.
std::cout is an object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog).
The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio>. It is used for outputting error to the standard output stream.
Note − All the objects declared in this header share a peculiar property - you can assume they are constructed before any static objects you define, in a translation unit that includes <iostream>. Equally, you can assume that these objects are not destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination.
You can use these stream objects as follows −
#include<iostream>
int main() {
   int my_int;
   std::cin >> my_int;
   std::cout << my_int;
   std::cerr << "An error message";
   return 0;
}
Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −
$ g++ hello.cpp
Run it using −
$ ./a.out
If you give it the input 15, this will give the output −
15 An error message
gzip - Unix, Linux Command

gunzip, gzip - compress or expand files
gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ]
gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ]
Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension .gz, while keeping the same ownership modes, access and modification times. (The default extension is -gz for VMS, z for MSDOS, OS/2 FAT, Windows NT FAT and Atari.) If no files are specified, or if a file name is "-", the standard input is compressed to the standard output. Gzip will only attempt to compress regular files. In particular, it will ignore symbolic links.
If the compressed file name is too long for its file system, gzip truncates it. Gzipattempts to truncate only the parts of the file name longer than 3 characters. (A part is delimited by dots.) If the name consists of small parts only, the longest parts are truncated. For example, if file names are limited to 14 characters, gzip.msdos.exe is compressed to gzi.msd.exe.gz. Names are not truncated on systems which do not have a limit on file name length.
By default, gzip keeps the original file name and timestamp in the compressed file. These are used when decompressing the file with the -N option. This is useful when the compressed file name was truncated or when the time stamp was not preserved after a file transfer.
Compressed files can be restored to their original form using gzip -d or gunzip or zcat. If the original name saved in the compressed file is not suitable for its file system, a new name is constructed from the original one to make it legal.
Example-1:
To Compress A File Using "gzip":
$ gzip test.sh
output:
$ lstest.sh
$ gzip test.sh
$ lstest.sh.gz
Example-2:
To Decompress A File Using The "gzip" Command:
$ gzip -d test.sh.gz
output:
$ lstest.sh.gz
$ gzip -d test.sh.gz
$ lstest.sh
Example-3:
Force A File To Be Compressed:
$ gzip -f filenatest.sh
output:
$ lstest.sh
$ gzip -f test.sh
$ lstest.sh.gz
Example-4:
To Keep The Uncompressed File:
$ gzip -k filename
output:
$ lstest.sh
$ gzip -k test.sh
$ lstest.sh  test.sh.gz
Example-5:
Compress Every File In A Folder And Subfolders:
$ gzip -r /tmp
output:
$ ls /tmp/abc  xyz
$ gzip -r /tmp/
$ ls /tmp/abc.gz  xyz.gz
Example-6:
To Test The Validity Of A Compressed File:
$ gzip -t test.sh.gz
output:
no output on screen if compressed file is valid.
Example-7:
To Change The Compression Level:
To get minimum compression at the fastest speed:
$ gzip -1 test.sh
To get maximum compression at the slowest speed:
$ gzip -9 test.sh
output:
test.sh.gz

    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