code-rag-bench/online-tutorials huggingface dataset:
How to Change the username or userID in Kali Linux? - GeeksforGeeks

30 Jun, 2020
Kali Linux allows us to enter the username while installing it and it assigns the username a unique user id to identify the user and it assigns the id itself. Now there come situations when we have to change the username or user id. This can be done easily with the help of usermod command.
But before change the username or user id we shall be aware of what is the user id or username. The details of a user such as userID, username, the complete name of the user, default shell, etc. are stored in a file which is /etc/passwd and all the password related details like the hash of the password is stored in /etc/shadow file. To get the userid or other details of a user we read passwd file and even in that file we read the line which has the details of the user in it. In order to do that we use the following command.
1. To get the user id of a user
cat /etc/passwd | grep oldusername
Replace the oldusername with the name of the user you want to use.
This will display us a few details of the user along with the userid.
2. To change the Username. We use usermod command along with -l parameter in order to change the username of a particular user.
usermod -l newusername oldusername
Replace the oldusername with the name of the user you want to change and the newusername with the new name of the user.
This command will change the username of the oldusername to the newusername but will not change the files and userID of the user.
3. To change the UserID we use usermod command along with -u parameter in order to change the userid of a particular user.
usermod -u 1234 newusername
Replace the newusername with the username you want to change the id of. And Replace 1234 with the id you want to set for the user.
This command will change the userid of the user from the default one to 1234.
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
Conditional Statements | Shell Script
Tail command in Linux with examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
scp command in Linux with Examples
Compiling with g++
Python | Count true booleans in a list - GeeksforGeeks

25 Jun, 2019
Given a list of booleans, write a Python program to find the count of true booleans in the given list.
Examples:
Input : [True, False, True, True, False]
Output : 3

Input : [False, True, False, True]
Output : 2

 Method #1 : Using List comprehension
One simple method to count True booleans in a list is using list comprehension.
# Python3 program to count True booleans in a list  def count(lst):      return sum(bool(x) for x in lst)      # Driver codelst = [True, False, True, True, False]print(count(lst))
3

 Method #2 : Using sum()
# Python3 program to count True booleans in a list  def count(lst):          return sum(lst)      # Driver codelst = [True, False, True, True, False]print(count(lst))
3

A more robust and transparent method to use sum is given below.
def count(lst):          return sum(1 for x in lst if x)
 Method #3 : count() method
# Python3 program to count True booleans in a list  def count(lst):          return lst.count(True)      # Driver codelst = [True, False, True, True, False]print(count(lst))
3

 Method #4 : filter()
# Python3 program to count True booleans in a list  def count(lst):          return len(list(filter(None, lst)))      # Driver codelst = [True, False, True, True, False]print(count(lst))
3

Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
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?
JavaScript Importing and Exporting Modules

To import and export modules using JavaScript, the code is as follows −
Note − To run this example you will need to run a localhost server.
INDEX.html
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Importing and Exporting Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>
Click on the above button to import module
</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html>
script.js
import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
   test();
})
sample.js
let resultEle = document.querySelector(".result");
export default function testImport(){
   resultEle.innerHTML = 'Module testImport has been imported';
}
On clicking the ‘IMPORT’ button −
How to delete a character from a string using python?

If you want to delete a character at a certain index from the string, you can use string slicing to create a string without that character. For example,
>>> s = "Hello World"
>>> s[:4] + s[5:]
"Hell World"
But if you want to remove all occurances of a character or a list of characters, you can use the following methods:
The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:
>>> "Hello people".replace("e", "")
"Hllo popl"
If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:
>>> import re
>>> re.sub("e|l", "", "Hello people")
"Ho pop"
Note: You can also use the [] to create group of characters to replace in regex.
C Program for factorial of a number - GeeksforGeeks

07 Aug, 2019
Factorial of a non-negative integer is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Recursive:
// C program to find factorial of given number  #include <stdio.h>  // Function to find factorial of given numberunsigned int factorial(unsigned int n){    if (n == 0)        return 1;    return n * factorial(n - 1);}  // Driver codeint main(){    int num = 5;    printf("Factorial of %d is %d",           num, factorial(num));    return 0;}
Factorial of 5 is 120

Iterative :
#include <stdio.h>  // Function to find factorial of given numberunsigned int factorial(unsigned int n){    int res = 1, i;    for (i = 2; i <= n; i++)        res *= i;    return res;}  // Driver codeint main(){    int num = 5;    printf("Factorial of %d is %d",           num, factorial(num));    return 0;}
Factorial of 5 is 120

One line Solution (Using Ternary operator):
// C++ program to find factorial of given number  #include <iostream>  int factorial(int n){    // single line to find factorial    return (n == 1 || n == 0)               ? 1               : n * factorial(n - 1);}  // Driver codeint main(){    int num = 5;    printf("Factorial of %d is %d",           num, factorial(num));    return 0;}// This code is contributed by  Rithika palaniswamy.
Factorial of 5 is 120

Using tgamma() method:
Example:
Input: n = 4
Output: 24

Syntax:
tgamma(n+1)=n!
It works upto 20! because c can't store large value

Implementation: use math.h header file for this
#include <math.h>#include <stdio.h>  int main(){      // use long long int    // for larger values of n    int n = 4;      // tgamma(n+1)=n!    n = tgamma(n + 1);      printf("%d", n);    return 0;    // This code is contributed by Soumyadip Basak}
24

The above solutions cause overflow for large numbers. Please refer factorial of large number for a solution that works for large numbers.
Please refer complete article on Program for factorial of a number for more details!
basaksoumyadip7
factorial
C Programs
factorial
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
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
How to Append a Character to a String in C
Producer Consumer Problem in C
Program to calculate First and Follow sets of given grammar
time() function in C
C++ String Library - replace

It replaces the portion of the string that begins at character pos and spans len characters.
Following is the declaration for std::string::replace.
string& replace (size_t pos,  size_t len,  const string& str,
                 size_t subpos, size_t sublen);
string& replace (size_t pos,size_t len,const string& str,
                 size_t subpos, size_t sublen);
string& replace (size_t pos,size_t len,const string& str,
                 size_t subpos, size_t sublen = npos);
pos − It is an insertion point.
pos − It is an insertion point.
str − It is a string object.
str − It is a string object.
len − It contains information about number of characters to erase.
len − It contains information about number of characters to erase.
It returns *this.
if an exception is thrown, there are no changes in the string.
In below example for std::string::replace.
#include <iostream>
#include <string>

int main () {
   std::string base="this is a test string.";
   std::string str2="n example";
   std::string str3="sample phrase";
   std::string str4="useful.";

   std::string str=base;
   str.replace(9,5,str2);
   str.replace(19,6,str3,7,6);
   str.replace(8,10,"just a");
   str.replace(8,6,"a shorty",7);
   str.replace(22,1,3,'!');

   str.replace(str.begin(),str.end()-3,str3);
   str.replace(str.begin(),str.begin()+6,"replace");
   str.replace(str.begin()+8,str.begin()+14,"is coolness",7);
   str.replace(str.begin()+12,str.end()-4,4,'o');
   str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
   std::cout << str << '\n';
   return 0;
}
The sample output should be like this −
replace is useful.

 Print
 Add Notes
 Bookmark this page
8085 program to multiply two 8 bit numbers using logical instructions - GeeksforGeeks

22 May, 2018
Prerequisite – Logical instructions in 8085 microprocessorProblem – Write a assembly language program multiply two 8 bit numbers and store the result at memory address 3050 in 8085 microprocessor.
Example –
The value of accumulator(A) after using RLC instruction is:
A = 2n*A
Where n = number of times RLC instruction is used.
Assumptions –Assume that the first number is stored at register B, and second number is stored at register C. And the result must not have any carry.
Algorithm –
Assign the value 05 to register BAssign the value 04 to register CMove the content of B in ARotate accumulator left without carryRotate accumulator left without carryStore the content of accumulator at memory address 3050Halt of the program
Assign the value 05 to register B
Assign the value 04 to register C
Move the content of B in A
Rotate accumulator left without carry
Rotate accumulator left without carry
Store the content of accumulator at memory address 3050
Halt of the program
Program –
Explanation –
MVI B 05: assign the value 05 to B register.MVI C 04: assign the value 04 to C register.MOV A, B: move the content of register B to register A.RLC: rotate the content of accumulator left without carry.RLC: rotate the content of accumulator left without carry.STA 3050: store the content of register A at memory location 3050HLT: stops the execution of the program.
MVI B 05: assign the value 05 to B register.
MVI C 04: assign the value 04 to C register.
MOV A, B: move the content of register B to register A.
RLC: rotate the content of accumulator left without carry.
RLC: rotate the content of accumulator left without carry.
STA 3050: store the content of register A at memory location 3050
HLT: stops the execution of the program.
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Logical and Physical Address in Operating System
Memory Hierarchy Design and its Characteristics
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Architecture of 8086
Computer Organization | RISC and CISC
Memory mapped I/O and Isolated I/O
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Programmable peripheral interface 8255
Creating Dynamic Dashboards with Streamlit | by M Khorasani | Towards Data Science

For those of us who have heralded all the bells and whistles brought into existence by Streamlit, from its ease of use to its ability to create powerful visualizations, we’ve largely overlooked one really handy feature. Its ability to render dynamic dashboards that can be updated in real time. I gather that most users are using Streamlit to create static dashboards or at most are utilizing the multitude of widgets available to redact dataframes that are then fed back into their visualizations. But I haven’t really seen anyone using one of the greatest inherent capabilities of Streamlit - to create instantaneously and constantly changing visuals. Bring in the mighty ‘placeholder.’
Placeholders in Streamlit figuratively allow you to reserve a spot at the table should you choose to use it later at a time of your choice or not at all. As per Streamlit’s own API, the placeholder:
Inserts a container into your app that can be used to hold a single element. This allows you to, for example, remove elements at any point, or replace several elements at once (using a child multi-element container).
Perhaps it was solely designed to enable you to retroactively insert an element or widget just once into your code post an event. Regardless, it gives us this unique vantage to be able to constantly feed a stream of anything into the placeholder, effectively rendering a dashboard that is updating in real time. Without further ado, let me show you how to create a radar chart that is updated continuously.
First thing’s first, lets go ahead and insert the stack of packages we’ll be using.
And incase you need to install any of the above packages, please proceed by using ‘pip install’ in Anaconda prompt.
pip install streamlit
Then we will create two placeholders, one for the radar chart itself and one for a start button that will trigger our script. You can name each placeholder as you wish by equating your instance name to ‘st.empty()’.
Subsequently, we will create the function for the radar chart using Plotly. Mind you, the input here to the radar chart is a list of randomly changing numbers, however it could literally be anything else. You could interface the list with a stream of data coming in through a serial COM port or via a remote web server.
Notice how in the gist above we are writing the completed figure to the ‘placeholder’ we created earlier.
Finally, we wrap it all up by creating two buttons to start and stop the dynamic radar chart (the start button using a placeholder as well). In addition we use a while loop to continuously re-run our radar chart function with a sleep function to delay each iteration by half a second.
And now you have it, our radar chart in a dynamically updated dashboard!
If you want to learn more about data visualization, Python, and deploying a Streamlit web application to the cloud then check out the following (affiliate linked) courses:
MoviePy – Rotating Video File

01 Aug, 2020
In this article we will see how we can rotate a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Rotation is the act or process of moving or turning around of a video to its central point. Rotation of 360 degree will be a complete turn around a central point. We can rotate the video with any angle.
In order to do this we will use rotate method with the VideoFileClip object
Syntax : clip.rotate(degree)
Argument : It takes integer as argument
Return : It returns VideoFileClip object
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm")  # getting subclip as video is largeclip = clip.subclip(55, 65)  # rotating clip by 45 degreeclip = clip.rotate(45)  # showing clipclip.ipython_display(width = 480)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")  # getting subclip clip = clip.subclip(0, 7)  # rotating clip by 180 degreeclip = clip.rotate(180)  # showing clipclip.ipython_display()
Output :
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
find_elements_by_css_selector() driver method – Selenium Python

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_css_selector() is discussed in this article. This method returns a list with type of elements specified.To grab a single first element, checkout – find_element_by_css_selector() driver method – Selenium Python
driver.find_elements_by_css_selector("css selector")

Example –For instance, consider this page source:
<html> <body>  <form id="loginForm">   <input name="1" type="text" />   <input name="1" type="password" />   <input name="1" 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_css_selector('#loginForm')

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 class name “gsc-input”.Create a file called run.py to demonstrate find_elements_by_css_selector 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_css_selector(".gsc-input")  # 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
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
Python OOPs Concepts
Iterate over a list in Python
How to Select DataFrame Columns by Index in R?

28 Nov, 2021
In this article, we will discuss how to select columns by index from a dataframe in R programming language.
Note: The indexing of the columns in the R programming language always starts from 1.
Here, we are going to select columns by using index with the base R in the dataframe.
Syntax:
dataframe[,c(column_indexes)]
Example:
R
#  create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c("akash","kyathi","preethi"),                subjects=c("java","R","dbms"),                marks=c(90,98,78))  # select second and third columnprint(data[,c(2,3)])
Output:
  subjects marks
1     java    90
2        R    98
3     dbms    78
We can select by using the index range operator, as shown below.
Syntax:
dataframe[,column_index_start:column_index_end]
where.
column_index_start is the first index number, and column_index_end is the second index number.
Example:
R
# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c("akash","kyathi","preethi"),                subjects=c("java","R","dbms"),                marks=c(90,98,78))  # select first to third columnprint(data[,1:3])
Output:
     name subjects marks
1   akash     java    90
2  kyathi        R    98
3 preethi     dbms    78
We can exclude the index columns by specifying in the c() vector with a – sign.
Syntax:
dataframe[,-c(column_indexes)]
Example:
R
# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c("akash","kyathi","preethi"),                subjects=c("java","R","dbms"),                marks=c(90,98,78))  # exclude second and third columnprint(data[,-c(2,3)])
Output:
[1] "akash"   "kyathi"  "preethi"
The select() function from the dplyr package is used for selecting column by index.
Syntax:
dataframe %>%
 select(column_numbers)
where
%>%  operator is to load into dataframe
Syntax to import and install the dpylr package:
install.packages("dplyr")
library("dplyr")
Example:
R
# loads the packagelibrary("dplyr")  # create a dataframe with 3 rows and 4 columnsdata = data.frame(name=c("akash", "kyathi", "preethi"),                  subjects=c("java", "R", "dbms"),                   marks=c(90, 98, 78))  # select 1  and 3 columnsdata % >%select(1, 3)
Output:
     name marks
1   akash    90
2  kyathi    98
3 preethi    78
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
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Shorthand Syntax for Object Property Value in ES6

20 May, 2020
Objects in JavaScript are the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript primitive data-types (Number, String, Boolean, null, undefined, and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types).
The shorthand syntax for object property value is very popular and widely used nowadays. The code looks cleaner and easy to read. The shorthand property makes the code size smaller and simpler.
Example: This example displaying the details of object using shorthand Syntax for object property value in ES6.
// Object property shorthandconst name = 'Raj'const age = 20const location = 'India'  // User with ES6 shorthand// property const user = {    name,          age,    location}  console.log(user) 
Output:
Example: This example displaying the details of the object without using shorthand Syntax for object property value.
// Object property shorthandconst name = 'Raj'const age = 20const location = 'India'  // User without ES6 // shorthand property const user = {    name: name,          age: age,    location: location}  console.log(user) 
Output:
ES6
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How do you run JavaScript script through the Terminal?
Hide or show elements in HTML using display property
Send unlimited Whatsapp messages using JavaScript
Set the value of an input field in JavaScript
Node.js | fs.writeFileSync() Method
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
HTML <legend> Tag

06 Jun, 2022
The legend tag is used to define the title for the child contents. The legend elements are the parent element. This tag is used to define the caption for the <fieldset> element.
Syntax
<legend> Text </legend>
Attribute : 
align: It sets the alignment of the legend element.
Example 1: 
html
<!DOCTYPE html><html>    <head>    </head>    <body>        <h1>GeeksforGeeks</h1>        <strong>HTML Legend Tag</strong>        <form>            <fieldset>                <!-- Legend tag using -->                <legend>STUDENT::</legend>                <label>Name:</label>                <input type="text">                <br><br>                <label>Email:</label>                <input type="text">                <br><br>                <label>Date of birth:</label>                <input type="text">                <br><br>                <label>Address:</label>                <input type="text">                <br><br>                <label>Enroll No:</label>                <input type="text">            </fieldset>        </form>    </body></html>
Output: 
Example 2: Styling the legend tag using CSS properties.  
html
<!DOCTYPE html><html>    <head>        <style>            form{            width: 50%;            }            legend {                display: block;                padding-left: 10px;                padding-right: 10px;                border: 3px solid green;                background-color:tomato;                color:white;;            }            label {                display: inline-block;                float: left;                clear: left;                width: 90px;                margin:5px;                text-align: left;            }            input[type="text"] {                width:250px;                margin:5px 0px;            }            .gfg {                font-size:40px;                color:green;                font-weight:bold;            }        </style>    </head>    <body>        <div class = "gfg">GeeksforGeeks</div>        <h2>HTML Legend Tag</h2>        <form>            <fieldset>                <!-- Legend tag using -->                <legend>STUDENT:</legend>                <label>Name:</label>                <input type="text">                <br>                <label>Email:</label>                <input type="text">                <br>                <label>Date of birth:</label>                <input type="text">                <br>                <label>Address:</label>                <input type="text">                <br>                <label>Enroll No:</label>                <input type="text">            </fieldset>        </form>    </body></html>
Output: 
Supported Browsers: 
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 6 and above
Firefox 1 and above
Opera 12.1 and above
Safari 3 and above
nidhi_biet
ghoshsuman0129
saurabh1990aror
chhabradhanvi
kumargaurav97520
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL query to count the number of times a specific integer appears in a column for its corresponding value in another column

For this, use aggregate function COUNT(). Let us first create a table −
mysql> create table DemoTable650 (Value1 int,Value2 int);
Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable650 values(200,500);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable650;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 100    |    500 |
| 100    |    500 |
| 100    |    500 |
| 100    |    500 |
| 200    |    500 |
+--------+--------+
5 rows in set (0.00 sec)
Following is the query to count the number of times a specific integer appears in a column for its corresponding value in another column −
mysql> select Value2,count(Value1) from DemoTable650 where Value1=100 group by Value2;
This will produce the following output −
+--------+---------------+
| Value2 | count(Value1) |
+--------+---------------+
| 500    |             4 |
+--------+---------------+
1 row in set (0.04 sec)
Dunder or magic methods in Python

14 Mar, 2018
Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.
The __init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP etc. These methods are the reason we can add two strings with ‘+’ operator without any explicit typecasting.
Here’s a simple implementation :
# declare our own string classclass String:          # magic method to initiate object    def __init__(self, string):        self.string = string          # Driver Codeif __name__ == '__main__':          # object creation    string1 = String('Hello')      # print object location    print(string1)
Output :
<__main__.String object at 0x7fe992215390>

 The above snippet of code prints only the memory address of the string object. Let’s add a __repr__ method to represent our object.
# declare our own string classclass String:          # magic method to initiate object    def __init__(self, string):        self.string = string              # print our string object    def __repr__(self):        return 'Object: {}'.format(self.string)  # Driver Codeif __name__ == '__main__':          # object creation    string1 = String('Hello')      # print object location    print(string1)
Output :
Object: Hello

 If we try to add a string to it :
# declare our own string classclass String:          # magic method to initiate object    def __init__(self, string):        self.string = string              # print our string object    def __repr__(self):        return 'Object: {}'.format(self.string)  # Driver Codeif __name__ == '__main__':          # object creation    string1 = String('Hello')          # concatenate String object and a string    print(string1 +' world')
Output :
TypeError: unsupported operand type(s) for +: 'String' and 'str'

 Now add __add__ method to String class :
# declare our own string classclass String:          # magic method to initiate object    def __init__(self, string):        self.string = string               # print our string object    def __repr__(self):        return 'Object: {}'.format(self.string)              def __add__(self, other):        return self.string + other  # Driver Codeif __name__ == '__main__':          # object creation    string1 = String('Hello')          # concatenate String object and a string    print(string1 +' Geeks')
Output :
Hello Geeks

 
Reference : docs.python.org.
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python
C Program to count number of lines in a file

11 Jul, 2022
C
/* C Program to count the Number of Lines in a Text File  */#include <stdio.h>#define MAX_FILE_NAME 100 int main(){    FILE *fp;    int count = 0;  // Line counter (result)    char filename[MAX_FILE_NAME];    char c;  // To store a character read from file     // Get file name from user. The file should be    // either in current folder or complete path should be provided    printf("Enter file name: ");    scanf("%s", filename);     // Open the file    fp = fopen(filename, "r");     // Check if file exists    if (fp == NULL)    {        printf("Could not open file %s", filename);        return 0;    }     // Extract characters from file and store in character c    for (c = getc(fp); c != EOF; c = getc(fp))        if (c == '\n') // Increment count if this character is newline            count = count + 1;     // Close the file    fclose(fp);    printf("The file %s has %d lines\n ", filename, count);     return 0;}
Output:
Enter file name: countLines.c
The file countLines.c has 41 lines
Time complexity: O(N) where N is total number of characters in given file
Please write comments if you find anything incorrect or want to share more information about the topic discussed above.
kumargaurav97520
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Attributes in PHP 8

Attributes are kinds of classes that can be used to add metadata to other classes, functions, class methods, class properties, constants, and parameters. Attributes do nothing during runtime.
Attributes have no impact on the code, but available for the reflection API. Attributes in PHP 8 allow other code to examine the class properties and methods.
We can have more than one attribute to a declaration.
We can have more than one attribute to a declaration.
It may resolve the class name.
It may resolve the class name.
Attributes can be namespaced.
Attributes can be namespaced.
It may have zero or more parameters
It may have zero or more parameters
In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration.
In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration.
We can declare multiple attributes inside #[ ], separated by a comma.
We can declare multiple attributes inside #[ ], separated by a comma.
Arguments are optional to use but need to be enclosed inside parenthesis ().
Arguments are optional to use but need to be enclosed inside parenthesis ().
Arguments can be literals values or constant expressions.
Arguments can be literals values or constant expressions.
Attribute: Syntax
#[attribute]
We can use an attribute to a class for instance.
#[Attribute]
Final class EmpClass{
}
Example: Attribute Function
#[Attr('param')]
function Exam(){}
Example: Attribute Classes
#[Attr('param')]
class Exam{}
Example: Attribute Class Properties
class Emp{
   #[Attribute('param')]
   public $name;
}
Example: Attribute Class Constants
Class Emp{
   #[Attribute('emp')]
   private const EMP = 'emp';
}
Example: Attribute Function
#[Attribute('emp')]
function exam(){}
Example: Attribute Method Arguments
Function emp(#[Attribute('param')]$name){
}
<?php
#[MyAttribute]
class Emp
{
   #[MyAttribute]
   public const EMP = 'emp';
   #[MyAttribute]
   public $a;
   #[MyAttribute]
   public function foo(#[MyAttribute] $dept){}
}

$object = new #[MyAttribute] class(){};
#[MyAttribute]
function f() {}

$f1 = #[MyAttribute] function(){};
$f2 = #[MyAttribute] fn() => 1;
print_r($f1);
?>
Closure Object ( )
GATE | GATE-CS-2007 | Question 10

19 Nov, 2018
Consider a 4-way set associative cache consisting of 128 lines with a line size of 64 words. The CPU generates a 20-bit address of a word in main memory. The number of bits in the TAG, LINE and WORD fields arerespectively:
(A) 9,6,5(B) 7, 7, 6(C) 7, 5, 8(D) 9, 5, 6Answer: (D)Explanation:
Here the number of sets = 128/4 = 32 (as it is 4 say set associative)

We have total 64 words then we need 6 bits to identify the word

So the line offset is 5 bits and the word offset is 6 bits

and the TAG = 20-(5+6) =9 bits

so it should be 9,5,6
Quiz of this Question
beherasarthak75
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Counting Sort

22 Jun, 2022
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 do some arithmetic to calculate the position of each object in the output sequence.  
Python3
# Python program for counting sort # The main function that sort the given string arr[] in# alphabetical orderdef countSort(arr):     # The output character array that will have sorted arr    output = [0 for i in range(256)]     # Create a count array to store count of individual    # characters and initialize count array as 0    count = [0 for i in range(256)]     # For storing the resulting answer since the    # string is immutable    ans = ["" for _ in arr]     # Store count of each character    for i in arr:        count[ord(i)] += 1     # Change count[i] so that count[i] now contains actual    # position of this character in output array    for i in range(256):        count[i] += count[i-1]     # Build the output character array    for i in range(len(arr)):        output[count[ord(arr[i])]-1] = arr[i]        count[ord(arr[i])] -= 1     # Copy the output array to arr, so that arr now    # contains sorted characters    for i in range(len(arr)):        ans[i] = output[i]    return ans # Driver program to test above functionarr = "geeksforgeeks"ans = countSort(arr)print ("Sorted character array is %s"  %("".join(ans))) # This code is contributed by Nikhil Kumar Singh
Output:  
Sorted character array is eeeefggkkorss
Time Complexity: O(n)
Space Complexity: O(n)
Please refer complete article on Counting Sort for more details! 
surindertarika1234
amartyaghoshgfg
harshmaster07705
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2011 | Question 65

28 Jun, 2021
Consider a relational table with a single record for each registered student with the following attributes.
1. Registration_Num: Unique registration number
   of each registered student
2. UID: Unique identity number, unique at the 
   national level for each citizen
3. BankAccount_Num: Unique account number at
   the bank. A student can have multiple accounts
   or join accounts. This attribute stores the 
   primary account number.
4. Name: Name of the student
5. Hostel_Room: Room number of the hostel 
Which one of the following option is INCORRECT?(A) BankAccount_Num is candidate key(B) Registration_Num can be a primary key(C) UID is candidate key if all students are from the same country(D) If S is a superkey such that S∩UID is NULL then S∪UID is also a superkeyAnswer: (A)Explanation: A Candidate Key value must uniquely identify the corresponding row in table. BankAccount_Number is not a candidate key. As per the question “A student can have multiple accounts or joint accounts. This attributes stores the primary account number”. If two students have a joint account and if the joint account is their primary account, then BankAccount_Number value cannot uniquely identify a row.Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split a comma delimited string into an array in PHP

31 Jul, 2021
Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array.
Examples:
Input : geeks,for,geeks
Output : Array ( [0] => geeks [1] => for [2] => geeks )

Input : practice, code
Output : Array ( [0] => practice [1] => code )

Use explode() or preg_split() function to split the string in php with given delimiter.
PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.Syntax:
array explode( separator, OriginalString, NoOfElements )
PHP | preg_split() Function: The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
Syntax:
array preg_split( string $pattern, string 
$subject [, int $limit = -1 [, int $flags = 0 ]] )
Example:
<?php  // Use preg_split() function$string = "123,456,78,000"; $str_arr = preg_split ("/\,/", $string); print_r($str_arr);      // use of explode$string = "123,46,78,000";$str_arr = explode (",", $string); print_r($str_arr);?>
Array
(
    [0] => 123
    [1] => 456
    [2] => 78
    [3] => 000
)
Array
(
    [0] => 123
    [1] => 46
    [2] => 78
    [3] => 000
)

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Randomly select n elements from list in Python

21 Aug, 2020
In this article, we will discuss how to randomly select n elements from the list in Python. Before moving on to the approaches let’s discuss Random Module which we are going to use in our approaches.Random Module:Random module is the predefined Module in Python, It contains methods to return random values. This module is useful when we want to generate random values. Some of the methods of Random module are:-seed(), getstate(), choice(), sample() etc.
Let’s discuss different approaches to implement this.Approach 1 : Using sample() Method. sample() method is used to return required list of items from a given sequence. This method do not allow duplicate elements in a sequence.
# importing random moduleimport random  # declaring listlist = [2, 2, 4, 6, 6, 8]  # initializing the value of nn = 4  # printing n elements from listprint(random.sample(list, n))
Output :
[8, 6, 6, 4]

Approach 2 : Using choice() Method. choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list).
# importing random moduleimport random  # declaring listlist = [2, 2, 4, 6, 6, 8]  # initializing the value of nn = 4  # traversing and printing random elementsfor i in range(n):          # end = " " so that we get output in single line    print(random.choice(list), end = " ")
Output :
8 2 4 6 

Python list-programs
python-list
Python-random
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
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 - Pandas dataframe.append()
Python | datetime.timedelta() function
How to Install Scrapy on MacOS?

22 Sep, 2021
In this article, we will learn how to install Scrapy in Python on MacOS. 
Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.
Follow the below steps to install the SCrapy package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Scrapy using pip3.
pip3 install Scrapy
Follow the below steps to install the Scrapy package on macOS using the setup.py file:
Step 1: Download the latest source package of Scrapy for python3 from here.
curl https://files.pythonhosted.org/packages/e9/dc/b2f41d802f548fba35c2d7c443ab0ab3df358eebd261f4d30d19ad39658a/Scrapy-2.5.0.tar.gz > scrapy.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf scrapy.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd Scrapy-2.5.0
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import scrapy
If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to print Python dictionary into JSON format?

JSON stands for Javascript Standard Object Notation. Python module called json is a JSON encoder/decoder. The dumps() function in this module returns a JSON string representation of Python dictionary object.
D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> import json
>>> j=json.dumps(D1)
>>> j
'{"pen": 25, "pencil": 10, "book": 100, "sharpner": 5, "eraser": 5}'
strpbrk() in C

The function strpbrk() is used to find the first character of first string and matches it to any character of second string. It returns NULL, if no matches are found otherwise, it returns a pointer to the character of first string that matches to the character of second string.
Here is the syntax of strpbrk() in C language,
char *strpbrk(const char *string1, const char *string2)
Here is an example of strpbrk() in C language,
 Live Demo
#include <stdio.h>
#include <string.h>
int main () {
   const char s1[] = "Helloworld";
   const char s2[] = "Blank";
   char *result;
   result = strpbrk(s1, s2);
   printf("The matching character : %c\n", *result);
   return(0);
}
The matching character : l
Ruby | Regexp match() function

18 Dec, 2019
Regexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search.
Syntax: Regexp.match()
Parameter: Regexp values
Return: regular expression with the string after matching it.
Example #1 :
# Ruby code for Regexp.match() method  # declaring Regexp valuereg_a = /a/  # declaring Regexp valuereg_b = /geeks/  # declaring Regexp valuereg_c = /a/    #  match methodputs "Regexp match form : #{reg_a.match("abcd")}\n\n"  puts "Regexp match form : #{reg_b.match("geeksforgeeks")}\n\n"  puts "Regexp match form : #{reg_c.match("playway")}\n\n"
Output :
Regexp match form : a

Regexp match form : geeks

Regexp match form : a


Example #2 :
# Ruby code for Regexp.match() method  # declaring Regexp valuereg_a = /geeks/  # declaring Regexp valuereg_b = /problem/  # declaring Regexp valuereg_c = /code/    #  match methodputs "Regexp match form : #{reg_a.match("geeksforgeeks")}\n\n"  puts "Regexp match form : #{reg_b.match("geeksforgeeks")}\n\n"  puts "Regexp match form : #{reg_c.match("codeer")}\n\n"
Output :
Regexp match form : geeks

Regexp match form : 

Regexp match form : code


Ruby Regexp-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.