code-rag-bench/online-tutorials huggingface dataset:
What is Python commit() method in MySQL?

The commit() method is one among the various methods in Python which is used to make the database transactions.
Here, we will discuss about the commit() method. The commit() method is used to confirm the changes made by the user to the database. Whenever any change is made to the database using update or any other statements, it is necessary to commit the changes. If we donot use the commit() method after making any changes to the database, the database will not not be updated and changes will not be reflected.
db.commit()
db refers to the database connection object.
Given below is an example to update value in a table and commit the changes to the database.
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
commit the changes made using commit() method
commit the changes made using commit() method
close the connection
close the connection
Suppose we have a table named “Student” as follows −
+----------+---------+-----------+------------+
|    Name  |   Class |    City   |    Marks   |
+----------+---------+-----------+------------+
|    Karan |    4    | Amritsar  |    95      |
|    Sahil |    6    | Amritsar  |    93      |
|    Kriti |    3    | Batala    |    88      |
|   Khushi |    9    | Delhi     |    90      |
|    Kirat |    5    | Delhi     |    85      |
+----------+---------+-----------+------------+
Suppose, we have the above table of students and we want to update the city of Kriti from Batala to Kolkata. And commit the changes to the database.
import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="UPDATE Students SET City='Kolkata' WHERE Name='Kriti'"
cursor.execute(query)
db.commit()

query="SELECT * FROM Students"
cursor.execute(query)

for row in cursor:
   print(row)
db.close()
The above code updates the city name of Kriti and commits this change to the database.
(‘Karan’, 4 ,’Amritsar’ , 95)
(‘Sahil’ , 6 , ‘Amritsar’ ,93)
(‘Kriti’ , 3 , ‘Kolkata’ ,88)
(‘Amit’ , 9 , ‘Delhi’ , 90)
(‘Priya’ , 5 , ‘Delhi’ ,85)
The db.commit() in the above code is important. It is used to commit the changes made to the table. Without using commit(), no changes will be made in the table.
How to convert more than one column in R data frame to from integer to numeric in a single line code?

To convert columns of an R data frame from integer to numeric we can use lapply function. For example, if we have a data frame df that contains all integer columns then we can use the code lapply(df,as.numeric) to convert all of the columns data type into numeric data type.
Consider the below data frame −
 Live Demo
set.seed(871)
x1<−sample(0:1,20,replace=TRUE)
x2<−sample(0:5,20,replace=TRUE)
x3<−sample(1:5,20,replace=TRUE)
x4<−sample(0:9,20,replace=TRUE)
x5<−sample(1:10,20,replace=TRUE)
df1<−data.frame(x1,x2,x3,x4,x5)
df1
x1 x2 x3 x4 x5
1 0 2 2 9 9
2 0 2 1 1 10
3 1 1 5 8 10
4 1 3 2 4 3
5 0 0 2 4 3
6 1 5 2 8 3
7 0 4 5 4 5
8 1 1 5 8 1
9 0 1 4 9 7
10 0 4 2 0 9
11 1 1 4 7 6
12 0 2 4 8 5
13 1 5 5 0 1
14 1 0 1 5 4
15 0 0 3 7 5
16 1 0 4 6 4
17 1 5 4 7 8
18 1 1 1 3 2
19 1 2 3 6 3
20 0 0 1 8 1
str(df1)
'data.frame': 20 obs. of 5 variables:
$ x1: int 0 0 1 1 0 1 0 1 0 0 ...
$ x2: int 2 2 1 3 0 5 4 1 1 4 ...
$ x3: int 2 1 5 2 2 2 5 5 4 2 ...
$ x4: int 9 1 8 4 4 8 4 8 9 0 ...
$ x5: int 9 10 10 3 3 3 5 1 7 9 ...
Converting columns of df1 to numeric −
df1<−lapply(df1,as.numeric)
str(df1)
List of 5
$ x1: num [1:20] 0 0 1 1 0 1 0 1 0 0 ...
$ x2: num [1:20] 2 2 1 3 0 5 4 1 1 4 ...
$ x3: num [1:20] 2 1 5 2 2 2 5 5 4 2 ...
$ x4: num [1:20] 9 1 8 4 4 8 4 8 9 0 ...
$ x5: num [1:20] 9 10 10 3 3 3 5 1 7 9 ...
 Live Demo
y1<−rpois(20,10)
y2<−rpois(20,8)
y3<−rpois(20,5)
y4<−rpois(20,2)
df2<−data.frame(y1,y2,y3,y4)
df2
y1 y2 y3 y4
1 9 10 4 3
2 6 9 4 0
3 7 9 3 4
4 4 3 6 1
5 9 7 2 4
6 17 4 7 2
7 6 5 7 0
8 3 5 5 4
9 12 6 7 5
10 15 10 4 2
11 6 3 5 2
12 9 10 6 0
13 6 8 6 2
14 11 6 4 2
15 9 7 3 5
16 12 7 3 3
17 18 9 8 4
18 7 5 3 5
19 14 4 7 4
20 17 8 8 3
str(df2)
'data.frame': 20 obs. of 4 variables:
$ y1: int 9 6 7 4 9 17 6 3 12 15 ...
$ y2: int 10 9 9 3 7 4 5 5 6 10 ...
$ y3: int 4 4 3 6 2 7 7 5 7 4 ...
$ y4: int 3 0 4 1 4 2 0 4 5 2 ...
Converting columns of df2 to numeric −
df2<−lapply(df2,as.numeric)
str(df2)
List of 4
$ y1: num [1:20] 9 6 7 4 9 17 6 3 12 15 ...
$ y2: num [1:20] 10 9 9 3 7 4 5 5 6 10 ...
$ y3: num [1:20] 4 4 3 6 2 7 7 5 7 4 ...
$ y4: num [1:20] 3 0 4 1 4 2 0 4 5 2 ...
 Live Demo
z1<−sample(21:30,20,replace=TRUE)
z2<−sample(1:50,20)
z3<−sample(101:200,20)
df3<−data.frame(z1,z2,z3)
df3
z1 z2 z3
1 29 32 130
2 27 26 149
3 22 11 199
4 30 28 161
5 21 36 174
6 29 8 152
7 23 23 142
8 27 22 114
9 24 45 135
10 21 34 171
11 28 40 125
12 24 42 148
13 21 43 106
14 25 1 137
15 26 7 118
16 22 2 184
17 28 4 192
18 24 38 183
19 27 31 168
20 21 3 185
str(df3)
'data.frame': 20 obs. of 3 variables:
$ z1: int 29 27 22 30 21 29 23 27 24 21 ...
$ z2: int 32 26 11 28 36 8 23 22 45 34 ...
$ z3: int 130 149 199 161 174 152 142 114 135 171 ...
Converting columns of df3 to numeric −
df3<−lapply(df3,as.numeric)
str(df3)
List of 3
$ z1: num [1:20] 29 27 22 30 21 29 23 27 24 21 ...
$ z2: num [1:20] 32 26 11 28 36 8 23 22 45 34 ...
$ z3: num [1:20] 130 149 199 161 174 152 142 114 135 171 ...
How to pass objects to functions in C++ Program?

There are four ways of passing objects to functions. Let's assume you have a class X and want to pass it to a function fun, then
This creates a shallow local copy of the object in the function scope. Things you modify here won't be reflected in the object passed to it. For example,
void fun(X x);
X x;
fun(x);
This passes a reference to the object to the function. Things you modify here will be reflected in the object passed to it. No copy of the object is created. For example,
void fun(X &x);
X x;
fun(x);
This passes a const reference to the object to the function. You cannot modify/reassign the object here directly(you can use its methods that do so though). This is useful if you want the function to have only a readonly copy of the object. No copy of the object is created. For example,
void fun(X const *x);
X x;
fun(&x);
This passes a const pointer to the object to the function. You cannot modify/reassign the pointer here. This is useful if you want the function to have only the address of this object in the pointer. No copy of object is created. For example,
void fun(X *x);
X x;
fun(&x);
This passes a pointer to the object to the function. This is similar to passing a reference to the object. No copy of object is created. For example,
<void fun(X *x);>
X x;
fun(&x);
Vue.js v-cloak Directive

07 Jun, 2022
The v-cloak directive is a Vue.js directive that will remain on the element until the associated Vue instance finishes compilation. Combined with CSS rules such as [v-cloak] { display: none }, this directive can be used to hide uncompiled mustache bindings until the Vue instance is ready. First, we will create a div element with id as app, and let’s apply the v-cloak directive to an element.
Syntax:
Template:
<element v-cloak>
    // content....
</element>
CSS:
[v-cloak] {
  display: none;
}
Parameters: This function doesn’t accept any parameter.
Example: This example uses Vue.js to show the working of the data with v-cloak so that it becomes visible only when the compilation completes.
HTML
<!DOCTYPE html><html> <head>     <!-- Load Vuejs -->    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">    </script>     <style>        [v-cloak] {            display: none;        }    </style></head> <body>    <div style="text-align: center;width: 600px;">                 <h1 style="color: green;">            GeeksforGeeks        </h1>        <b>            VueJS | v-cloak directive        </b>    </div>     <div id="canvas" style=            "border:1px solid #000000;            width: 600px;height: 200px;">         <div id="app" style=            "text-align: center;            padding-top: 40px;">            <h1 v-cloak>{{ data }}</h1>        </div>    </div>     <script>        var app = new Vue({            el: '#app',            data: {                data: 'GeeksforGeeks'            }        })    </script></body> </html>             
Output:
satyamm09
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create and fill a new column in an already created MySQL table?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.77 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values(20,30);
Query OK, 1 row affected (0.24 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |   10   |
|     20 |   30   |
+--------+--------+
2 rows in set (0.00 sec)
Following is the query to create and fill a new third column in a MySQL table. Here, boolean is considered as an integer in an integer context, i.e. the values 0 for false and 1 for true.
We have used generated column here −
mysql> alter table DemoTable add Value3 int generated always as (Value1 = Value2);
Query OK, 0 rows affected (0.51 sec)
Records: 0  Duplicates: 0  Warnings: 0
Let us display all records from the table once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     10 |   10   | 1      |
|     20 |   30   | 0      |
+--------+--------+--------+
2 rows in set (0.00 sec)
How to compile and run the C++ program?

Once you've got your compiler and source program ready, it is very easy to compile and run a C++ program. Assuming that you've installed GCC compiler, and you have a source.cpp file that you want to compile, follow the following instructions to compile and run it.
Step 1 − Open a new terminal window or cmd if you are on windows.
Step 2 − Change the directory to the directory in which you have your source.cpp file. For example, if it is in C:/Users/Dell/Documents, enter your command line −
$ cd 'C:/Users/Dell/Documents'
Step 3 − Now enter the following command to compile the source file using g++.
$ g++ -o <name-you-want-to-give> source.cpp
In place of <name-you-want-to-give> replace it by any name like myprogram, etc.
Step 4 − Run it! Now you can run the program using −
$ ./myprogram
How to add line border to JLabel in Java?

Use the createLineBorder() method to ad line border to JLabel −
Border border = BorderFactory.createLineBorder(Color.ORANGE);
label.setBorder(border);
Above, we have set the line border to color orange.
The following is an example to add line border to JLabel −
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import javax.swing.border.Border;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      label = new JLabel("Demo Label!", JLabel.RIGHT);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      Border border = BorderFactory.createLineBorder(Color.ORANGE);
      label.setBorder(border);
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}
Ruby | String end_with? Method - GeeksforGeeks

12 Dec, 2019
end_with? is a String class method in Ruby which is used to check if the specified string ends with one of the suffixes given or not.
Syntax: str.end_with?
Parameters: Here, str is the given string.
Returns: true if it matches otherwise return false.
Example 1:
# Ruby program to demonstrate # the end_with? method        # Taking a string and # using the methodputs "Ruby".end_with?("by") puts "String".end_with?("ab") 
Output:
true
false

Example 2:
# Ruby program to demonstrate # the end_with? method        # Taking a string and # using the method# returns true if one of# the +suffixes+ matches.puts "Sample".end_with?("ple", "sam")puts "Program".end_with?("gr", "pro") 
Output:
true
false

Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerator each_with_index function
Ruby | Types of Variables
Ruby For Beginners
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby Mixins
Ruby | Array shift() function
Ruby | Array collect() operation
Ruby | String concat Method
Ruby | unless Statement and unless Modifier
Ruby | Module
lsmod command in Linux with Examples - GeeksforGeeks

23 May, 2019
lsmod command is used to display the status of modules in the Linux kernel. It results in a list of loaded modules. lsmod is a trivial program which nicely formats the contents of the /proc/modules, showing what kernel modules are currently loaded.
Syntax:
lsmod
Example: Run lsmod at the command line to list all active kernel modules.
lsmod

Output:
Output Format: There are three columns in output.
First, column is used for ‘Name‘ of the module file. Or you can sayName = Module file name  -  Module file extension(eg .o or .ko)  

Name = Module file name  -  Module file extension(eg .o or .ko)  

Second, column is used for ‘size‘ of the module in Bytes.
The third column in output is for ‘used by‘. It is basically used to display the number of instances of the module which are used.
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
Tail command in Linux with examples
diff command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
How to update dependency in package.json file ?

27 Feb, 2020
In this article, we will discuss how to update the dependencies of a project with npm. You must have heard about npm which is called a node package manager. So, we can run this command to install an npm package.
npm install
Note: The –save flag is no longer needed after the Node 5.0.0 version.
The package gets installed and should be found in the node_modules folder in the same directory where package.json file exists. The entry of the package name with version should be found in package.json and package-lock.json. You can see the current version of the package in package.json file. You can find the latest version of the npm added in package.json file.
If you want to add a specific version you can run npm install @version_here like npm install react@^1.8.5
{
    "dependencies": {
        "react": "^1.8.5"
    }
}
If you want to add the latest version either you can run npm install or npm install @latest.
{
    "dependencies": {
        "react": "^16.12.0"
    }
}
By looking at those two files we got clear that we have version 16.12.0 of react and the rule for future updates is ^. This rule means that in future npm can only update to patch and minor releases.
In the future, if there will be a new patch or minor release and when we type the npm update command, the already installed version will get updated and package-lock.json will also get updated simultaneously by getting filled with the new version. It is clear that only package-lock.json file will get updated but not package.json.
To get the whole list of the new releases or outdated packages till now, we have to run this command
npm outdated
By running npm update it will not update the version of the major releases because major releases are never updated in this way because some of them might introduce the breaking changes in your live web app so npm don’t want to put in trouble.
For updating a new and major version of the packages, you must install the npm-check-updates package globally.
npm install -g npm-check-updates
After installing the package run the following command:
ncu
It will display the new dependencies in the current directory whereas running this command will list all the global packages which have new releases.
ncu -g
Now run this command:
ncu -u
After running this command it will result in the upgrading of all the version hints in the package.json file, so npm will install the major version by using this method.
Now everything is done. Just run the update command:
npm update
If you have a new project without any node_modules dependencies and you want to install the new version then run the following command:
npm install
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
dot (.) operator in C/C++

26 Nov, 2019
The dot (.) operator is used for direct member selection via object name. In other words, it is used to access the child object.
Syntax:
object.member;
For example:
#include <stdio.h>  struct Point {    int x, y;};  int main(){    struct Point p1 = { 0, 1 };      // Accessing members of point p1    // using the dot operator    p1.x = 20;      printf("x = %d, y = %d", p1.x, p1.y);      return 0;}
x = 20, y = 1

Is dot (.) actually an Operator?
Yes, dot (.) is actually an operator in C/C++ which is used for direct member selection via object name. It has the highest precedence in Operator Precedence and Associativity Chart after the Brackets.
Is there any other Operator like dot(.) operator?
Yes. There is another such operator (->). It is called as “Indirect member selection” operator and it has precedence just lower to dot (.) operator. It is used to access the members indirectly with the help of pointers.
Example:
void addXtoList(struct Node* node, int x){    while (node != NULL) {        node->data = node->data + x;        node = node->next;    }}
Can dot (.) operator be overloaded?
No, Dot (.) operator can’t be overloaded. Doing so will cause an error.
Example:
// C++ program to illustrate// Overloading this .(dot) operator  #include <iostream>using namespace std;  class cantover {public:    void fun();};  // assume that you can overload . operator// Class X below overloads the . operatorclass X {      cantover* p;      // Overloading the . operator    cantover& operator.()    {        return *p;    }      void fun();};  void g(X& x){      // Now trying to access the fun() method    // using the . operator    // But this will throw an error    // as we have overloaded the . operator above    // Hence compiler won't allow doing so    x.fun();}
Output:
prog.cpp:11:20: error: expected type-specifier before '.' token
  cantover& operator.() 
                    ^
prog.cpp:11:12: error: expected ';' at end of member declaration
  cantover& operator.() 
            ^
prog.cpp:11:20: error: expected unqualified-id before '.' token
  cantover& operator.() 
                    ^
prog.cpp: In function 'void g(X&)':
prog.cpp:15:7: error: 'void X::fun()' is private
  void fun(); 
       ^
prog.cpp:19:8: error: within this context
  x.fun(); // X::fun or cantover::fun or error? 
        ^

shubham_singh
C++-Operator Overloading
C-Operators
cpp-operator
cpp-operator-overloading
C Language
C++
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
What is the purpose of a function prototype?
Exception Handling in C++
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Lodash _.pick() Method

07 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 _.pick() method is used to return a copy of the object that is composed of the picked object properties.
Syntax:
_.pick( object, paths )

Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the source object.
paths: This parameter holds the property paths to pick.
Return Value: This method returns the new object.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source objectvar obj = {     Name: "GeeksforGeeks",     password: "gfg@1234",     username: "your_geeks"}  // Using the _.pick() method console.log(_.pick(obj, ['password', 'username']));
Output:
{password: "gfg@1234", username: "your_geeks"}

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source objectvar obj = { 'x': 1, 'y': '2', 'z': 3 };  // Using the _.pick() method console.log(_.pick(obj, ['x', 'y']));
Output:
{x: 1, y: '2'}

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to Calculate Rolling Correlation in Python?

29 Jan, 2022
Correlation generally determines the relationship between two variables. The rolling correlation measure the correlation between two-time series data on a rolling window Rolling correlation can be applied to a specific window width to determine short-term correlations. 
Let’s use sales data of two products A and B in the last 60 months to calculate the rolling correlation. Pandas package provides a function called rolling.corr() to calculate the rolling correlation.
Syntax:
data1.rolling(width).corr(data2)
Where, 
data1, data2 – data/column of interest (type series)
width – Rolling window width (int)
Note: The width of the rolling window should be 3 or greater in order to calculate correlations.
Data Used:  
Python3
# import pandas moduleimport pandas as pd # read the datadata = pd.read_csv('product_sales.csv') # display top 10 rowsprint(data.head(10)) # display column namesprint(data.columns)
Output:
Example 2:
Here, we used the window width of 6, which shows the successive 6 months rolling correlation. We could see a significant correlation between two products sales any sudden dip or rise in correlation signals an unusual event, that caused the dip.
Python3
data['Product A'].rolling(6).corr(data['Product B']) # formatting the outputk = 1for i, j in enumerate(data['Product A'].rolling(6).corr(data['Product B'])):    if (i >= 5 and i < 12):        print(f'The correlation in sales during months\        {k} through {i+1} is {j}')        i = 0        k += 1
Output:
Now’s let us try the same for 3-month correlation as shown below,
Example 3:
Python3
data['Product A'].rolling(3).corr(data['Product B']) # formatting the outputk = 1for i, j in enumerate(data['Product A'].rolling(3).corr(data['Product B'])):    if (i >= 3 and i < 12):        print(            f'The correlation in sales during months {k} \            through {i+1} is {j}')        i = 0        k += 1
Output:
clintra
Picked
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
HashMap values() Method in Java

26 Nov, 2018
The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap.
Syntax:
Hash_Map.values()
Parameters: The method does not accept any parameters.
Return Value: The method is used to return a collection view containing all the values of the map.
Below programs are used to illustrate the working of java.util.HashMap.values() Method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the values() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();          // Mapping string values to int keys        hash_map.put(10, "Geeks");        hash_map.put(15, "4");        hash_map.put(20, "Geeks");        hash_map.put(25, "Welcomes");        hash_map.put(30, "You");          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Using values() to get the set view of values        System.out.println("The collection is: " + hash_map.values());    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The collection is: [Geeks, Welcomes, Geeks, You, 4]

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the values() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Using values() to get the set view of values        System.out.println("The collection is: " + hash_map.values());    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The collection is: [15, 20, 30, 25]

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Initializing a List in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java
How to push elements in an array using AngularJS ?

14 Oct, 2020
Given an array and the task is to perform the push operation on array using AngularJS.
Approach: In this approach, the push() method is used to insert the element at the end of the array. In the first example, a static value ‘Geek’ is inserted in the array and in the second example a input box is provided to the user to push the value they want.
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.arr = ['GFG', 'GeeksForGeeks'];            $scope.val = "Geek";            $scope.push = function () {                $scope.arr.push($scope.val);            };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to push element in         array in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            value to push - "{{val}}"<br>            Array = {{arr}}<br><br>            <button ng-click='push()'>                Click to push            </button>        </div>    </div></body>  </html>
Output:
Example 2:
<!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.arr = ['GFG', 'GeeksForGeeks'];            $scope.push = function () {                // get the input value                var inputVal = $scope.arrInput;                $scope.arr.push(inputVal);              };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to push element in         array in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            Input here:            <input type="text"                 name="arrExample"                 ng-model="arrInput">                              <br><br>            Array = {{arr}}<br><br>            <button ng-click='push()'>                Click to push            </button>        </div>    </div></body>  </html>       
Output:
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to get the process id from Python Multiprocess?

27 Mar, 2021
In this article, we will see how to get the process id from Python Multiprocess For this we should make use of method multiprocessing.current_process() to get the multiprocess id.  Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken into smaller routines that run independently. The operating system allocates these threads to the processors improving the performance of the system.
Consider a computer system with a single processor. If it is assigned several processes at the same time, it will have to interrupt each task and switch briefly to another, to keep all the processes going.This situation is just like a chef working in a kitchen alone. He has to do several tasks like baking, stirring, kneading dough, etc.
Example 1:
First, we need to import a multiprocessing library in python.
Python3
# importing libraryimport multiprocessing  # define functiondef twos_multiple(y):          # get current process    print(multiprocessing.current_process())          return y * 2  pro = multiprocessing.Pool()  print(pro.map(twos_multiple, range(10)))
Output:
Example 2:
Multiprocessing will maintain an itertools.counter object for each and every process, which is used to generate an _identity tuple for any child processes it spawns and the top-level process produces child process with single-value ids, and they spawn process with two-value ids, and so on. Then, if no names are passed to the Process constructor, it simply autogenerates the name based on the _identity, using  ‘:’.join(...). Then Pool alters the name of the process using replace, leaving the autogenerated id the same.
The auto-generated names are unique. It will return the process object itself, there is a possibility of the process being its own identity.
The upshot of all this is that although two Processes may have the same name, because you may assign the same name to them when you create them, they are unique if you don’t touch the name parameter. Also, you could theoretically use _identity as a unique identifier; but I gather they made that variable private for a reason!
Python3
import multiprocessing  def twos_multiple(x):            proc = multiprocessing.Process()          curr_proc = multiprocessing.current_process()          print('current process:', curr_proc.name, curr_proc._identity)      print('created process:', proc.name, proc._identity)          return x * 2  pro = multiprocessing.Pool()  print(pro.map(twos_multiple, range(10)))
Output:
Picked
Python-multithreading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Landscape Layout in Android Studio?

22 Oct, 2020
In Android, whenever the user switches to landscape mode an issue is encountered in which some of the widgets become invisible (as you can see in the below image) and so in this scenario, there is a need to design a separate layout for the landscape mode. So in android, every application is designed in almost both the orientations i.e Portrait and Landscape. But by default Android Studio gives the option to design the application in Portrait mode but for Landscape mode, we need to create a Landscape Layout folder under the res folder. As per Android developer website guidelines, the name of this folder should be “layout-land”.
We are going to discuss two methods to create a landscape layout in android studio.
Step 1: If the project is already opened in the “Android” mode then change the project to “Project” mode as shown in the below image.
Step 2: Go to app > src > main > res > right-click > New > Android Resource Directory and one pop up will be prompted as shown below. Select Resource type as layout then go to Orientation and then click on the >> icon.
Step 3: Now in the Screen orientation select Landscape and the directory name automatically change to layout-land and let the Directory name as layout-land and don’t change it.
Step 4: Go to the layout-land > right-click > New > XML > Layout XML File and name the file. 
Step 5: Now cut the layout.xml file and paste it under the layout-land folder. Open the XML file and you will get the Landscape mode. 
If you want to redesign the activity_main.xml in Landscape mode then copy the activity_main.xml file from the layout folder to the layout-land folder. Please refer to this article to Design the Landscape and Portrait Mode of Application in Android. Refer to the following video to get the whole steps:
Method 2 is very easy to implement. In fact In Android Studio 3.x.x, there is no need to create an extra layout folder. There are only two steps to implement the method. 
Step 1: Open the base UI layout in DESIGN mode so that you see the actual GUI, such as Buttons, icons, etc. 
Step 2: Click the icon marked in the below screenshot and, from the menu, select Create Landscape Variation. Then the corresponding Landscape file will be created automatically named as land\xml file name.
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Navigation Drawer in Android
Android RecyclerView in Kotlin
How to Post Data to API using Retrofit in Android?
How to Create and Add Data to SQLite Database in Android?
Flutter - Custom Bottom Navigation Bar
CardView in Android With Example
Retrofit with Kotlin Coroutine in Android
How to Update Gradle in Android Studio?
GATE | GATE-CS-2014-(Set-1) | Question 33

28 Jun, 2021
Consider the following three statements about link state and distance vector routing protocols, for a large network with 500 network nodes and 4000 links.
[S1] The computational overhead in link state protocols 
     is higher than in distance vector protocols.
[S2] A distance vector protocol (with split horizon) 
     avoids persistent routing loops, but not a link
     state protocol.
[S3] After a topology change, a link state protocol 
     will converge faster than a distance vector
     protocol.
Which one of the following is correct about S1, S2, and S3 ?(A) S1, S2, and S3 are all true.(B) S1, S2, and S3 are all false.(C) S1 and S2 are true, but S3 is false(D) S1 and S3 are true, but S2 is falseAnswer: (D)Explanation:
Link-state:
Every node collects complete graph structure
Each computes shortest paths from it
Each generates own routing table

Distance-vector
No one has copy of graph
Nodes construct their own tables iteratively
Each sends information about its table to neighbors 
Source: http://www.cs.cmu.edu/~srini/15-441/S05/lectures/10-Routing.ppt
[S1] The computational overhead in link state protocols 
     is higher than in distance vector protocols.
[S2] A distance vector protocol (with split horizon) 
     avoids persistent routing loops, but not a link
     state protocol.
[S3] After a topology change, a link state protocol 
     will converge faster than a distance vector
     protocol.
S1 is clearly true as in Link State all nodes compute shortest path for whole network graph.
S3 is also true as Distance Vector protocol has count to infinity problem and converges slower.
S2 is false. In distance vector protocol, split horizon with poison reverse reduces the chance of forming loops and uses a maximum number of hops to counter the ‘count-to-infinity’ problem. These measures avoid the formation of routing loops in some, but not all, casesQuiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
How to check in C# whether the string array contains a particular work in a string array?

In C#, String.Contains() is a string method. This method is used to check whether the substring occurs within a given string or not.
It returns the boolean value. If substring exists in string or value is the empty string (“”), then it returns True, otherwise returns False.
Exception − This method can give ArgumentNullException if str is null.
This method performs the case-sensitive checking. The search will always begin from the first character position of the string and continues until the last character position.
Contains is case sensitive if the string is found it return true else false
static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   if (strs.Contains("sachin")){
      System.Console.WriteLine("String Present");
   } else {
      System.Console.WriteLine("String Not Present");
   }
   Console.ReadLine();
}
String Not Present
static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   if (strs.Contains("Sachin")){
      System.Console.WriteLine("String Present");
   } else {
      System.Console.WriteLine("String Not Present");
   }
   Console.ReadLine();
}
String Present
static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   var res = strs.Where(x => x == "Sachin").FirstOrDefault();
   System.Console.WriteLine(res);
   Console.ReadLine();
}
Sachin
static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   foreach (var item in strs){
      if (item == "Sachin"){
         System.Console.WriteLine("String is present");
      }
   }
   Console.ReadLine();
}
String is present
Python – Remove front column from Matrix

27 Dec, 2019
Sometimes, while working with Matrix data, we can have stray element that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + del + list slicingThe combination of above functionalities can be used to perform this task. In this, we run a loop for each row in matrix and remove the front element using del.
# Python3 code to demonstrate working of# Remove front column from Matrix# Using loop + del + list slicing  # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]]  # printing original list print("The original list : " + str(test_list))  # Remove front column from Matrix# Using loop + del + list slicingfor ele in test_list: del ele[0]   # printing resultprint("Matrix after removal of front column : " + str(test_list))
The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
Matrix after removal of front column : [[3, 4], [4, 6], [8, 1]]

 
Method #2 : Using list comprehension + list slicingThe combination of above functions can also be used to perform this task. In this, we just iterate for each row and delete front element using list slicing.
# Python3 code to demonstrate working of# Remove front column from Matrix# Using list comprehension + list slicing  # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]]  # printing original list print("The original list : " + str(test_list))  # Remove front column from Matrix# Using list comprehension + list slicingres = [ele[1:] for ele in test_list]  # printing resultprint("Matrix after removal of front column : " + str(res))
The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
Matrix after removal of front column : [[3, 4], [4, 6], [8, 1]]

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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
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 Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
TreeSet in Java

TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order. It contains only unique elements and the access & retrieval is quick.
Following is the list of the constructors supported by the TreeSet class.
Let us now see an example to work with TreeSet class −
import java.util.*;
public class Main {
   public static void main(String args[]) {
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("John");
      ts.add("Kevin");
      ts.add("Amy");
      ts.add("Ryan");
      ts.add("Katie");
      ts.add("Tom");
      System.out.println(ts);
   }
}
[Amy, John, Katie, Kevin, Ryan, Tom]
Let us now see another example wherein we are checking for the existence of an element in the TreeSet −
import java.util.*;
public class Main {
   public static void main(String args[]) {
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("John");
      ts.add("Kevin");
      ts.add("Amy");
      ts.add("Ryan");
      ts.add("Katie");
      ts.add("Tom");
      Iterator<String> i = ts.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      System.out.println("The Set has element 'Jacob'? = " +
      ts.contains("Jacob"));
      System.out.println("The Set has element 'Ryan'? = " +
      ts.contains("Ryan"));
   }
}
Amy
John
Katie
Kevin
Ryan
Tom
The Set has element 'Jacob'? = false
The Set has element 'Ryan'? = true
Python | Remove multiple keys from dictionary

19 Jul, 2019
While working with Python dictionaries, we can have utility in which we require to remove more than one keys at once. This type of problem can occur while working in Web Development domain with NoSQL Databases. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using pop() + list comprehensionIn this method, we just use the pop function which is used to remove a single key along with the list comprehension which iterates for the entire list to perform the remove operation.
# Python3 code to demonstrate working of# Remove multiple keys from dictionary# Using pop() + list comprehension  # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}  # initializing Remove keysrem_list = ['is', 'for', 'CS']  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using pop() + list comprehension# Remove multiple keys from dictionary[test_dict.pop(key) for key in rem_list]  # printing result print("Dictionary after removal of keys : " + str(test_dict))
The original dictionary is : {‘is’: 2, ‘best’: 3, ‘for’: 4, ‘Gfg’: 1, ‘CS’: 5}Dictionary after removal of keys : {‘best’: 3, ‘Gfg’: 1}
 
Method #2 : Using items() + list comprehension + dict()In this method, rather than removal of keys, we reconstruct the dictionary using the dict function, by extracting key and value pairs using items() and iterating over them using list comprehension.
# Python3 code to demonstrate working of# Remove multiple keys from dictionary# Using items() + list comprehension + dict()  # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}  # initializing Remove keysrem_list = ['is', 'for', 'CS']  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using items() + list comprehension + dict()# Remove multiple keys from dictionaryres = dict([(key, val) for key, val in            test_dict.items() if key not in rem_list])  # printing result print("Dictionary after removal of keys : " + str(res))
The original dictionary is : {‘is’: 2, ‘best’: 3, ‘for’: 4, ‘Gfg’: 1, ‘CS’: 5}Dictionary after removal of keys : {‘best’: 3, ‘Gfg’: 1}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to delay a loop in JavaScript using async/await with Promise ?

10 Sep, 2021
Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either by web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScript. All we have in JavaScript is setTimeout() function, but this is not what we look for when we have a bulk of code to execute after some delay, as a result there come conflicts in linear execution of code in JavaScript. Here we found a proper asynchronous way to pause a loop for specific time as we used to do in C++ or C.
What is async and await?
Async and await make promises easier to write. The async keyword makes a function return a promise : async keyword is mainly used while declaring a function.
Syntax:
async function delay() {
    return new Promise(resolve => {resolve()})
}
await makes a function wait for a Promise: await is mainly used while calling a function.
Syntax:
await delay();
Approach: The Promise actually does is that it traps the program execution inside it until it doesn’t get resolved, and when it gets resolved after some time period it gives control back to the main method from where it was called.
Here, waitforme function is the actual function which helps us in delaying the code which accepts one argument as millisecond, which allows user to delay code for a duration of his/her choice.
To understand Promises in deep you should visit:  https://www.geeksforgeeks.org/javascript-promises
You can directly copy and paste the code below to the console and check it or you can create separate JavaScript file and load it in chrome or try it in Node.js
Example:
Javascript
function waitforme(milisec) {    return new Promise(resolve => {        setTimeout(() => { resolve('') }, milisec);    })} async function printy() {    for (let i = 0; i < 10; ++i) {        await waitforme(1000);        console.log(i);    }    console.log("Loop execution finished!)");} printy();
 
 
Output:
 
 
Note: We can change the value of parameter of waitforme function while calling the function to increase/decrease the delay in the code.
 
gabaa406
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.