code-rag-bench/online-tutorials huggingface dataset:
Counting number of repeating words in a Golang String - GeeksforGeeks

04 May, 2020
Given a string, the task is to count the number of words being repeated in that particular string in Golang.
Example:
Input: s = "She is mother of my mother."
Output: She = 1     
         is = 1
         mother = 2
         of = 1
         my = 1

To count the number of repeating words, first, the string is taken as input and then strings.Fields() function is used to split the string. A function “repetition” is defined to count the number of words getting repeated.
Below is the program in Golang to count the number of repeating words in a given string.
// Golang program to count the number of// repeating words in given Golang Stringpackage main  import (    "fmt"    "strings")  func repetition(st string) map[string]int {      // using strings.Field Function    input := strings.Fields(st)    wc := make(map[string]int)    for _, word := range input {        _, matched := wc[word]        if matched {            wc[word] += 1        } else {            wc[word] = 1        }    }    return wc}  // Main functionfunc main() {    input := "betty bought the butter , the butter was bitter , " +        "betty bought more butter to make the bitter butter better "    for index, element := range repetition(input) {        fmt.Println(index, "=", element)    }}
Output:
the = 3
, = 2
bitter = 2
to = 1
make = 1
better = 1
betty = 2
bought = 2
butter = 4
was = 1
more = 1

Explanation: In the above program, we first take a string as an input and then split that string using strings.Fields() function. If the same word has occurred, the count increases by one else value 1 is returned that implies that word occurs only once in the string.
Golang-Program
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
Class and Object in Golang
How to convert a string in uppercase in Golang?
Rune in Golang
C# | How to change the Output Encoding Scheme of the Console - GeeksforGeeks

28 Jan, 2019
Given the normal Console in C#, the task is to change the Output Encoding Scheme of the Console.
Approach: This can be done using the OutputEncoding property in the Console class of the System package in C#.
Program 1: Getting the value of Output Encoding Scheme
// C# program to illustrate the// Console.OutputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the Output Encoding Scheme        Console.WriteLine("Current Output Encoding Scheme: {0}",                                        Console.OutputEncoding);    }}}
Output:
Program 2: Setting the value of Output Encoding Scheme
// C# program to illustrate the// Console.OutputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the Output Encoding Scheme        Console.WriteLine("Current Output Encoding Scheme: {0}",                                        Console.OutputEncoding);          // Set the Output Encoding Scheme to ASCII        Console.OutputEncoding = Encoding.ASCII;          // Get the Output Encoding Scheme        Console.WriteLine("Current Output Encoding Scheme: {0}",                                        Console.OutputEncoding);    }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
PyQt5 QDateEdit - Setting Date Programmatically - GeeksforGeeks

25 May, 2021
In this article, we will see how we can date programmatically to the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records.In order to do this we use setDate method with the QDateEdit object  
Syntax : date.setDate(d)Argument : It takes QDate object as argumentReturn : It returns None  
Below is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 500, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QDateEdit widget        date = QDateEdit(self)         # setting geometry of the date edit        date.setGeometry(100, 100, 150, 40)         # date        d = QDate(2020, 6, 10)         # setting date to the date edit        date.setDate(d)            # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
sweetyty
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
clock() function in C/C++ - GeeksforGeeks

28 Sep, 2018
The clock() function is defined in the ctime header file. The clock() function returns the approximate processor time that is consumed by the program. The clock() time depends upon how the operating system allocate resources to the process that’s why clock() time may be slower or faster than the actual clock.
Syntax:
clock_t clock( void );
Parameters: This function does not accept any parameter.
Return Value: This function returns the approximate processor time that is consumed by the program and on failure function returns -1.
Below program illustrates the implementation of clock() function:
// C++ program to demonstrate// example of clock() function.  #include<bits/stdc++.h>using namespace std;  int main (){    float a;    clock_t time_req;      // Without using pow function    time_req = clock();    for(int i=0; i<200000; i++)    {        a = log(i*i*i*i);    }    time_req = clock()- time_req;    cout << "Processor time taken for multiplication: "        << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;      // Using pow function    time_req = clock();    for(int i=0; i<200000; i++)    {        a = log(pow(i, 4));    }    time_req = clock() - time_req;    cout << "Processor time taken in pow function: "        << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;      return 0;}
Processor time taken for multiplication: 0.006485 seconds
Processor time taken in pow function: 0.022251 seconds

C-Functions
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
Substring in C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Printing the correct number of decimal points with cout in C++

Here we will see how to print some floating point numbers up to some pre-defined decimal places. In C++, we can use setprecision with the cout to do this word. This is present under the iomanip header file in C++.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
   double x = 2.3654789d;
   cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl;
   cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl;
   cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl;
}
Print up to 3 decimal places: 2.365
Print up to 2 decimal places: 2.37
Print up to 7 decimal places: 2.3654789
How to use relative xpath for locating a web-element by particular Attribute in Selenium?

We can use relative xpath for locating web-element by particular attribute value. A relative xpath begins from the element to be located and not from the root.
It begins with the // symbol. It’s advantage is that even if an element is deleted or added in the DOM, the relative xpath for a specific element remains unaffected. To obtain a relative path by an attribute, the xpath expression is //tagname[@attribute='value'].
Let us identify the below highlighted element on the page with the help of the alt attribute.
l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element with an attribute using xpath
l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")
#get src attribute
s = l.get_attribute('src')
print('Src attribute value is: ')
print(s)
#browser quit
driver.quit()
Python: Passing Dictionary as Arguments to Function - GeeksforGeeks

30 Jan, 2020
A dictionary in Python is a collection of data which is unordered and mutable. Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value.
Refer to the below article to get the idea about Python Dictionary.
Python Dictionary
In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.
Example:
# Python program to demonstrate# passing dictionary as argument    # A function that takes dictionary# as an argumentdef func(d):          for key in d:        print("key:", key, "Value:", d[key])          # Driver's codeD = {'a':1, 'b':2, 'c':3}func(D)
Output:
key: b Value: 2
key: a Value: 1
key: c Value: 3

Passing Dictionary as kwargs
“kwargs” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn’t have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.
Example 1:
# Python program to demonstrate# passing dictionary as kwargs    def display(**name):          print (name["fname"]+" "+name["mname"]+" "+name["lname"])  def main():          # passing dictionary key-value     # pair as arguments    display(fname ="John",            mname ="F.",             lname ="Kennedy")# Driver's codemain()
Output:
John F. Kennedy

Example 2:
# Python program to demonstrate# passing dictionary as kwargs    def display(x = 0, y = 0, **name):          print (name["fname"]+" "+name["mname"]+" "+name["lname"])    print ("x =", x)    print ("y =", y)  def main():    # passing dictionary key-value     # pair with other arguments    display(2, fname ="John", mname ="F.", lname ="Kennedy")      # Driver's codemain()
Output:
John F. Kennedy
x = 2
y = 0

Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
HTML content modification using Javascript - GeeksforGeeks

23 Apr, 2019
JavaScript is the dynamic, lightweight and most commonly computer programming language used to create a web pages. It interact with client side and make dynamic pages.
JavaScript Can Change Content of HTML page: The getElementById() method is used to get the id of element and change the HTML content.
Example:
<!DOCTYPE html><html>  <head>    <title>        Change HTML Content using Javascript    </title></head>  <body>    <h1>        GeeksforGeeks    </h1>          <h2>        Change HTML Content using Javascript    </h2>          <p id="GFG">        GeeksforGeeks: A computer science portal    </p>          <button type="button" onclick=        'document.getElementById("GFG").innerHTML                 ="Welcome to GeeksforGeeks"'>        Click Here!    </button></body>  </html>
Output:
Before Clicking the button:
After Clicking the button:
JavaScript Can Change Styles of HTML page: JavaScript can be used to change the CSS property of HTML page.
Example:
<!DOCTYPE html><html>  <head>    <title>        Change HTML Content using Javascript    </title></head>  <body>    <h1>        GeeksforGeeks    </h1>          <h2>        Change HTML Content using Javascript    </h2>          <p id="GFG">        GeeksforGeeks: A computer science portal    </p>          <button type="button" onclick=        "document.getElementById('GFG').style.fontSize=                '25px'">        Click Here!    </button></body>  </html>
Output:
Before Clicking the button:
After Clicking the button:
JavaScript Can Hide or Show HTML Elements: JavaScript can be used to change the display property to hide or show element content.
Example:
<!DOCTYPE html><html>  <head>    <title>        Change HTML Content using Javascript    </title></head>  <body>    <h1>        GeeksforGeeks    </h1>          <h2>        Change HTML Content using Javascript    </h2>          <p id="GFG">        GeeksforGeeks: A computer science portal    </p>          <button type="button" onclick=        "document.getElementById('GFG').style.display=                'none'">        Click Here!    </button></body>  </html>
Output before clicking:
Output after clicking:
HTML-Misc
JavaScript-Misc
Picked
JavaScript
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 append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
How to Use the JavaScript Fetch API to Get Data?
ALTER SCHEMA in SQL Server - GeeksforGeeks

04 Sep, 2020
The ALTER SCHEMA statement used to transfer a object from a schema to another schema in the same database.
Syntax :
ALTER SCHEMA target_schema_name    
   TRANSFER [ object_type :: ] object_name;

Parameters :
target_schema_name is the schema in the database, into which the object will be moved.
object_type represents the type of the object for which the owner schema will be changed.
object_name is the name of the object that will be moved to the target_schema_name.
Note : SYS or INFORMATION_SCHEMA cannot be altered.
Example :Let us create table named geektab in the dbo schema :
CREATE TABLE dbo.geektab
(id INT PRIMARY KEY IDENTITY,
name NVARCHAR(40) NOT NULL,
address NVARCHAR(255) NOT NULL);

Now, insert some rows into the dbo.geektab table :
INSERT INTO dbo.geektab (id, name, address)
VALUES (1, 'Neha', 'B-Wing, Delhi'), (2, 'Vineet', 'D-Wing, Noida');

Lets us create a stored procedure that finds id :
CREATE PROCEDURE sp_get_id(@id INT
) AS
BEGIN
SELECT *
FROM dbo.geektab
WHERE id = @id;
END;

Let us move this dbo.geektab table to the geek schema :
ALTER SCHEMA geek TRANSFER OBJECT::dbo.geektabs;
Run the sp_get_id stored procedure :
EXEC sp_get_id;
SQL Server will throw an error similar to mentioned below :
strong>Msg 208, Level 16, State 1, Procedure sp_get_id, Line 3
Invalid object name 'dbo.geektab'

Now, let us manually alter the stored procedure to reflect the geek schema :
ALTER PROCEDURE sp_get_id( @id INT
) AS
BEGIN SELECT *
FROM geek.geektab
WHERE id = @id;
END;

Run the sp_get_id stored procedure :
EXEC sp_get_id 1; 
Output –
DBMS-SQL
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Two Phase Locking Protocol
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
PostgreSQL - RANK Function - GeeksforGeeks

10 Feb, 2021
In PostgreSQL, the RANK() function is used to assign a rank to each row of the query result set within the specified partition. The rank of the first row within each partition is 1.
The following illustrates the syntax of the RANK() function:
Syntax:
RANK() OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)
Let’s analyze the above syntax:
First, the PARTITION BY clause creates partition in the query result where the RANK() function is applied.
The ORDER BY clause sets the order in which the query results are displayed.
Example 1:
First, create a table named Rankings that contains one column:
CREATE TABLE Rankings(
    g VARCHAR(100)
);
Now add some data to it:
INSERT INTO Rankings(g)
VALUES('Ram'), ('Ravi'), ('Bhola'), ('Bhagat'), ('Bhushan'), ('Chintu'), ('Isha');
Now, use the RANK() function to assign ranks to the rows in the result set of ranks table:
SELECT
    g,
    RANK () OVER ( 
        ORDER BY g 
    ) rank
FROM
    Rankings;
Output:
Example 2:
First, create two tables named Mammals and Animal_groups:
CREATE TABLE Animal_groups (
    animal_id serial PRIMARY KEY,
    animal_name VARCHAR (255) NOT NULL
);

CREATE TABLE Mammals (
    mammal_id serial PRIMARY KEY,
    mammal_name VARCHAR (255) NOT NULL,
    lifespan DECIMAL (11, 2),
    animal_id INT NOT NULL,
    FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id)
);


Now add some data to it:
INSERT INTO Animal_groups (animal_name)
VALUES
    ('Terrestrial'),
    ('Aquatic'),
    ('Winged');

INSERT INTO Mammals(mammal_name, animal_id, lifespan)
VALUES
    ('Cow', 1, 10),
    ('Dog', 1, 7),
    ('Ox', 1, 13),
    ('Wolf', 1, 11),
    ('Blue Whale', 2, 80),
    ('Dolphin', 2, 5),
    ('Sea Horse', 2, 3),
    ('Octopus', 2, 8),
    ('Bat', 3, 4),
    ('Flying Squirrels', 3, 1),
    ('Petaurus', 3, 2);
The below statement uses the RANK() function to assign a rank to each mammals by its lifespan:
SELECT
    mammal_id,
    mammal_name,
    lifespan,
    RANK () OVER ( 
        ORDER BY lifespan DESC
    ) long_life 
FROM
    Mammals;
Output:
PostgreSQL-function
PostgreSQL-Window-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - Identity Column
Opening tif file using GDAL in Python - GeeksforGeeks

12 Nov, 2020
To open a raster file we need to register drivers. In python, GDALAllRegister() is implicitly called whenever gdal is imported. The tiff file to be opened can be downloaded here.
Importing the modules: Import the gdal and ogr modules from osgeo.
Python3
from osgeo import gdal, ogr
Opening the file: The raster dataset can be opened using gdal.open() by passing the filename and path. 
Python3
dataset = gdal.Open(r'land_shallow_topo_2048.tif')
Getting the metadata: We can fetch the metadata of the tif file using the GetMetadata() method.
Python3
print(dataset.GetMetadata())
Output:
{‘TIFFTAG_RESOLUTIONUNIT’: ‘2 (pixels/inch)’, ‘TIFFTAG_XRESOLUTION’: ’72’, ‘TIFFTAG_YRESOLUTION’: ’72’}
Getting other information: We can get the number of bands(represents the RGB channels) using the RasterCount() method, width of the image using RasterXSize() method and the height using RasterYSize() method.
Python3
print(dataset.RasterCount)  # width print(dataset.RasterXSize)  # heightprint(dataset.RasterYSize)
Output:
3
2048
1024

python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Function Overloading and Default Arguments in C++ - GeeksQuiz

07 Mar, 2018
#include <iostream>
using namespace std;

int fun(int x, int y = 0, int z = 0)
{  return (x + y + z); }

int main()
{
   cout << fun(10);
   return 0;
}

    int fun(int x, int y);
         void fun(int x, int y); 
    int fun(int x, int y);
         static int fun(int x, int y); 
int fun(int *ptr, int n);
int fun(int ptr[], int n); 
int fun( int x, int y); 
int fun( int x, int y = 10); 
#include 
using namespace std;
void square (int *x)
{
*x = (*x)++ * (*x);
}
void square (int *x, int *y)
{
*x = (*x) * --(*y);
}
int main ( )
{
int number = 30;
square(&number, &number);
cout << number;
return 0;
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
C Program For Finding Length Of A Linked List
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
C Program to read contents of Whole File
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
Python - Unique values count of each Key - GeeksforGeeks

24 Jan, 2021
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key.
Example:
Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6}, 
{“gfg” : 7, “is” : 3, “best” : 10}]
Output : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Explanation : gfg has 1 and 7 as unique elements, hence 2.
Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6},
 {“gfg” : 1, “is” : 3, “best” : 10}]
Output : {‘gfg’: 1, ‘is’: 1, ‘best’: 3}
Explanation : gfg has only 1 as unique element, hence 1.
Method #1 : Using len() + set() + loop
In this, unique values is extracted using set(), len() is used to get its count, and then the result is mapped to each key extracted using keys(). Iterating over keys occur in loop.
Python3
# Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set()  # initializing liststest_list = [{"gfg": 1, "is": 3, "best": 2}, {    "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original listprint("The original list is : " + str(test_list))  res = dict()for key in test_list[0].keys():      # mapping unique values.    res[key] = len(set([sub[key] for sub in test_list]))  # printing resultprint("Unique count of keys : " + str(res))
Output:
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},
 {‘gfg’: 7, ‘is’: 3, ‘best’: 10}]
Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Method #2 : Using dictionary comprehension + len() + set()
Similar to above method, difference being dictionary comprehension is used as one liner alternative for shorthand.
Python3
# Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set() + dictionary comprehension  # initializing liststest_list = [{"gfg": 1, "is": 3, "best": 2}, {    "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original listprint("The original list is : " + str(test_list))  # dictionary comprehension for compact solutionres = {key: len(set([sub[key] for sub in test_list]))       for key in test_list[0].keys()}  # printing resultprint("Unique count of keys : " + str(res))
Output:
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},
 {‘gfg’: 7, ‘is’: 3, ‘best’: 10}]
Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Python dictionary-programs
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?
Insert a given column at a specific position in a Pandas DataFrame - GeeksforGeeks

26 Jul, 2020
In this article, we will use Dataframe.insert() method of Pandas to insert a new column at a specific column index in a dataframe.
Syntax: DataFrame.insert(loc, column, value, allow_duplicates = False)
Return: None
Code: Let’s create a Dataframe.
Python3
# Importing pandas libraryimport pandas as pd  # dictionaryvalues = {'col2': [6, 7, 8,                    9, 10],          'col3': [11, 12, 13,                   14, 15]}  # Creating dataframedf = pd.DataFrame(values)  # show the dataframedf
Output:
Example 1: Inserting column at the beginning of the dataframe.
Python3
# Importing pandas libraryimport pandas as pd  # dictionaryvalues = {'col2': [6, 7, 8,                    9, 10],           'col3': [11, 12, 13,                   14, 15]}  # Creating dataframedf = pd.DataFrame(values)  # New column to be addednew_col = [1, 2, 3, 4, 5]   # Inserting the column at the# beginning in the DataFramedf.insert(loc = 0,          column = 'col1',          value = new_col)# show the dataframedf
Output: 
Example 2: Inserting column in the middle of the dataframe
Python3
# Importing pandas libraryimport pandas as pd  # dictionaryvalues = {'col2': [6, 7, 8,                    9, 10],           'col3': [11, 12, 13,                   14, 15]}  # Creating dataframedf = pd.DataFrame(values)  # New column to be addednew_col = [1, 2, 3, 4, 5]   # Inserting the column at the# middle of the DataFramedf.insert(loc = 1,          column = 'col1',          value = new_col)# show the dataframedf
Output: 
Example 3: Inserting column at the end of the dataframe
Python3
# Importing pandas libraryimport pandas as pd  # dictionaryvalues = {'col2': [6, 7, 8,                    9, 10],           'col3': [11, 12, 13,                   14, 15]}  # Creating dataframedf = pd.DataFrame(values)  # New column to be addednew_col = [1, 2, 3, 4, 5]   # Inserting the column at the# end of the DataFrame# df.columns gives index array # of column namesdf.insert(loc = len(df.columns),          column = 'col1',          value = new_col)# show the dataframedf
Output:  
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Perl system Function

This function executes the command specified by PROGRAM, passing LIST as arguments to the command.
The return value is the exit status of the program as returned by the wait function. To obtain the actual exit value, divide by 256.
Following is the simple syntax for this function −
system PROGRAM, LIST

system PROGRAM

This function returns exit status of program as returned by wai
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

system("ls -F /var > /tmp/t.tmp");
When above code is executed, it produces the following result −
A file in /tmp directory, check it out.


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to Export the Azure VMs using PowerShell?

To export the azure VMs using PowerShell, we first need to get their desired properties. The cmdlet Get-AZVM will get all the VMs connected to the particular subscription. To export them to the CSV file we can use the below command.
Get-AzVM | Export-Csv .\AZVMs.csv -NoTypeInformation
Once you run the above command, you will notice that you get all the properties of the VM, and sometimes they are not needed. To get the particular properties of the VM use the Select-Object (alias Select) command.
Get-AzVM | Select Name, ResourceGroupName, Location, @{N='VMSize';E={$_.HardwareProfile.VmSize}} | Export-Csv .\AzureVms.csv -NoTypeInformation
If you want to export the VMs from a particular Resource group,
Get-AZVM -ResourceGroupName TestRG | Export-CSV .\TestRGVMs.csv -NoTypeInformation
When you add -Status Parameter in the Get-AzVM command, it shows the power state of the virtual machine.
Get-AzVM -Status | Export-Csv .\AZVMs.csv -NoTypeInformation
If you need VMs from another subscription, you can use Set-AZContext or Select-AZSubscription command to switch the subscription and then use any of the above commands to get the VM details in the CSV file.
CSS Rounded Corners

With the CSS border-radius property, you can give any element "rounded corners".
The CSS 
border-radius property defines the radius of an 
element's corners.
Tip: This property allows you to add rounded corners to 
elements!
Here are three examples:
1. Rounded corners for an element with a specified background color:
Rounded corners!
2. Rounded corners for an element with a border:
Rounded corners!
3. Rounded corners for an element with a background image:
Rounded corners!
Here is the code:
Tip: The border-radius property is actually a shorthand property for the 
border-top-left-radius, border-top-right-radius, border-bottom-right-radius 
and border-bottom-left-radius properties.
The border-radius property can have from one 
to four values. Here are the rules:
Four values - border-radius: 15px 50px 30px 5px; (first 
value applies to top-left corner, second value applies to top-right corner, 
third value applies to bottom-right corner, and fourth value applies to 
bottom-left corner): 
Three values - border-radius: 15px 50px 30px; (first value 
applies to top-left corner, second value applies to top-right and bottom-left 
corners, and third value applies to bottom-right corner):
Two values - border-radius: 15px 50px; (first value applies 
to top-left and bottom-right corners, and the second value applies to top-right 
and bottom-left corners):
One value - border-radius: 15px; (the value applies to all 
four corners, which are rounded equally:
Here is the code:
You could also create elliptical corners:
Give the div element rounded corners.
<style>
div {
  background: red;
  : 10px;  
}
</style>

<body>
  <div>This is a div element. It has some text.</div>
</body>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Python – reversed() VS [::-1] , Which one is faster?

20 Aug, 2020
Python lists can be reversed using many python method such as using slicing method or using reversed() function. This article discusses how both of these work and Which one of them seems to be the faster one and Why.
Code: Reversing a list using Slicing.
Python3
# Python code to reverse# a list using slicing  ls = [110, 220, 330,       440, 550]print('Original list :', ls)  # list reversels = ls[::-1]  print('Reversed list elements :')for element in ls:  print(element)
Output:
Original list : [110, 220, 330, 440, 550]
Reversed list elements :
550
440
330
220
110
Explanation : The format[a : b : c] in slicing states that from an inclusive to b exclusive, count in increments of c. In above code, a and b is blank and c is -1. So it iterates the entire list counting from the last element to the first element resulting in a reversed list.
Code: Reversing a list Using reversed() built-in function.
Python3
# Python code to reverse # a list using reversed()  ls = [110, 220, 330, 440, 550]print('Original list :', ls)  # list reversels = reversed(ls)print('Iterator object :', ls)  print('Reversed list elements :')for element in ls:  print(element)
Output: 
Original list : [110, 220, 330, 440, 550]
Iterator object : <list_reverseiterator object at 0x7fbd84e0b630>
Reversed list elements :
550
440
330
220
110
Explanation : The built-in reversed() function in Python returns an iterator object rather than an entire list.
For a comparatively large list, under time constraints, it seems that the reversed() function performs faster than the slicing method. This is because reversed() just returns an iterator that iterates the original list in reverse order, without copying anything whereas slicing creates an entirely new list, copying every element from the original list. For a list with 106 Values, the reversed() performs almost 20,000 better than the slicing method. If there is a need to store the reverse copy of data then slicing can be used but if one only wants to iterate the list in reverse manner, reversed() is definitely the better option.
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sort list of dictionaries by values in Python – Using lambda function

05 Jul, 2022
In this article, we will cover how to sort a dictionary by value in Python. 
Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can prove useful in such cases.
There are 2 ways to achieve this sorting:
 
This article deals with sorting using the lambda function and using the “sorted()” inbuilt function. Various variations can also be achieved for sorting the dictionaries. 
For descending order : Use “reverse = True” in addition to the sorted() function.
For sorting w.r.t multiple values: Separate by “comma” mentioning the correct order in which sorting has to be performed.
Example:
Python3
# Python code demonstrate the working of# sorted() with lambda # Initializing list of dictionarieslis = [{"name": "Nandini", "age": 20},       {"name": "Manjeet", "age": 20},       {"name": "Nikhil", "age": 19}] # using sorted and lambda to print list sorted# by ageprint("The list printed sorting by age: ")print(sorted(lis, key=lambda i: i['age'])) print("\r") # using sorted and lambda to print list sorted# by both age and name. Notice that "Manjeet"# now comes before "Nandini"print("The list printed sorting by age and name: ")print(sorted(lis, key=lambda i: (i['age'], i['name']))) print("\r") # using sorted and lambda to print list sorted# by age in descending orderprint("The list printed sorting by age in descending order: ")print(sorted(lis, key=lambda i: i['age'], reverse=True))
Output:
The list printed sorting by age: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]

The list printed sorting by age and name: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]

The list printed sorting by age in descending order: 
[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]
Next Article -> Ways to sort list of dictionaries by values in Python – Using itemgetter
shubham_singh
anshitaagarwal
amartyaghoshgfg
surajkumarguptaintern
Python dictionary-programs
python-dict
python-lambda
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Pattern CASE_INSENSITIVE field in Java with examples

This CASE_INSENSITIVE field of the Pattern class matches characters irrespective of case. When you use this as flag value to the compile() method and if you search for characters using regular expressions characters of both cases will be matched.
Note − By default, this flag matches only ASCII characters
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CASE_INSENSITIVE_Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input data: ");
      String input = sc.nextLine();
      System.out.println("Enter required character: ");
      char ch = sc.next().toCharArray()[0];
      //Regular expression to find the required character
      String regex = "["+ch+"]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("The letter "+ch+" occurred "+count+" times in the given text (irrespective of case)");
   }
}
Enter input data:
Tutorials Point originated from the idea that there exists a class 
of readers who respond better to online content and prefer to learn 
new skills at their own pace from the comforts of their drawing rooms.
Enter required character:
T
The letter T occurred 20 times in the given text (irrespective of case)
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.next();
      Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(str);
      if(matcher.matches()){
         System.out.println("Given string is a boolean type");
      } else {
         System.out.println("Given string is not a boolean type");
      }
   }
}
Enter a string value:
true
Given string is a boolean type
Enter a string value:
false
Given string is a boolean type
Enter a string value:
hello
Given string is not a boolean type
Python | Pandas Index.dtype

20 Feb, 2019
Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects.
Pandas Index.dtype attribute return the data type (dtype) of the underlying data of the given Index object.
Syntax: Index.dtype
Parameter : None
Returns : dtype
Example #1: Use Index.dtype attribute to find the dtype of the underlying data of the given Index object.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May'])  # Print the indexprint(idx)
Output :
Now we will use Index.dtype attribute to find the data type of the underlying data of the given series object.
# return the dtyperesult = idx.dtype  # Print the resultprint(result)
Output :
As we can see in the output, the Index.dtype attribute has returned object as the data type of the underlying data of the given Index object.
Example #2 : Use Index.dtype attribute to find the dtype of the underlying data of the given Index object.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index([100, 200, 142, 88, 124])  # Print the indexprint(idx)
Output :
Now we will use Index.dtype attribute to find the data type of the underlying data of the given series object.
# return the dtyperesult = idx.dtype  # Print the resultprint(result)
Output :
As we can see in the output, the Index.dtype attribute has returned int64 as the data type of the underlying data of the given Index object.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Sort List by Dictionary values

11 May, 2020
Sometimes while working with Python dictionary, we can have problem in which we need to perform a sort of list according to corresponding value in dictionary. This can have application in many domains, including data and web development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sorted() + key + lambdaThe combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(). The lambda function is used to get key’s values.
# Python3 code to demonstrate working of # Sort List by Dictionary values# Using sorted() + key + lambda  # initializing listtest_list = ['gfg', 'is', 'best']  # initializing Dictionarytest_dict = {'gfg' : 56, 'is' : 12, 'best' : 76}  # printing original listprint("The original list is : " + str(test_list))  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Sort List by Dictionary values# Using sorted() + key + lambdares = sorted(test_list, key = lambda ele: test_dict[ele])  # printing result print("The list after sorting : " + str(res)) 
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']

 
Method #2 : Using sorted() + key + get()This method performs the task in similar way as above method. The difference is that it accesses values get().
# Python3 code to demonstrate working of # Sort List by Dictionary values# Using sorted() + key + get()  # initializing listtest_list = ['gfg', 'is', 'best']  # initializing Dictionarytest_dict = {'gfg' : 56, 'is' : 12, 'best' : 76}  # printing original listprint("The original list is : " + str(test_list))  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Sort List by Dictionary values# Using sorted() + key + get()res = sorted(test_list, key = test_dict.get)  # printing result print("The list after sorting : " + str(res)) 
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']

Python list-programs
Python-sort
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 ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Name validation using IGNORECASE in Python Regex

29 Dec, 2020
In this article, we will learn about how to use Python Regex to validate name using IGNORECASE.
re.IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It’s passed as an optional argument to re.compile().
Let’s consider an example of a form where the user is asked to enter their name and we have to validate it using RegEx. The format for entering name is as follow:
Mr. or Mrs. or Ms. (Either one) followed by a single space
First Name, followed by a single space
Middle Name(optional), followed by a single space
Last Name(optional)
Examples:
Input : Mr. Albus Severus Potter 
Output : Valid

Input : Lily and Mr. Harry Potter
Output : Invalid
Note : Since, we are using IGNORECASE flag, the first character of First, Second, and Last name may or may not be capital.
Below is the Python code –
# Python program to validate name using IGNORECASE in RegEx  # Importing re packageimport re  def validating_name(name):      # RegexObject = re.compile( Regular expression, flag )    # Compiles a regular expression pattern into a regular expression object    regex_name = re.compile(r'^(Mr\.|Mrs\.|Ms\.) ([a-z]+)( [a-z]+)*( [a-z]+)*$',               re.IGNORECASE)      # RegexObject is matched with the desired     # string using search function    # In case a match is found, search() returns    # MatchObject Instance    # If match is not found, it return None    res = regex_name.search(name)      # If match is found, the string is valid    if res: print("Valid")              # If match is not found, string is invalid    else: print("Invalid")  # Driver Codevalidating_name('Mr. Albus Severus Potter')validating_name('Lily and Mr. Harry Potter')validating_name('Mr. Cedric')validating_name('Mr. sirius black')
Output:
Valid
Invalid
Valid
valid

Python Regex-programs
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
What is the difference between = (Assignment) and == (Equal to) operators

05 Apr, 2019
= operator
The “=” is an assignment operator is used to assign the value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';

Example:
// C program to demonstrate// working of Assignment operators  #include <stdio.h>  int main(){      // Assigning value 10 to a    // using "=" operator    int a = 10;    printf("Value of a is %d\n", a);      return 0;}
Value of a is 10

== operator
The ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false.For example:
5==5

This will return true.

Example:
// C program to demonstrate// working of relational operators#include <stdio.h>  int main(){    int a = 10, b = 4;      // equal to    if (a == b)        printf("a is equal to b\n");    else        printf("a and b are not equal\n");      return 0;}
a and b are not equal

The differences can be shown in tabular form as follows:
Operators
Difference Between
Programming Language
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.