code-rag-bench/online-tutorials huggingface dataset:
itertools.groupby() in Python

30 Jan, 2020
Prerequisites: Python Itertools
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.
Syntax: itertools.groupby(iterable, key_func)
Parameters:iterable: Iterable can be of any kind (list, tuple, dictionary).key: A function that calculates keys for each element present in iterable.
Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged.
Example 1:
# Python code to demonstrate # itertools.groupby() method     import itertools    L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]  # Key functionkey_func = lambda x: x[0]  for key, group in itertools.groupby(L, key_func):    print(key + " :", list(group))
Output:
a : [('a', 1), ('a', 2)]
b : [('b', 3), ('b', 4)]

Example 2 :
# Python code to demonstrate # itertools.groupby() method     import itertools    a_list = [("Animal", "cat"),           ("Animal", "dog"),           ("Bird", "peacock"),           ("Bird", "pigeon")]    an_iterator = itertools.groupby(a_list, lambda x : x[0])  for key, group in an_iterator:    key_and_group = {key : list(group)}    print(key_and_group)
Output
{'Animal': [('Animal', 'cat'), ('Animal', 'dog')]}
{'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}

Python-itertools
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
frozenset() in Python

12 Aug, 2021
The frozenset() is an inbuilt function in Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable.
In Python, frozenset is the same as set except the frozensets are immutable which means that elements from the frozenset cannot be added or removed once created. This function takes input as any iterable object and converts them into an immutable object. The order of elements is not guaranteed to be preserved.
Syntax : frozenset(iterable_object_name)Parameter : This function accepts iterable object as input parameter.Return Type: This function return an equivalent frozenset object.
Below examples explains it clearly.
Example #1: If no parameters are passed to frozenset() function then it returns a empty frozenset type object.  
Python3
# Python program to understand frozenset() function # tuple of numbersnu = (1, 2, 3, 4, 5, 6, 7, 8, 9) # converting tuple to frozensetfnum = frozenset(nu) # printing detailsprint("frozenset Object is : ", fnum)
frozenset Object is :  frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
 
 Example #2: Uses of frozenset().Since frozenset object are immutable they are mainly used as key in dictionary or elements of other sets. Below example explains it clearly. 
Python3
# Python program to understand use# of frozenset function # creating a dictionaryStudent = {"name": "Ankit", "age": 21, "sex": "Male",           "college": "MNNIT Allahabad", "address": "Allahabad"} # making keys of dictionary as frozensetkey = frozenset(Student) # printing keys detailsprint('The frozen set is:', key)
The frozen set is: frozenset({'sex', 'age', 'address', 'name', 'college'})
 
Example #3: WarningIf by mistake we want to change the frozenset object then it throws an error “‘frozenset’ object does not support item assignment“. 
Python3
# Python program to understand# use of frozenset function # creating a listfavourite_subject = ["OS", "DBMS", "Algo"] # making it frozenset typef_subject = frozenset(favourite_subject) # below line will generate error f_subject[1] = "Networking"
Output: 
Traceback (most recent call last):
  File "/home/0fbd773df8aa631590ed0f3f865c1437.py", line 12, in 
    f_subject[1] = "Networking"
TypeError: 'frozenset' object does not support item assignment
 
786meimran
122006025
Python-Functions
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
PyQt5 – How to access content of label ?

26 Mar, 2020
We can create label using QLabel() method, and set the content using setText() method. In this article, we will see how to access the content of the label, in order to do this we will use text() method.
Syntax : label.text()
Argument : It takes no argument.
Return : It returns a string.
Code :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # creating a label widget        self.label_1 = QLabel("old label ", self)          # setting up the border and background color        self.label_1.setStyleSheet("border :3px solid black;                                     background : pink")          # getting the content of label        content = self.label_1.text()                  # printing the content of label        print(content)          # moving the label        self.label_1.move(10, 100)          # creating a new label widget        self.label_2 = QLabel("new Label ", self)          # setting up the border and background color        self.label_2.setStyleSheet("border :3px solid black;                                     background : green")          # moving the label        self.label_2.move(110, 110)                  # printing the content of label        print(self.label_2.text())          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
old label 
new Label 

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

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment.
The keyword AUTOINCREMENT can be used with INTEGER field only.
The basic usage of AUTOINCREMENT keyword is as follows −
CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);
Consider COMPANY table to be created as follows −
sqlite> CREATE TABLE COMPANY(
   ID INTEGER PRIMARY KEY AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);
Now, insert the following records into table COMPANY −
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Paul', 32, 'California', 20000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Allen', 25, 'Texas', 15000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Teddy', 23, 'Norway', 20000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'David', 27, 'Texas', 85000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Kim', 22, 'South-Hall', 45000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'James', 24, 'Houston', 10000.00 );

This will insert 7 tuples into the table COMPANY and COMPANY will have the following records −
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
How to get the standard deviation of an array of numbers using JavaScript ?

15 Jul, 2021
Given an array and the task is to calculate the standard deviation of it.
Example:
Input:  [1, 2, 3, 4, 5]
Output: 1.4142135623730951

Input:  [23, 4, 6, 457, 65, 7, 45, 8]
Output: 145.13565852332775
Please refer to Mean, Variance, and Standard Deviation for details.
Mean is average of element. Where 0 <= i < n
Mean of arr[0..n-1] = ∑(arr[i]) / n
Variance is the sum of squared differences from the mean divided by a number of elements.
Variance = ∑(arr[i] – mean)2 / n
Standard Deviation is the square root of the variance.
Standard Deviation = variance ^ 1/2
Approach: To calculate the standard deviation first we calculate the mean and then variance and then deviation. To calculate the mean we use Array.reduce() method and calculate the sum of all the array items and then divide the array with the length of the array.
To calculate the variance we use the map() method and mutate the array by assigning (value – mean) ^ 2 to every array item, and then we calculate the sum of the array, and then we divide the sum with the length of the array. To calculate the standard deviation we calculate the square root of the array.
Example:
Javascript
<script>// Javascript program to calculate the standered deviation of an arrayfunction dev(arr){  // Creating the mean with Array.reduce  let mean = arr.reduce((acc, curr)=>{    return acc + curr  }, 0) / arr.length;     // Assigning (value - mean) ^ 2 to every array item  arr = arr.map((k)=>{    return (k - mean) ** 2  })     // Calculating the sum of updated array let sum = arr.reduce((acc, curr)=> acc + curr, 0);   // Calculating the variance let variance = sum / arr.length   // Returning the Standered deviation return Math.sqrt(sum / arr.length)}  console.log(dev([1, 2, 3, 4, 5]))console.log(dev([23, 4, 6, 457, 65, 7, 45, 8]))</script>
Output:
1.4142135623730951
145.13565852332775
singghakshay
javascript-array
javascript-math
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
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 ?
How does a vector work in C++?

08 Oct, 2021
A Vectors in C++ can resize itself when more elements are added. It also allows deletion of elements. Below is a very basic idea when array becomes full and user wishes to add an item. 1) Create a bigger sized memory on heap memory (for example memory of double size). 2) Copy current memory elements to the new memory. 3) New item is added now as there is bigger memory available now. 4) Delete the old memory.However the actual library implementation may be more complex. If we create a new double sized array whenever current array becomes full (or it is about to become full), and copy current elements to new double sized array, we get amortized time complexity as O(1). So a particular insert operation may be costly, but overall time complexity remains O(1). Please refer Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) for proof. So time complexity of push_back() is O(1). 
CPP
// CPP program to illustrate push_back()#include <iostream>#include <vector>using namespace std;  int main(){    vector<int> myvector{ 1, 2, 3, 4, 5 };     myvector.push_back(6);      // Vector becomes 1, 2, 3, 4, 5, 6      for (auto x : myvector)        cout << x << " ";}
Output : 
1 2 3 4 5 6 
What is the time complexity of erase() in vector()? Since erasing an element requires moving other elements (to ensure random access), time complexity of erase is O(n). 
CPP
// CPP program to illustrate// working of erase() function#include <iostream>#include <vector>using namespace std; int main(){    vector<int> myvector{ 1, 2, 3, 4, 5 };     auto it = myvector.begin();    myvector.erase(it);     // Printing the Vector    for (auto x : myvector)        cout << x << " ";    return 0;}
Output : 
2 3 4 5 
 
atharvautekar99
cpp-vector
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Turtle programming in Python

Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing board.
First we import the turtle module. Then create a window, next we create turtle object and using turtle method we can draw in the drawing board.
# import turtle library
import turtle             
my_window = turtle.Screen() 
my_window.bgcolor("blue")       # creates a graphics window
my_pen = turtle.Turtle()      
my_pen.forward(150)           
my_pen.left(90)               
my_pen.forward(75)
my_pen.color("white")
my_pen.pensize(12)
# import turtle library
import turtle             
my_pen = turtle.Turtle()      
for i in range(4):
   my_pen.forward(50)           
   my_pen.right(90)               
turtle.done()
# import turtle library
import turtle             
my_pen = turtle.Turtle()      
for i in range(50):
   my_pen.forward(50)           
   my_pen.right(144)               
turtle.done()
# import turtle library
import turtle             
polygon = turtle.Turtle()
my_num_sides = 6
my_side_length = 70
my_angle = 360.0 / my_num_sides
for i in range(my_num_sides):
   polygon.forward(my_side_length)           
   polygon.right(my_angle) 
turtle.done()
# import turtle library
import turtle             
my_wn = turtle.Screen()
my_wn.bgcolor("light blue")
my_wn.title("Turtle")
my_pen = turtle.Turtle()
my_pen.color("black")
def my_sqrfunc(size):
   for i in range(4):
      my_pen.fd(size)
      my_pen.left(90)
      size = size - 5
my_sqrfunc(146)
my_sqrfunc(126)
my_sqrfunc(106)
my_sqrfunc(86)
my_sqrfunc(66)
my_sqrfunc(46)
my_sqrfunc(26)
# import turtle library
import turtle             
my_wn = turtle.Screen()
turtle.speed(2)
for i in range(30):
   turtle.circle(5*i)
   turtle.circle(-5*i)
   turtle.left(i)
turtle.exitonclick()
# import turtle library
import turtle             
colors = [ "red","purple","blue","green","orange","yellow"]
my_pen = turtle.Pen()
turtle.bgcolor("black")
for x in range(360):
   my_pen.pencolor(colors[x % 6])
   my_pen.width(x/100 + 1)
   my_pen.forward(x)
   my_pen.left(59)
Pivot and Unpivot in SQL

24 Jul, 2019
In SQL, Pivot and Unpivot are relational operators that are used to transform one table into another in order to achieve more simpler view of table. Conventionally we can say that Pivot operator converts the rows data of the table into the column data. The Unpivot operator does the opposite that is it transform the column based data into rows.
Syntax:
1. Pivot:
SELECT (ColumnNames) 
FROM (TableName) 
PIVOT
 ( 
   AggregateFunction(ColumnToBeAggregated)
   FOR PivotColumn IN (PivotColumnValues)
 ) AS (Alias) //Alias is a temporary name for a table

2. Unpivot:
SELECT (ColumnNames) 
FROM (TableName) 
UNPIVOT
 ( 
   AggregateFunction(ColumnToBeAggregated)
   FOR PivotColumn IN (PivotColumnValues)
 ) AS (Alias)

Example-1:We have created a simple table named “geeksforgeeks” with values like Course name, course category and price and inserted the respective values.
Create Table geeksforgeeks 
( 
CourseName nvarchar(50), 
CourseCategory nvarchar(50),
Price int  
) 

Insert into geeksforgeeks  values('C', 'PROGRAMMING', 5000) 
Insert into geeksforgeeks  values('JAVA', 'PROGRAMMING', 6000) 
Insert into geeksforgeeks  values('PYTHON', 'PROGRAMMING', 8000) 
Insert into geeksforgeeks  values('PLACEMENT 100', 'INTERVIEWPREPARATION', 5000) 

SELECT * FROM geeksforgeeks 
The output we get is :
Now, applying PIVOT operator to this data:
SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION
FROM geeksforgeeks 
PIVOT 
( 
SUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION ) 
) AS PivotTable 

After using Pivot operator we get the following result:
Example-2:Now, we use the same table “geeksforgeeks” created in the above example and apply the Unpivot operator to our Pivoted table.
Applying UNPIVOT operator:
SELECT CourseName, CourseCategory, Price 
FROM 
(
SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION FROM geeksforgeeks 
PIVOT 
( 
SUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION) 
) AS PivotTable
) P 
UNPIVOT 
( 
Price FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION)
) 
AS UnpivotTable

After using Unpivot operator we get our original table back as we have successfully transformed the columns of the table back to rows:
Picked
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
SQL | GROUP BY
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
MySQL | Group_CONCAT() Function
SAS - Frequency Distributions

A frequency distribution is a table showing the frequency of the data points in a data set. Each entry in the table contains the frequency or count of the occurrences of values within a particular group or interval, and in this way, the table summarizes the distribution of values in the sample.
SAS provides a procedure called PROC FREQ to calculate the frequency distribution of data points in a data set.
The basic syntax for calculating frequency distribution in SAS is −
PROC FREQ DATA = Dataset ;
TABLES Variable_1 ;
BY Variable_2 ;

Following is the description of the parameters used −
Dataset is the name of the dataset.
Dataset is the name of the dataset.
Variables_1 is the variable names of the dataset whose frequency distribution needs to be calculated.
Variables_1 is the variable names of the dataset whose frequency distribution needs to be calculated.
Variables_2 is the variables which categorised the frequency distribution result.
Variables_2 is the variables which categorised the frequency distribution result.
We can determine the frequency distribution of a single variable by using PROC FREQ. In this case the result will show the frequency of each value of the variable. The result also shows the percentage distribution, cumulative frequency and cumulative percentage.
In the below example we find the frequency distribution of the variable horsepower for the dataset named CARS1 which is created form the library SASHELP.CARS. We can see the result divided into two categories of results. One for each make of the car.
PROC SQL;
create table CARS1 as
SELECT make, model, type, invoice, horsepower, length, weight
   FROM 
   SASHELP.CARS
   WHERE make in ('Audi','BMW')
;
RUN;

proc FREQ data = CARS1 ;
tables horsepower; 
by make;
run;

When the above code is executed, we get the following result −
We can find the frequency distributions for multiple variables which groups them into all possible combinations.
In the below example we calculate the frequency distribution for the make of a car for grouped by car type and also the frequency distribution of each type of car grouped by each make.
proc FREQ data = CARS1 ;
tables make type; 
run;

When the above code is executed, we get the following result −
With the weight option we can calculate the frequency distribution biased with the weight of the variable. Here the value of the variable is taken as the number of observations instead of the count of value.
In the below  example we calculate the frequency distribution of the variables make and type with weight assigned to horsepower.
proc FREQ data = CARS1 ;
tables make type; 
weight horsepower;
run;

When the above code is executed, we get the following result −
How to count rows in MySQL table in PHP ?

26 May, 2021
PHP stands for hypertext preprocessor. MySQL is a database query language used to manage databases.
In this article, we are going to discuss how to get the count of rows in a particular table present in the database using PHP and MySQL.
Requirements:
XAMPP
Approach: By using PHP and MySQL, one can perform database operations. We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function.
Syntax:
mysqli_num_rows( result );
The result is to specify the result set identifier returned by mysqli_query() function.
Example: The following table has 5 rows.
To count the number of rows in the building table, the following code snippet is used.
$sql = "SELECT * from building";

if ($result = mysqli_query($con, $sql)) {

    // Return the number of rows in result set
    $rowcount = mysqli_num_rows( $result );
    
    // Display result
    printf("Total rows in this table :  %d\n", $rowcount);
 }
Output: The expected result is as follows.
Total rows in this table : 5
Steps for the approach:
Create a database named database.
Create a table named building inside the database.
Insert records into it.
Write PHP code to count rows.
 
Steps:
Start XAMPP server.
XAMPP server
Create a database named database and create a table named building inside the database.
Insert records into it
building table
Write PHP code to count rows.
PHP code:
PHP
<?php  // localhost is localhost// servername is root// password is empty// database name is database$con = mysqli_connect("localhost","root","","database");      // SQL query to display row count    // in building table    $sql = "SELECT * from building";      if ($result = mysqli_query($con, $sql)) {      // Return the number of rows in result set    $rowcount = mysqli_num_rows( $result );          // Display result    printf("Total rows in this table : %d\n", $rowcount);}  // Close the connectionmysqli_close($con);  ?>
Output: After running the above PHP file in localhost, the following result is achieved.
Total rows in this table : 5
Example 2: In the following example, we count the table rows using MySQL count() function. It’s an aggregate function used to count rows.
Syntax:
select count(*) from table;
Consider the table.
PHP code:
PHP
<?php  // Servername$servername = "localhost";  // Username$username = "root";  // Empty password$password = "";  // Database name $dbname = "database";   // Create connection by passing these// connection parameters$conn = new mysqli($servername,     $username, $password, $dbname);   // SQL query to find total count// of college_data table$sql = "SELECT count(*) FROM college_data ";$result = $conn->query($sql);  // Display data on web pagewhile($row = mysqli_fetch_array($result)) {    echo "Total Rows is ". $row['count(*)'];    echo "<br />";}   // Close the connection$conn->close();  ?>
Output:
Total Rows is 8
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python os.removedirs() Method

Python method removedirs() removes dirs recursively. If the leaf directory is succesfully removed, removedirs tries to successively remove every parent directory displayed in path.
Following is the syntax for removedirs() method −
os.removedirs(path)

path − This is the path of the directory, which needs to be removed.
path − This is the path of the directory, which needs to be removed.
This method does not return any value.
The following example shows the usage of removedirs() method.
# !/usr/bin/python

import os, sys

# listing directories
print "The dir is: %s" %os.listdir(os.getcwd())

# removing
os.removedirs("/tutorialsdir")

# listing directories after removing directory
print "The dir after removal is:" %os.listdir(os.getcwd())
When we run above program, it produces following result −
The dir is:
[  'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal is:
[  'a1.txt','resume.doc','a3.py','amrood.admin' ]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to input multiple values from user in one line in C#?

Use a while loop to input multiple values from the user in one line.
Let’s say you need to get the elements of a matrix. Get it using Console.ReadLine() as shown below −
Console.Write("\nEnter elements - Matrix 1 : ");
for (i = 0; i < m; i++) {
   for (j = 0; j < n; j++) {
      arr1[i, j] = Convert.ToInt16(Console.ReadLine());
   }
}
The following is an example showing how we can input multiple values from user −
 Live Demo
using System;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[,] arr1 = new int[10, 10];
         int i, j;

         Console.Write("\nEnter Matrix elements: ");
         for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
               arr1[i, j] = Convert.ToInt16(Console.ReadLine());
            }
         }

      }
   }
}
Enter Matrix elements:
Dart Programming - If Else Statement

An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false.
Following is the syntax.
if(boolean_expression){ 
   // statement(s) will execute if the Boolean expression is true. 
} else { 
   // statement(s) will execute if the Boolean expression is false. 
} 

If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed.
The following illustration shows the flowchart of the if...else statement.
The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.
The following example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same.
void main() { 
   var num = 12; 
   if (num % 2==0) { 
      print("Even"); 
   } else { 
      print("Odd"); 
   } 
}
The following output is displayed on successful execution of the above code.
Even


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Format TimeSpan in C#

You can format a TimeSpan in the hh: mm: ss format in C#.
Firstly, set the TimeSpan −
TimeSpan ts = new TimeSpan(9, 15, 30);
To format TimeSpan −
{0:hh\\:mm\\:ss}
The following is the code −
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      TimeSpan ts = new TimeSpan(9, 15, 30);
      Console.WriteLine("{0:hh\\:mm\\:ss}", ts);
   }
}
09:15:30
Check if three consecutive elements in an array is identical in JavaScript

We are required to write a JavaScript function, say checkThree() that takes in an array and
returns true if anywhere in the array there exists three consecutive elements that are identical
(i.e., have the same value) otherwise it returns false.
Therefore, let’s write the code for this function −
const arr = ["g", "z", "z", "v" ,"b", "b", "b"];
const checkThree = arr => {
   const prev = {
      element: null,
      count: 0
   };
   for(let i = 0; i < arr.length; i++){
      const { count, element } = prev;
      if(count === 2 && element === arr[i]){
         return true;
      };
      prev.count = element === arr[i] ? count + 1 : count;
      prev.element = arr[i];
   };
   return false;
};
console.log(checkThree(arr));
console.log(checkThree(["z", "g", "z", "z"]));
The output in the console will be −
true
false
Sign Magnitude notation

The sign-magnitude binary format is the simplest conceptual format. In this method of representing signed numbers, the most significant digit (MSD) takes on extra meaning.
If the MSD is a 0, we can evaluate the number just as we would any normal unsigned integer. And also we shall treat the number as a positive one.
If the MSD is a 0, we can evaluate the number just as we would any normal unsigned integer. And also we shall treat the number as a positive one.
If the MSD is a 1, this indicates that the number is negative.
The other bits indicate the magnitude (absolute value) of the number. Some of the signed decimal numbers and their equivalent in SM notation follows assuming a word size of 4 bits.
From the above table, it is obvious that if the word size is n bits, the range of numbers that can be represented is from -(2n-1 -1) to +(2n-1 -1). A table of word size and the range of SM numbers that can be represented as shown in the following.
Notice that the bit sequence 1101corresponds to the unsigned number 13, as well as the number –5 in SM notation. Its value depends only on the way the user or the programmer interprets the bit sequence.
A number is represented inside a computer with the purpose of performing some calculations using that number. The most basic arithmetic operation in a computer is the addition operation. That’s why a computer can also be called as an adder.
When adding two numbers with the same signs, add the values and keep the common sign. 
Add the numbers (+5) and (+3) using a computer. The numbers are assumed to be represented using 4-bit SM notation.
             111  <- carry generated during addition
             0101 <- (+5) First Number
           + 0011 <- (+3) Second Number
             1000 <- (+8) Sum                 
             111  <- carry generated during addition
             0101 <- (+5) First Number
           + 0011 <- (+3) Second Number
             1000 <- (+8) Sum                 
Let’s take another example of two numbers with unlike signs.
Add the numbers (-4) and (+2) using a computer. The numbers are assumed to be represented using 4-bit SM notation.
              000 <- carry generated during addition              1100 <- (-4) First number           +  0010 <-(+2) Second Number              1110 <- (-2) Sum
              000 <- carry generated during addition
              1100 <- (-4) First number
           +  0010 <-(+2) Second Number
              1110 <- (-2) Sum
Here, the computer has given the wrong answer of -6 = 1110, instead of giving the correct answer of -2 = 1010.
There are two notations for 0(0000 and 1000), which is very inconvenient when the computer wants to test for a 0 result.
There are two notations for 0(0000 and 1000), which is very inconvenient when the computer wants to test for a 0 result.
It is not convenient for the computer to perform arithmetic.
It is not convenient for the computer to perform arithmetic.
Hence, due to the above mention ambiguities, SM notation is generally not used to represent signed numbers inside a computer.
HTML script Tag - GeeksforGeeks

17 Mar, 2022
The <script> tag in HTML is used to define the client-side script. The <script> tag contains the scripting statements, or it points to an external script file. The JavaScript is mainly used in form validation, dynamic changes of content, image manipulation, etc.Syntax:  
<script> Script Contents... </script>
Attributes: Many attribute associated with script tag.  
async: It is used to specify the script is executed asynchronously.
charset: It is used to specify the character encoding used in an external script file.
defer: It is used to specify that the script is executed when the page has finished parsing.
src: It is used to specify the URL of an external script file.
type: It is used to specify the media type of the script.
Example 1:  
HTML
<!DOCTYPE html><html>         <body>             <h1>GeeksforGeeks</h1>            <h2><script> Tag</h2>            <p id="Geeks"></p>             <!-- html script tag starts here -->            <script>                document.getElementById("Geeks").innerHTML =                                     "Hello GeeksforGeeks!";            </script>               <!-- html script tag ends here -->         </body> </html>                   
Output:  
Example 2(script outside body tag): 
HTML
<!DOCTYPE html><html>    <head>        <title>script tag</title>        <style>            body {                text-align:center;            }            h1 {                color:green;            }        </style>        <script>            function Geeks() {                alert('Welcome to GeeksforGeeks!');            }        </script>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2><script> Tag</h2>        <button type="button" onclick="Geeks()">            Hello GeeksforGeeks</button>    </body></html>                   
Output:  
Supported Browsers:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubham_singh
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
UNIX_TIMESTAMP() function in MySQL - GeeksforGeeks

22 Dec, 2020
UNIX_TIMESTAMP() :This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since ‘1970-01-01 00:00:00’UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that.
Syntax :
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
Parameters :It will accept only one argument.
date –A date value which can be DATE, DATETIME, TIMESTAMP, or a number in ‘YYYYMMDD’ or ‘YYMMDD’ format.
Return :
If no parameter is passed, the function will return a Unix timestamp in seconds since ‘1970-01-01 00:00:00’ UTC in form of an unsigned integer.
But if the date parameter is passed, the function will return the value of parameter in form of an unsigned integer in seconds since ‘1970-01-01 00:00:00’ UTC.
Example-1 :Working of UNIX_TIMESTAMP() using Current date/time.
SELECT UNIX_TIMESTAMP() 
As TimeStamp; 
Output :
Example-2 :Working of UNIX_TIMESTAMP() using date value ‘1999-01-22’.
SELECT UNIX_TIMESTAMP('1999-01-22') 
As TimeStamp; 
Output :
Example-3 :Working of UNIX_TIMESTAMP() using DateTime value ‘2020-10-17 02:35:43’.
SELECT UNIX_TIMESTAMP('2020-10-17 02:35:43') 
As TimeStamp; 
Output :
Example-4 :Working of UNIX_TIMESTAMP() using DateTime value along with fractional seconds ‘2020-10-17 02:35:43.12345’.
SELECT UNIX_TIMESTAMP('2020-10-17 02:35:43.12345') 
As TimeStamp; 
Output :
DBMS-SQL
mysql
Technical Scripter 2020
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
What is Temporary Table in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
Python - Remove records if Key not present - GeeksforGeeks

21 Feb, 2022
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the dictionaries in which a particular key is not present. This kind of problem can have applications in many domains such as day-day programming and data domain. Let’s discuss certain ways in which this task can be performed. 
Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}] , K = ‘Best’ Output : [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}]Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}], K = ‘good’ Output : []  
Method #1: Using list comprehension This is one of the ways in which this task can be performed. In this, we iterate and test for key presence using list comprehension and conditional statements. 
Python3
# Python3 code to demonstrate working of# Remove records if Key not present# Using list comprehension # initializing listtest_list = [{'Gfg' : 1, 'Best' : 3},             {'Gfg' : 3, 'Best' : 5},             {'Best' : 3}] # printing original listprint("The original list : " + str(test_list)) # initializing K KeyK = 'Gfg' # Remove records if Key not present# Using list comprehensionres = [ele for ele in test_list if K in ele]         # printing resultprint("List after filtration : " + str(res))
The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]
 
 Method #2 : Using list comprehension + keys() The combination of the above functions can be used to solve this problem. In this, we perform the task of extraction of all the keys using keys(), reduces the overhead of checking in items. 
Python3
# Python3 code to demonstrate working of# Remove records if Key not present# Using list comprehension + keys() # initializing listtest_list = [{'Gfg' : 1, 'Best' : 3},             {'Gfg' : 3, 'Best' : 5},             {'Best' : 3}] # printing original listprint("The original list : " + str(test_list)) # initializing K KeyK = 'Gfg' # Remove records if Key not present# Using list comprehension + keys()res = [ele for ele in test_list if K in ele.keys()]         # printing resultprint("List after filtration : " + str(res))
The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]
 
adnanirshad158
reenadevi98412200
Python List-of-Dict
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
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?
Python | Pandas Dataframe.sample() - GeeksforGeeks

24 Apr, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas sample() is used to generate a sample random row or column from the function caller data frame.
Syntax:
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Parameters:
n: int value, Number of random rows to generate.frac: Float value, Returns (float value * length of data frame values ). frac cannot be used with n.replace: Boolean value, return sample with replacement if True.random_state: int value or numpy.random.RandomState, optional. if set to a particular integer, will return same rows as sample in every iteration.axis: 0 or ‘row’ for Rows and 1 or ‘column’ for Columns.
Return type: New object of same type as caller.
To download the CSV file used, Click Here.
Example #1: Random row from Data frame
In this example, two random rows are generated by the .sample() method and compared later.
# importing pandas packageimport pandas as pd  # making data frame from csv file data = pd.read_csv("employees.csv")  # generating one row row1 = data.sample(n = 1)  # displayrow1  # generating another rowrow2 = data.sample(n = 1)  # displayrow2
Output:As shown in the output image, the two random sample rows generated are different from each other.
 Example #2: Generating 25% sample of data frameIn this example, 25% random sample data is generated out of the Data frame.
# importing pandas packageimport pandas as pd  # making data frame from csv file data = pd.read_csv("employees.csv")  # generating one row rows = data.sample(frac =.25)  # checking if sample is 0.25 times data or not  if (0.25*(len(data))== len(rows)):    print( "Cool")    print(len(data), len(rows))  # displayrows
Output:As shown in the output image, the length of sample generated is 25% of data frame. Also the sample is generated randomly.
pacificlion
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Java String charAt() method with example - GeeksforGeeks

04 Dec, 2018
The Java String charAt() method returns the character at the specified index. The index value should lie between 0 and length()-1.Signature:
 public char charAt(int index)  

Parameter:
 index- Index of the character to be returned.

Return:
 returns character at the specified position.

Exception:
 StringIndexOutOfBoundsException- If index is 
 negative or greater then the length of the 
 String.

Example:To show working of charAt() method
// Java program to demonstrate// working of charAt() method  class Gfg {    public static void main(String args[])    {        String s = "Welcome! to Geeksforgeeks Planet";          char ch = s.charAt(3);        System.out.println(ch);          ch = s.charAt(0);        System.out.println(ch);    }}
c
W

// Java program to demonstrate// working of charAt() method  class Gfg {    public static void main(String args[])    {        String s = "abc";          char ch = s.charAt(4);        System.out.println(ch);    }}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.charAt(String.java:658)
    at Gfg.main(File.java:9)


String Class in Java
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
Prime or not in Python

Prime numbers play a central role in many e it applications like cryptography. So it is a necessity to check for prime numbers using Python programs in various applications. A prime number is a number which doesn't have any factors other than one and itself. Below will see programs that can find out if a given number is prime or not.
We take the following approach to decide whether a number is prime or not.
Check at the beginning is positive or not. As only positive numbers can be prime numbers.
Check at the beginning is positive or not. As only positive numbers can be prime numbers.
We divide the number with all the numbers in the range of 2 to one number less than given number.
We divide the number with all the numbers in the range of 2 to one number less than given number.
If the remainder becomes zero for any number in this range then it is not a prime number.
If the remainder becomes zero for any number in this range then it is not a prime number.
 Live Demo
x = 23
if x > 1:
   for n in range(2, x):
      if (x % n) == 0:
         print(x, "is not prime")
         print(n, "times", x // n, "is", x)
         break
   else:
      print(x, "is a prime number")
   else:
      print(x, "is not prime number")
Running the above code gives us the following result −
23 is a prime number
All prime numbers which are greater than 6 can be represented in the form of 6i+1. Here I starts from 1 and goes on as integer. In the below example we will check if the number can be presented in the form of 6i+1 by dividing its 6 and checking for a reminder as one. Accordingly, will decide if the number is prime or not. Also we need to check for a i value which is equal to square root of the given number.
 Live Demo
def CheckPrime(n):
   # Check for cases of 2 and 3
   if (n <= 1):
      return False
   if (n <= 3):
      return True
   # skip checking middle five numbers in the loop
   if (n % 2 == 0 or n % 3 == 0):
      return False
   i = 5
   while (i * i <= n):
      if (n % i == 0 or n % (i + 2) == 0):
         return False
      i = i + 6
   return True
# Check for inputs
if (CheckPrime(31)):
   print(" true")
else:
   print(" false")
if (CheckPrime(25)):
   print(" true")
else:
   print(" false")
Running the above code gives us the following result −
true
false