code-rag-bench/online-tutorials huggingface dataset:
Python - Extract Symmetric Tuples - GeeksforGeeks

10 Jul, 2020
Sometimes while working with Python tuples, we can have a problem in which we need to extract all the pairs which are symmetric, i.e for any (x, y), we have (y, x) pair present. This kind of problem can have application in domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(6, 7), (2, 3), (7, 6)]Output : {(6, 7)}
Input : test_list = [(6, 7), (2, 3)]Output : {}
Method #1 : Using dictionary comprehension + set()The combination of above functionalities can be used to solve this problem. In this, we initially construct reverse pairs, and then compare with original list pairs, and extract one of equals. The set() is used to remove duplicates, to avoid unnecessary computions of elements.
# Python3 code to demonstrate working of # Extract Symmetric Tuples# Using dictionary comprehension + set()  # initializing listtest_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]  # printing original listprint("The original list is : " + str(test_list))  # Extract Symmetric Tuples# Using dictionary comprehension + set()temp = set(test_list) & {(b, a) for a, b in test_list}res = {(a, b) for a, b in temp if a < b}  # printing result print("The Symmetric tuples : " + str(res)) 
The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
The Symmetric tuples : {(8, 9), (6, 7)}

 
Method #2 : Using Counter() + list comprehensionThis is yet another way in which this task can be performed. In this, we follow similar approach of constructing reverse pairs, but here, we count the equal elements, the element with count 2 is duplicate and matches the reversed tuples.
# Python3 code to demonstrate working of # Extract Symmetric Tuples# Using Counter() + list comprehensionfrom collections import Counter  # initializing listtest_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]  # printing original listprint("The original list is : " + str(test_list))  # Extract Symmetric Tuples# Using Counter() + list comprehension<temp = [(sub[1], sub[0]) if sub[0] < sub[1] else sub for sub in test_list]cnts = Counter(temp)res = [key for key, val in cnts.items() if val == 2]  # printing result print("The Symmetric tuples : " + str(res)) 
The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
The Symmetric tuples : [(7, 6), (9, 8)]

Python List-of-Tuples
Python list-programs
Python tuple-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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
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?
How to scale Pandas DataFrame columns ? - GeeksforGeeks

02 Jul, 2021
When a dataset has values of different columns at drastically different scales, it gets tough to analyze the trends and patterns and comparison of the features or columns. So, in cases where all the columns have a significant difference in their scales, are needed to be modified in such a way that all those values fall into the same scale. This process is called Scaling.
There are two most common techniques of how to scale columns of Pandas dataframe – Min-Max Normalization and Standardization. Both of them have been discussed in the content below.
Dataset in Use: Iris
Here, all the values are scaled in between the range of [0,1] where 0 is the minimum value and 1 is the maximum value. The formula for Min-Max Normalization is –
Method 1: Using Pandas and Numpy 
The first way of doing this is by separately calculate the values required as given in the formula and then apply it to the dataset.
Example:
Python3
import seaborn as snsimport pandas as pdimport numpy as np data = sns.load_dataset('iris')print('Original Dataset')data.head() # Min-Max Normalizationdf = data.drop('species', axis=1)df_norm = (df-df.min())/(df.max()-df.min())df_norm = pd.concat((df_norm, data.species), 1) print("Scaled Dataset Using Pandas")df_norm.head()
Output:
Method 2: Using MinMaxScaler from sklearn 
This is a straightforward method of doing the same. It just requires sklearn module to be imported.
Example:
Python3
import seaborn as snsfrom sklearn.preprocessing import MinMaxScalerimport pandas as pd data = sns.load_dataset('iris')print('Original Dataset')data.head() scaler = MinMaxScaler() df_scaled = scaler.fit_transform(df.to_numpy())df_scaled = pd.DataFrame(df_scaled, columns=[  'sepal_length', 'sepal_width', 'petal_length', 'petal_width']) print("Scaled Dataset Using MinMaxScaler")df_scaled.head()
Output:
Standardization doesn’t have any fixed minimum or maximum value. Here, the values of all the columns are scaled in such a way that they all have a mean equal to 0 and standard deviation equal to 1. This scaling technique works well with outliers. Thus, this technique is preferred if outliers are present in the dataset. 
Example:
Python3
import pandas as pdfrom sklearn.preprocessing import StandardScalerimport seaborn as sns data = sns.load_dataset('iris')print('Original Dataset')data.head() std_scaler = StandardScaler() df_scaled = std_scaler.fit_transform(df.to_numpy())df_scaled = pd.DataFrame(df_scaled, columns=[  'sepal_length','sepal_width','petal_length','petal_width']) print("Scaled Dataset Using StandardScaler")df_scaled.head()
  
Output :
 
 
simranarora5sos
sweetyty
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Lodash _.minBy() Method - GeeksforGeeks

02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.minBy() method is used to compute the minimum value from the original array by iterating over each element in the array using the Iteratee function. It is almost the same as _.min() function.
Syntax:
_.minBy( array, [iteratee = _.identity] )

Parameters: This method accepts two parameters as mentioned above and described below:
array: It is the array that the method iterates over to get the minimum element.
iteratee: It is the function that is invoked for every element in the array.
Return Value: This method returns the minimum element.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }];    // Use of _.minBy() method let min_val =   _.minBy(arr, function(o) { return o.n; });         // Printing the output  console.log(min_val);
Output:
{ 'n': 2 }

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Original array var arr = [{ 'n': 10 }, { 'n': 5 },            { 'n': 3 }, { 'n': 12 }];    // Use of _.minBy() method let min_val = _.minBy(arr, 'n');         // Printing the output  console.log(min_val);
Output:
{ 'n': 3 }

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to find maximum string length by column in R DataFrame ? - GeeksforGeeks

30 May, 2021
In this article, we are going to see how to find maximum string length by column in R Programming Language. 
To find the maximum string length by column in the given dataframe, first, nchar() function is called to get the length of all the string present in the particular column of the dataframe, and then the max() function must be called to get the maximum value of the length of the string generated by the nchar() function. The nchar() and the max() function are base functions of the R programming language, so there is no need to import any package.
nchar() function takes a character vector as an argument and returns a vector whose elements contain the sizes of the corresponding elements of x
Syntax:
nchar(x, type = “chars”, allowNA = FALSE, keepNA = NA)
Parameter:
x: character vector or a vector to be coerced to a character vector. Giving a factor is an error.
type:character string: partial matching to one of c(“bytes”, “chars”, “width”). See ‘Details’.
allowNA: logical, should NA be returned for invalid multibyte strings or “bytes”-encoded strings (rather than throwing an error)?
keepNA:logical: should NA be returned where ever x is NA?
max() function finds the maximum value among the data provided.
Syntax:
MAX(vector, rank = 1, value = FALSE, rank.adjust = TRUE, forceChoice = FALSE)
Parameter:
vector: Vector in which maximum/minimum element needs to be identified
rank:value(s) or rank(s) of maximum values.
value:  Should value or rank be returned?
rank.adjust: If the maximum value of a range of ranks exceeds vector length, should this be adjusted?
forceChoice: In the case of ties, should all results be returned or only one?
Example1:
R
gfg_data <- data.frame(x = c("geeks", "for", "geeks"),                         y = c("I", "Love", "Coding"),                       z=c("R", "programming ", "language"))  max(nchar(gfg_data$y))  
Output:
[1] 6
Example 2:
R
gfg_data <- data.frame(x = c("geeks", "for", "geeks"),                         y = c("I", "Love", "Coding"),                       z=c("R", "programming ", "language"))  max(nchar(gfg_data$z))  
Output:
[1] 12
Picked
R DataFrame-Programs
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to import an Excel File into R ?
Plot mean and standard deviation using ggplot2 in R
How to filter R dataframe by multiple conditions?
GATE | GATE-CS-2017 (Set 2) | Question 30 - GeeksforGeeks

27 Sep, 2017
A Circular queue has been implemented using singly linked list where each node consists of a value and a pointer to next node. We maintain exactly two pointers FRONT and REAR pointing to the front node and rear node of queue. Which of the following statements is/are correct for circular queue so that insertion and deletion operations can be performed in O(1) i.e. constant time.
I. Next pointer of front node points to the rear node.
II. Next pointer of rear node points to the front node.

(A) I only
(B) II only(C) Both I and II(D) Neither I nor IIAnswer: (B)Explanation: Since, Circular queue deletes an item using Front pointer and insert an element using Rear pointer. If we want to insert an element into circular queue then we have to increment Rear pointer to next node then insert element. Then after update the next pointer of Rear node to the Front node. This method will have O(1) time for Insertion and Deletion.Only statement (ii) is true. So, option (B).Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
strings.FieldsFunc() Function in Golang With Examples - GeeksforGeeks

19 Apr, 2020
strings.FieldsFunc() Function in Golang is used to splits the given string str at each run of Unicode code points c satisfying f(c) and returns an array of slices of str.
Syntax:
func FieldsFunc(str string, f func(rune) bool) []string
Here, str is the given string, the rune is a built-in type meant to contain a single Unicode character and f is a user-defined function.
Return: If all code points in str satisfy f(c) or the string is empty, an empty slice is returned.
Note: This function makes no guarantees about the order in which it calls f(c). If f does not return consistent results for a given c, FieldsFunc may crash.
Example 1:
// Golang program to illustrate the// strings.FieldsFunc() Function  package main  import (    "fmt"    "strings"    "unicode")  func main() {      // f is a function which returns true if the    // c is number and false otherwise    f := func(c rune) bool {        return unicode.IsNumber(c)    }      // FieldsFunc() function splits the string passed    // on the return values of the function f    // String will therefore be split when a number    // is encontered and returns all non-numbers    fmt.Printf("Fields are: %q\n",        strings.FieldsFunc("ABC123PQR456XYZ789", f))}
Output:
Fields are: ["ABC" "PQR" "XYZ"]
Example 2:
// Golang program to illustrate the// strings.FieldsFunc() Functionpackage main  import (    "fmt"    "strings"    "unicode")  func main() {      // f is a function which returns true if the    // c is a white space or a full stop    // and returns false otherwise    f := func(c rune) bool {        return unicode.IsSpace(c) || c == '.'    }      // We can also pass a string indirectly    // The string will split when a space or a    // full stop is encontered and returns all non-numbers    s := "We are humans. We are social animals."    fmt.Printf("Fields are: %q\n", strings.FieldsFunc(s, f))}
Output:
Fields are: ["We" "are" "humans" "We" "are" "social" "animals"]
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
SAP HANA Admin - Key Commands

hdbsql -n localhost -i 1 -u username -p Password \s 

This command will display the details of HANA database such as the host name, database, user, Kernel version, SQLDBC version, etc.
hdbsql -n localhost -i 1 -u username -p Password 
"SELECT CNO,TITLE,FIRSTNAME,NAME,ZIP FROM Database_Name" 

The above command displays the following result about concurrent sessions −
CNO | TITLE | FIRSTNAME | NAME | ZIP 

To start and stop HANA database using HDB, you have to login to HANA system host as <sid>adm and run the following command −
/usr/sap/<SID>/HDB<instance number>/HDB start 
/usr/sap/<SID>/HDB<instance number>/HDB stop 


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
What is the significant difference between MySQL TRUNCATE and DROP command?

The most significant difference between MySQL TRUNCATE and DROP command is that TRUNCATE command will not destroy table’s structure but in contrast DROP command will destroy table’s structure too.
mysql> Create table testing(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,Name Varchar(20));
Query OK, 0 rows affected (0.24 sec)

mysql> Insert into testing(Name) Values('Ram'),('Mohan'),('John');
Query OK, 3 rows affected (0.12 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> Select * from testing;
+----+-------+
| id | Name  |
+----+-------+
| 1  | Ram   |
| 2  | Mohan |
| 3  | John  |
+----+-------+
3 rows in set (0.00 sec)
Now after TRUNCATING the ‘testing’ table as follows, still its structure remains in the database and it also initializes the PRIMARY KEY.
mysql> Truncate table testing;
Query OK, 0 rows affected (0.04 sec)

mysql> DESCRIBE testing;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.21 sec)
But when we apply DROP command on a table then the structure also deleted from the database.
mysql> Drop table testing;
Query OK, 0 rows affected (0.08 sec)

mysql> DESCRIBE testing;
ERROR 1146 (42S02): Table 'query.testing' doesn't exist
Autorun a Python script on windows startup?

Appending a Python script to windows start-up basically indicates the python script will run as the windows boots up. This can be accomplished by two step processes -
Step #1: Appending or Adding script to windows Startup folder
After booting up of the windows, it executes (equivalent to double-clicking) all the application present in its startup folder or directory.
C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
By default, the AppData directory or folder under the current_user is hidden that enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Besides this the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing.
Step #2: Appending or adding script to windows Registry
This process may be risky if not accomplished properly, it includes editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry consists of the list of programs that must execute once the user Login. Registry Path−
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
# Python code to append or add current script to the registry
# module to modify or edit the windows registry
importwinreg as reg1
importos
   # in python __file__ is denoeted as the instant of
   # file path where it was run or executed
   # so if it was executed from desktop,
   # then __file__ will be
   # c:\users\current_user\desktop
   pth1 =os.path.dirname(os.path.realpath(__file__))
   # Python file name with extension
   s_name1="mYscript.py"
   # The file name is joined to end of path address
   address1=os.join(pth1,s_name1)
   # key we want to modify or change is HKEY_CURRENT_USER
   # key value is Software\Microsoft\Windows\CurrentVersion\Run
   key1 =HKEY_CURRENT_USER
   key_value1 ="Software\Microsoft\Windows\CurrentVersion\Run"
   # open the key to make modifications or changes to
   open=reg1.OpenKey(key1,key_value1,0,reg1.KEY_ALL_ACCESS)
   # change or modifiy the opened key
   reg1.SetValueEx(open,"any_name",0,reg1.REG_SZ,address1)
   # now close the opened key
   reg1.CloseKey(open)
# Driver Code
if__name__=="__main__":
AddToRegistry()
Add Count and Percentage Labels on Top of Histogram Bars in R - GeeksforGeeks

30 Jun, 2021
A histogram denotes the frequencies or contingency of values of the specified variable segregated into ranges. It groups the values into continuous ranges. Each bar of the histogram is used to denote the height, that is the number of values present in that specific range.
The hist() method in base R is used to display a histogram of the given data values. It takes as input a vector of the data values and outputs a corresponding histogram for the same. 
Syntax:
hist ( x , labels)
Parameter : 
x – The set of data points to plot
labels – By default, FALSE. If true, it is used to denote a set of counts on the top of bars. It can also take a function , a character or numeric vector .
Let us first create a regular histogram so that the difference is apparent.
Example:
R
# setting the seed valueset.seed(67832)  # define x values using the# rnorm methodxpos <- rnorm(50)  # plotting the histogram hist(xpos , ylim=c(0,20))
Output
In order to compute the counts of the number of values encountered in each range, the labels attribute can be set to TRUE. 
Syntax:
hist(..., labels=TRUE,..)
Example:
R
# setting the seed valueset.seed(67832)  # define x values using the # rnorm methodxpos <- rnorm(50)  # plotting the histogram hist(xpos , labels = TRUE, ylim=c(0,20))
Output
The percentage can be computed using mathematical functions. Initially, the histogram without any labels is stored in a variable. Its counts can be accessed using the counts attribute of the extracted histogram variable. This returns an integer vector of values each of which is divided by the length of the input data vector. These values are multiplied by 100 to turn into decimal values. 
The decimal values can be rounded off to a specific number of digits using the round() method in R programming language.
Syntax: 
round(num , digits)
The paste0() method can be used to concatenate values together and append a “%” sign to the corresponding values. In this method, the separator is an empty string by default. 
Syntax:
paste0(val , “%”)
Example:
R
# setting the seed valueset.seed(67832)  # define x values using the rnorm methodxpos <- rnorm(50)  # computing length of x labelslen <- length(xpos)  # drawing a histogram without labelshist_init <- hist(xpos, plot = FALSE)  # round the percentage to two placesrounded <- round(hist_init$counts / len * 100, 2)  # drawing a histogram # adding % symbol in the valuehist(xpos,                                labels = paste0(rounded , "%"), ylim=c(0,20))
Output
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Python - Tkinter place() Method

This geometry manager organizes widgets by placing them in a specific position in the parent widget.
widget.place( place_options )

Here is the list of possible options −
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
height, width − Height and width in pixels.
height, width − Height and width in pixels.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
x, y − Horizontal and vertical offset in pixels.
x, y − Horizontal and vertical offset in pixels.
Try the following example by moving cursor on different buttons −
from Tkinter import *
import tkMessageBox
import Tkinter

top = Tkinter.Tk()

def helloCallBack():
   tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
B.place(bordermode=OUTSIDE, height=100, width=100)
top.mainloop()
When the above code is  executed, it produces the following result −

    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
Tryit Editor v3.7

HTML Form elements
Tryit: HTML datalist element
HAS-A relationship in Java

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Let's look into an example −
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle {
   private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.
In an Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
Python - Convert TSV to CSV file - GeeksforGeeks

05 Nov, 2021

In this article, we will see how to Convert TSV Files to CSV using Python. 
TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\t”) with comma(“,”) as data in CSV file is comma-separated.  
Example:
Input File:
Python3
 

 
 










# Python program to convert .tsv file to .csv file 
# importing re library 
import re 
  
# reading given tsv file 
with open("Olympic.tsv", 'r') as myfile:   
  with open("Olympic.csv", 'w') as csv_file: 
    for line in myfile: 
        
      # Replace every tab with comma 
      fileContent = re.sub("\t", ",", line) 
        
      # Writing into csv file 
      csv_file.write(fileContent) 
  
# output 
print("Successfully made csv file")






Output:
Successfully made csv file
The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False.
Example:
Input File:
Python3
 

 
 










# Python program to convert .tsv file to .csv file 
# importing pandas library 
import pandas as pd  
  
tsv_file='GfG.tsv'
  
# readinag given tsv file 
csv_table=pd.read_table(tsv_file,sep='\t') 
  
# converting tsv file into csv 
csv_table.to_csv('GfG.csv',index=False) 
  
# output 
print("Successfully made csv file")






Output:
Successfully made csv file
Output File:

Picked


Python-TSV


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install PIP on Windows ?
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.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Mean Squared Error - GeeksforGeeks

30 Jun, 2019
The Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator measures the average of error squares i.e. the average squared difference between the estimated values and true value. It is a risk function, corresponding to the expected value of the squared error loss. It is always non – negative and values close to zero are better. The MSE is the second moment of the error (about the origin) and thus incorporates both the variance of the estimator and its bias.
Steps to find the MSE
Find the equation for the regression line.(1)   Insert X values in the equation found in step 1 in order to get the respective Y values i.e.(2)   Now subtract the new Y values (i.e. ) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.(3)   Square the errors found in step 3.(4)   Sum up all the squares.(5)   Divide the value found in step 5 by the total number of observations.(6)   
Find the equation for the regression line.(1)   
(1)   
Insert X values in the equation found in step 1 in order to get the respective Y values i.e.(2)   
(2)   
Now subtract the new Y values (i.e. ) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.(3)   
(3)   
Square the errors found in step 3.(4)   
(4)   
Sum up all the squares.(5)   
(5)   
Divide the value found in step 5 by the total number of observations.(6)   
(6)   
Example:Consider the given data points: (1,1), (2,1), (3,2), (4,2), (5,4)You can use this online calculator to find the regression equation / line.
Regression line equation: Y = 0.7X – 0.1
Now, using formula found for MSE in step 6 above, we can get MSE = 0.21606
MSE using scikit – learn:
from sklearn.metrics import mean_squared_error  # Given valuesY_true = [1,1,2,2,4]  # Y_true = Y (original values)  # calculated valuesY_pred = [0.6,1.29,1.99,2.69,3.4]  # Y_pred = Y'  # Calculation of Mean Squared Error (MSE)mean_squared_error(Y_true,Y_pred)
Output: 0.21606
MSE using Numpy module:
import numpy as np  # Given valuesY_true = [1,1,2,2,4]  # Y_true = Y (original values)  # Calculated valuesY_pred = [0.6,1.29,1.99,2.69,3.4]  # Y_pred = Y'  # Mean Squared ErrorMSE = np.square(np.subtract(Y_true,Y_pred)).mean()
Output: 0.21606
Advanced Computer Subject
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Extract images from video in Python - GeeksforGeeks

29 Aug, 2018
OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV.
Image Analysis is a very common field in the area of Computer Vision. It is the extraction of meaningful information from videos or images. OpenCv library can be used to perform multiple operations on videos.
Modules Needed:
import cv2
import os

Function Used :
VideoCapture(File_path) : Read the video(.mp4 format)
read() : Read data depending upon the type of object that calls
imwrite(filename, img[, params]) : Saves an image to a specified file.
Below is the implementation:
# Importing all necessary librariesimport cv2import os  # Read the video from specified pathcam = cv2.VideoCapture("C:\\Users\\Admin\\PycharmProjects\\project_1\\openCV.mp4")  try:          # creating a folder named data    if not os.path.exists('data'):        os.makedirs('data')  # if not created then raise errorexcept OSError:    print ('Error: Creating directory of data')  # framecurrentframe = 0  while(True):          # reading from frame    ret,frame = cam.read()      if ret:        # if video is still left continue creating images        name = './data/frame' + str(currentframe) + '.jpg'        print ('Creating...' + name)          # writing the extracted images        cv2.imwrite(name, frame)          # increasing counter so that it will        # show how many frames are created        currentframe += 1    else:        break  # Release all space and windows once donecam.release()cv2.destroyAllWindows()
Output:
All the extracted images will be saved in a folder named “data” on the system.
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Check if an Object is of Type Integer in R Programming - is.integer() Function - GeeksforGeeks

16 Jun, 2020
is.integer() function in R Language is used to check if the object passed to it as argument is of integer type.
Syntax: is.integer(x)
Parameters:x: Object to be checked
Example 1:
# R program to check if # object is an integer  # Creating a vectorx1 <- 4Lx2 <- c(1:6)x3 <- c("a", "b", "c", "d")x4 <- c(1, 2, "a", 3, "b")  # Calling is.integer() functionis.integer(x1)is.integer(x2)is.integer(x3)is.integer(x4)
Output:
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE

Example 2:
# R program to check if # object is an integer  # Creating a matrixx1 <- matrix(c(1:9), 3, 3)  # Calling is.integer() functionis.integer(x1)
Output:
[1] TRUE

R List-Function
R Math-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?
Insert values in a table by MySQL SELECT from another table in MySQL?

Fir this, use INSERT INTO SELECT statement. Let us first create a table −
mysql> create table DemoTable1
   -> (
   -> Id int,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (1.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(100,'Chris',24);
Query OK, 1 row affected (0.61 sec)
mysql> insert into DemoTable1 values(101,'Adam',23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1 values(102,'John',25);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(103,'Carol',26);
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1;
This will produce the following output −
+------+-------+------+
| Id   | Name | Age |
+------+-------+------+
|  100 | Chris |   24 |
|  101 | Adam  |   23 |
|  102 | John  |   25 |
|  103 | Carol |   26 |
+------+-------+------+
4 rows in set (0.00 sec)
Here is the query to create second table −
mysql> create table DemoTable2
   -> (
   -> EmployeeId int,
   -> EmployeeFirstName varchar(20),
   -> EmployeeAge int
   -> );
Query OK, 0 rows affected (1.63 sec)
Here is the query to insert values in DemoTable2 from MySQL select from DemoTable1 −
mysql> insert into DemoTable2(EmployeeId,EmployeeFirstName,EmployeeAge) select Id,Name,Age from DemoTable1 where Id=101;
Query OK, 1 row affected (0.17 sec)
Records: 1 Duplicates: 0 Warnings: 0
Let us check the table records −
mysql> select * from DemoTable2;
Here is the query to create second table −
+------------+-------------------+-------------+
| EmployeeId | EmployeeFirstName | EmployeeAge |
+------------+-------------------+-------------+
|        101 | Adam              |          23 |
+------------+-------------------+-------------+
1 row in set (0.00 sec)
How do we create a string from the contents of a file in java?

In Java you can read the contents of a file in several ways one way is to read it to a string using the java.util.Scanner class, to do so,
Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor.
Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor.
Create an empty String buffer.
Create an empty String buffer.
Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while.
Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while.
Within the loop append each line of the file to the StringBuffer object using the append() method.
Within the loop append each line of the file to the StringBuffer object using the append() method.
Convert the contents of the contents of the buffer to String using the toString() method.
Convert the contents of the contents of the buffer to String using the toString() method.
Create a file with name sample.txt in the C directory in your system, copy and paste the following content in it.
Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class 
of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, 
in your own space.

After a successful journey of providing the best learning content at tutorialspoint.com, we created 
our subscription based premium product called Tutorix to provide Simply Easy Learning in the best 
personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
Following Java program reads the contents of the file sample.txt in to a String and prints it.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileToString {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(" "+input);
      }
      System.out.println("Contents of the file are: "+sb.toString());
   }
}
Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to 
provide knowledge to that class of readers that responds better to online content. With Tutorials Point, 
you can learn at your own pace, in your own space. After a successful journey of providing the best 
learning content at tutorialspoint.com, we created our subscription based premium product called 
Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants 
of competitive exams like IIT/JEE and NEET.
Java Generics - Raw Types

A raw type is an object of a generic class or interface if its type arguments are not passed during its creation. Following example will showcase above mentioned concept.
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      Box<Integer> box = new Box<Integer>();
      
      box.set(Integer.valueOf(10));
      System.out.printf("Integer Value :%d\n", box.getData());
      
      
      Box rawBox = new Box();
      
      //No warning
      rawBox = box;
      System.out.printf("Integer Value :%d\n", rawBox.getData());
      
      //Warning for unchecked invocation to set(T)
      rawBox.set(Integer.valueOf(10));
      System.out.printf("Integer Value :%d\n", rawBox.getData());
      
      //Warning for unchecked conversion
      box = rawBox;
      System.out.printf("Integer Value :%d\n", box.getData());
   }
}

class Box<T> {
   private T t; 

   public void set(T t) {
      this.t = t;
   }

   public T getData() {
      return t;
   } 
}
This will produce the following result.
Integer Value :10
Integer Value :10
Integer Value :10
Integer Value :10


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Draw a Quantile-Quantile Plot in R Programming - qqline() Function - GeeksforGeeks

16 Dec, 2021
The Quantile-Quantile Plot in Programming Language, or (Q-Q Plot) is defined as a value of two variables that are plotted corresponding to each other and check whether the distributions of two variables are similar or not with respect to the locations. qqline() function in R Language is used to draw a Q-Q Line Plot.
Syntax: qqline(x, y, col)
Parameters: 
x, y: X and Y coordinates of plot
col: It defines color
Returns: A QQ Line plot of the coordinates provided 
R
# Set seed for reproducibilityset.seed(500) # Create random normally distributed valuesx <- rnorm(1200) # QQplot of normally distributed valuesqqnorm(x) # Add qqline to plotqqline(x, col = "darkgreen")
Output:
Above is a representation of QQplot of Normally Distributed Random Numbers.
R
# Set seed for reproducibility # Random values according to logistic distribution# QQplot of logistic distributiony <- rlogis(800) # QQplot of normally distributed valuesqqnorm(y) # Add qqline to plotqqline(y, col = "darkgreen")
Output: 
Above is the Q-Q Plot of theoretical quantiles. 
kumar_satyam
R Plot-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
How to Change Image Source URL using AngularJS ? - GeeksforGeeks

14 Oct, 2020
Here the task is to change the source URL of the image with the help of AngularJS.
Approach: The approach is to change the URL of the image when the user click on button. When a user clicks on a button then a method is called along with the new URL, that method replaces the new URL with the old one in controller.
Example 1:
<!DOCTYPE HTML><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>    <script>        var myApp = angular.module("app", []);        myApp.controller("controller", function ($scope) {            $scope.imgUrl ="https://media.geeksforgeeks.org/wp-content/uploads/20190515121004/gfgbg1-300x136.png";            $scope.changeURL = function (url) {                $scope.imgUrl = url;            };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to Change Image Src URL in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            <button ng-click="changeURL('https://media.geeksforgeeks.org/wp-content/uploads/20190515120525/gfglogo1.png')">                Change Image</button>            <br>            <br>            <img src="{{imgUrl}}">        </div>    </div></body>  </html> 
Output:
Example 2: In this example, the URL changing can be seen in output.
<!DOCTYPE HTML><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>      <script>        var myApp = angular.module("app", []);        myApp.controller("controller", function ($scope) {            $scope.imgUrl ="https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png";            $scope.changeURL = function (url) {                $scope.imgUrl = url;            };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to Change Image Src URL in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            <button ng-click="changeURL('https://media.geeksforgeeks.org/wp-content/uploads/20190529122826/bs11.png')">                Change Image</button>            <br>            <br>            URL - {{imgUrl}}            <img src="{{imgUrl}}">        </div>    </div></body>  </html>     
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Messages Component
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
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
HTML | <input> name Attribute - GeeksforGeeks

19 Oct, 2020
The HTML <input> name Attribute is used to specify a name for an <input> element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript.
Syntax:
<input name="name"> 
Attribute Values: It contains a single value name which describes the name of the <input> element.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML Input name Attribute    </title></head>  <body style="text-align:center;">      <h1>GeeksForGeeks</h1>      <h2>HTML Input name Attribute</h2>    <form id="myGeeks">        <input type="text"               id="text_id"                name="geeks"               pattern="[A-Za-z]{3}"                value="Manas Chhabra">    </form>    <br></body>  </html>
Output:
Supported Browsers:
Google Chrome 1.0
Firefox 1.0
Edge 2.0
Opera 1.0
Apple Safari 1.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
arorakashish0911
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
HTML Cheat Sheet - A Basic Guide to HTML
Form validation using HTML and JavaScript
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript