code-rag-bench/online-tutorials huggingface dataset:
Calculate the sum of all columns in a 2D NumPy array - GeeksforGeeks

21 Jul, 2021
Let us see how to calculate the sum of all the columns in a 2D NumPy array.Method 1 : Using a nested loop to access the array elements column-wise and then storing their sum in a variable and then printing it.Example 1:  
Python3
# importing required librariesimport numpy # explicit function to compute column wise sumdef colsum(arr, n, m):    for i in range(n):        su = 0;        for j in range(m):            su += arr[j][i]        print(su, end = " ")    # creating the 2D ArrayTwoDList = [[1, 2, 3], [4, 5, 6],            [7, 8, 9], [10, 11, 12]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))
Output :  
2D Array:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

Column-wise Sum:
22 26 30 
Example 2 :  
Python3
# importing required librariesimport numpy # explicit function to compute column wise sumdef colsum(arr, n, m):    for i in range(n):        su = 0;        for j in range(m):            su += arr[j][i]        print(su, end = " ")    # creating the 2D ArrayTwoDList = [[1.2, 2.3], [3.4, 4.5]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))
Output :  
2D Array:
[[1.2 2.3]
 [3.4 4.5]]

Column-wise Sum:
4.6 6.8 
Method 2: Using the sum() function in NumPy, numpy.sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.Example 1 :  
Python3
# importing required librariesimport numpy # creating the 2D ArrayTwoDList = [[1, 2, 3], [4, 5, 6],            [7, 8, 9], [10, 11, 12]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")print(numpy.sum(TwoDArray, axis = 0))
Output :  
2D Array:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

Column-wise Sum:
22 26 30
Example 2 :  
Python3
# importing required librariesimport numpy # creating the 2D ArrayTwoDList =[[1.2, 2.3], [3.4, 4.5]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")print(*numpy.sum(TwoDArray, axis = 0))
Output :  
2D Array:
[[1.2 2.3]
 [3.4 4.5]]

Column-wise Sum:
4.6 6.8
 
adnanirshad158
Python numpy-arrayManipulation
Python numpy-Mathematical Function
Python-numpy
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Arithmetic Aptitude 4 - GeeksforGeeks

16 May, 2019
The required numbers are 27, 36, 45......450.

This is an A.P. with a = 27 and d = 9

Let it has n terms.

Then Tn = 450 = 27 + (n-1) x9

∴ 450 = 27+ 9n - 9

∴ 9n = 432

∴ n = 48
3, 9, 27, 81..............531441 form a G.P. 
with a = 3 and r = 9/3 = 3
Let the number of terms be n
Then 3 x 3n-1 = 531441
∴ 3n = 312
∴ n = 12
Given series is a G. P. with a = 7, r = 7 and n = 6

∴ Sn = a(rn-1) / (r-1)

∴ Sn = 7(76-1) / 6

  Sn = = 137256
Let the numbers be 2X and 9X
Then their H.C.F. is X, so X = 19
∴ Numbers are (2x19 and 9x19) i.e. 38 and 171
Let the no. of Rs. 500 note be X
Then the no. of Rs. 1000 note = 90 – X
∴ 500X + 1000(90 – X) = 71000
∴ 500X + 90000 – 1000X = 71000
∴ 500X = 19000
∴ X = 38
Let the numbers be x, x+2, x+4 and x+6
Then (x + x + 2 + x + 4 + x + 6)/4  = 12
∴ 4x + 12 = 48
∴ x = 9 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Hash Functions and list/types of Hash functions
How to Replace Values in a List in Python?
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
Count the specific value in a given vector in R - GeeksforGeeks

07 Apr, 2021
In this article, we will discuss how to find the specific value in a given vector in R Programming Language. For finding the frequency of a given value two approaches can be employed and both of them are discussed below.
We can iterate over the vector in R using a for loop and then check if the element is equivalent to the given value. A counter is maintained, and it is increased by 1, each time the value matches. In case, the element is not present, counter returns a value 0. The time complexity of the approach is O(n), where n is the size of the vector. 
Example:
R
# declaring a vectorvec = c(1,2,3,4,2,1,4,6)  # printing original vectorprint("Original Vectors:")print(vec)  # declaring count = 0 count = 0  # given valuex = 4  # looping over vector valuesfor( i in vec){        # check if the value is equal to x    if(vec[i]==x){                # increment counter by 1         count= count + 1    }}  print("Count given value in above vector:")  # check which values are equal to the given # value and calculate sum of itprint (count)
Output
[1] “Original Vectors:”
[1] 1 2 3 4 2 1 4 6
[1] “Count given value in above vector:”
[1] 2
The sum() method can be used to calculate the summation of the values appearing in the function argument. Here, we specify a logical expression as an argument of the sum() function which calculates the sum of values which are equivalent to the specified value. In case the value is not present, the sum method returns 0 as an output. The time complexity of the approach is O(n), where n is the size of the vector. 
Syntax:
sum(vec == given_val)  
where, vec is the vector and given_val is the given value to check the presence for in the vector. 
Example:
R
# declaring a vectorvec = c("a","g","a","y","s","a","abcs")  # printing original vectorprint("Original Vectors:")print(vec)  print("Count given value in above vector:")  # check which values are equal to the given # value and calculate sum of itprint(sum(vec=="a"))
Output
[1] “Original Vectors:”
[1] “a”    “g”    “a”    “y”    “s”    “a”    “abcs”
[1] “Count given value in above vector:”
[1] 3
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
Virtual vs Sealed vs New vs Abstract in C#

The virtual keyword allows a class to be overridden. For overriding a parent class method in the child class, declare the parent class method as virtual.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.
public sealed override void getResult() { }
Use the new keyword to hide the base class method from the derived class. This is done by declaring the derived class function with new. This is how new is used in Shadowing.
public new string getResult()

Abstract classes contain abstract methods, which are implemented by the derived class.
abstract class Vehicle
How to access and modify the values of a Tensor in PyTorch?

We use Indexing and Slicing to access the values of a tensor.Indexing is used to access the value of a single element of the tensor, whereasSlicing is used to access the values of a sequence of elements.
We use the assignment operator to modify the values of a tensor. Assigning new value/s using the assignment operator will modify the tensor with new value/s.
Import the required libraries. Here, the required library is torch.
Import the required libraries. Here, the required library is torch.
Define a PyTorch tensor.
Define a PyTorch tensor.
Access the value of a single element at particular index using indexing or access the values of sequence of elements using slicing.
Access the value of a single element at particular index using indexing or access the values of sequence of elements using slicing.
Modify the accessed values with new values using the assignment operator.
Modify the accessed values with new values using the assignment operator.
Finally, print the tensor to check if the tensor is modified with the new values.
Finally, print the tensor to check if the tensor is modified with the new values.
# Python program to access and modify values of a tensor in PyTorch
# Import the libraries
import torch

# Define PyTorch Tensor
a = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n",a)

# Access a value at index [1,0]-> 2nd row, 1st Col using indexing
b = a[1,0]
print("a[1,0]:\n", b)

# Other indexing method to access value
c = a[1][0]
print("a[1][0]:\n",c)

# Modifying the value 1 with new value 9
# assignment operator is used to modify with new value
a[1,0] = 9
print("tensor 'a' after modifying value at a[1,0]:")
print("a:\n",a)
a:
tensor([[3., 5.],
         [1., 2.],
         [5., 7.]])
a[1,0]:
   tensor(1.)
a[1][0]:
   tensor(1.)
tensor 'a' after modifying value at a[1,0]:
a:
tensor([[3., 5.],
         [9., 2.],
         [5., 7.]])
# Python program to access and modify values of a tensor in PyTorch
# Import necessary libraries
import torch

# Define PyTorch Tensor
a = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n", a)

# Access all values of 2nd row using slicing
b = a[1]
print("a[1]:\n", a[1])

# Access all values of 1st and 2nd rows
b = a[0:2]
print("a[0:2]:\n" , a[0:2])

# Access all values of 2nd col
c = a[:,1]
print("a[:,1]:\n", a[:,1])

# Access values from first two rows but 2nd col
print("a[0:2, 1]:\n", a[0:2, 1])

# assignment operator is used to modify with new value
# Modifying the values of 2nd row
a[1] = torch.Tensor([9, 9])
print("After modifying a[1]:\n", a)

# Modify values of first two rows but 2nd col
a[0:2, 1] = torch.Tensor([4, 4])
print("After modifying a[0:2, 1]:\n", a)
a:
tensor([[3., 5.],
         [1., 2.],
         [5., 7.]])
a[1]:
   tensor([1., 2.])
a[0:2]:
   tensor([[3., 5.],
         [1., 2.]])
a[:,1]:
   tensor([5., 2., 7.])
a[0:2, 1]:
   tensor([5., 2.])
After modifying a[1]:
   tensor([[3., 5.],
            [9., 9.],
            [5., 7.]])
After modifying a[0:2, 1]:
tensor([[3., 4.],
         [9., 4.],
         [5., 7.]])
Python SQLite - Drop Table

You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete.
Following is the syntax of the DROP TABLE statement in PostgreSQL −
DROP TABLE table_name;

Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −
sqlite> CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
sqlite> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, 
   SEX CHAR(1), INCOME FLOAT
);
sqlite>
Now if you verify the list of tables using the .tables command, you can see the above created tables in it ( list) as −
sqlite> .tables
CRICKETERS EMPLOYEE
sqlite>

Following statement deletes the table named Employee from the database −
sqlite> DROP table employee;
sqlite>

Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it.
sqlite> .tables
CRICKETERS
sqlite>

If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below −
sqlite> DROP table employee;
Error: no such table: employee
sqlite>

To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation.
sqlite> DROP table IF EXISTS employee;
sqlite>

You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table.
To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it.
import sqlite3

#Connecting to sqlite
conn = sqlite3.connect('example.db')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists
cursor.execute("DROP TABLE emp")
print("Table dropped... ")

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()
Table dropped...


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Linking External Style Sheets in CSS

CSS allows us to link external style sheets to our files. This helps us make changes to CSS separately and improves the page load time. External files are specified in <link> tag inside <head> of the document.
The syntax for including external CSS is as follows.
<link rel="stylesheet" href="#location">
The following examples illustrate how CSS files are embedded &miuns;
HTML file
 Live Demo
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Demo Text</h2>
<div>
<ul>
<li>This is demo text.</li>
<li>This is demo text.</li>
<li>This is demo text.</li>
<li>This is demo text.</li>
<li>This is demo text.</li>
</ul>
</div>
</body>
</html>
CSS file
h2 {
   color: red;
}
div {
   background-color: lightcyan;
}
This gives the following output −
HTML file
 Live Demo
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Demo Heading</h2>
<p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. </p>
</body>
</html>
CSS file
p {
   background: url("https://www.tutorialspoint.com/images/QAicon.png");
   background-origin: content-box;
   background-size: cover;
   box-shadow: 0 0 3px black;
   padding: 20px;
   background-origin: border-box;
}
This gives the following output −
ES7 - New Features

This chapter provides knowledge about the new features in ES7.
ES7 introduces a new mathematical operator called exponentiation operator. This operator is similar to using Math.pow() method. Exponentiation operator is represented by a double asterisk **. The operator can be used only with numeric values. The syntax for using the exponentiation operator is given below −
The syntax for the exponentiation operator is mentioned below −
base_value ** exponent_value

The following example calculates the exponent of a number using the Math.pow() method and the exponentiation operator.
<script>
   let base = 2
   let exponent = 3
   console.log('using Math.pow()',Math.pow(base,exponent))
   console.log('using exponentiation operator',base**exponent)
</script>
The output of the above snippet is as given below −
using Math.pow() 8
using exponentiation operator 8

The Array.includes() method introduced in ES7 helps to check if an element is available in an array. Prior to ES7, the indexof() method of the Array class could be used to verify if a value exists in an array . The indexof() returns the index of the first occurrence of element in the array if the data is found ,else returns -1 if the data doesn't exist.
The Array.includes() method accepts a parameter, checks if the value passed as parameter exists in the array. This method returns true if the value is found, else returns false if the value doesn't exist. The syntax for using the Array.includes() method is given below −
Array.includes(value)

OR
Array.includes(value,start_index)

The second syntax checks if the value exists from the index specified.
The following example declares an array marks and uses the Array.includes() method to verify if a value is present in the array.
<script>
   let marks = [50,60,70,80]
   //check if 50 is included in array
   if(marks.includes(50)){
      console.log('found element in array')
   }else{
      console.log('could not find element')
   }

   // check if 50 is found from index 1
   if(marks.includes(50,1)){ //search from index 1
      console.log('found element in array')
   }else{
      console.log('could not find element')
   }

   //check Not a Number(NaN) in an array
   console.log([NaN].includes(NaN))

   //create an object array
   let user1 = {name:'kannan'},
   user2 = {name:'varun'},
   user3={name:'prijin'}
   let users = [user1,user2]

   //check object is available in array
   console.log(users.includes(user1))
   console.log(users.includes(user3))
</script>
The output of the above code will be as stated below −
found element in array
could not find element
true
true
false


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
Program to make Indian Flag in Python

Python’s libraries to draw graphs has very extensive features which can not only give us charts but also give us flexibility to draw other diagrams like flags. In that sense those modules have an artistic touch. In this article we will see how to draw the Indian flag using the libraries numpy and matplotlib.
We create three rectangles of same width and draw them with appropriate colours and borders.
We create three rectangles of same width and draw them with appropriate colours and borders.
Use pyplot function to draw the circle of the Ashok Chakra at the center of the middle rectangle.
Use pyplot function to draw the circle of the Ashok Chakra at the center of the middle rectangle.
Use numpy and matplotlib to draw the 24 lines inside the Ashok Chakra.
Use numpy and matplotlib to draw the 24 lines inside the Ashok Chakra.
In all the above drawing we mention the colours, borders, radius and line lengths to match the requirement of the final size of the flag we need.
In all the above drawing we mention the colours, borders, radius and line lengths to match the requirement of the final size of the flag we need.
We implement the above approach using the following program.
import numpy as np
import matplotlib.pyplot as py
import matplotlib.patches as patch
#Plotting the tri colours in national flag
a = patch.Rectangle((0,1), width=12, height=2, facecolor='green', edgecolor='grey')
b = patch.Rectangle((0,3), width=12, height=2, facecolor='white', edgecolor='grey')
c = patch.Rectangle((0,5), width=12, height=2, facecolor='#FF9933', edgecolor='grey')
m,n = py.subplots()
n.add_patch(a)
n.add_patch(b)
n.add_patch(c)
#AshokChakra Circle
radius=0.8
py.plot(6,4, marker = 'o', markerfacecolor = '#000088ff', markersize = 9.5)
chakra = py.Circle((6, 4), radius, color='#000088ff', fill=False, linewidth=7)
n.add_artist(chakra)
#24 spokes in AshokChakra
for i in range(0,24):
   p = 6 + radius/2 * np.cos(np.pi*i/12 + np.pi/48)
   q = 6 + radius/2 * np.cos(np.pi*i/12 - np.pi/48)
   r = 4 + radius/2 * np.sin(np.pi*i/12 + np.pi/48)
   s = 4 + radius/2 * np.sin(np.pi*i/12 - np.pi/48)
   t = 6 + radius * np.cos(np.pi*i/12)
   u = 4 + radius * np.sin(np.pi*i/12)
   n.add_patch(patch.Polygon([[6,4], [p,r], [t,u],[q,s]], fill=True, closed=True, color='#000088ff'))
py.axis('equal')
py.show()
Running the above code gives us the following result −
How can I create a MySQL stored procedure that returns multiple values from a MySQL table?

We can create a stored procedure with both IN and OUT parameters to get multiple values from a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Bangalore  | Computers  |
+------+---------+------------+------------+
4 rows in set (0.01 sec)
Now, by creating the procedure named ‘select_studentinfo’ as follow, we can select the values from ‘student_info’ table by providing the value of ‘id’ −
mysql> DELIMITER // ;
mysql> Create Procedure Select_studentinfo ( IN p_id INT, OUT p_name varchar(20),OUT p_address varchar(20), OUT p_subject varchar(20))
    -> BEGIN
    -> SELECT name, address, subject INTO p_name, p_address, p_subject
    -> FROM student_info
    -> WHERE id = p_id;
    -> END //
Query OK, 0 rows affected (0.03 sec)
In the query above, along with 1 IN parameters, it is taking 4 OUT parameters also. Now, invoke the procedure with the values we want to provide as condition as follows −
mysql> DELIMITER ; //
mysql> CALL Select_studentinfo(110, @p_name, @p_address, @p_subject);
Query OK, 1 row affected (0.06 sec)

mysql> Select @p_name AS Name,@p_Address AS Address, @p_subject AS Subject;
+--------+------------+-----------+
| Name   | Address    | Subject   |
+--------+------------+-----------+
| Rahul  | Chandigarh | History   |
+--------+------------+-----------+
1 row in set (0.00 sec)
Python MongoDB - Introduction

Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python.
To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command.
C:\WINDOWS\system32>pip install pymongo
Collecting pymongo
Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl
Installing collected packages: pymongo
Successfully installed pymongo-3.9.0

Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py.
import pymongo

If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues.
D:\Python_MongoDB>test.py
D:\Python_MongoDB>


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
C program to print environment variables

Here, we will create a c program to print environment variables.
Environment variable is a global variable that can affect the way the running process will behave on the system.
//Program to print environment variables
 Live Demo
#include <stdio.h>
int main(int argc, char *argv[], char * envp[]){
   int i;
   for (i = 0; envp[i] != NULL; i++)
   printf("\n%s", envp[i]);
   getchar();
   return 0;
}
ALLUSERSPROFILE=C:\ProgramData
CommonProgramFiles=C:\Program Files\Common Files
HOMEDRIVE=C:
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=2a07
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
WATCOM=C:\watcom
windir=C:\Windows
Java program to split and join a string

To split and join a string in Java, use the split() and join() method as in the below example −
public class Demo{
   public static void main(String args[]){
      String my_str = "This_is_a_sample";
      String[] split_str = my_str.split("_", 4);
      System.out.println("The split string is:");
      for (String every_Str : split_str)
      System.out.println(every_Str);
      String joined_str = String.join("_", "This", "is", "a", "sample");
      System.out.println("The joined string is:");
      System.out.println(joined_str);
   }
}
The split string is:
This
is
a
sample
The joined string is:
This_is_a_sample
A class named Demo contains the main function. Here a String object is defined and it is split based on the ‘_’ value upto the last word. A ‘for’ loop is iterated over and the string is split based on the ‘_’ value. Again, the string is joined using the ‘join’ function. Relevant messages are displayed on the console.
PHP - Function eregi_replace()

string eregi_replace (string pattern, string replacement, string originalstring);

The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
After the replacement has occurred, the modified string will be returned.
After the replacement has occurred, the modified string will be returned.
If no matches are found, the string will remain unchanged.
If no matches are found, the string will remain unchanged.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
   $copy_date = "Copyright 2000";
   $copy_date = eregi_replace("([a-z]+)", "&Copy;", $copy_date);
   
   print $copy_date;
?>
This will produce the following result −

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Find average of a list in python?

Python provides sum function for calculating n number of element. Here we use this function and then calculate average.
Step 1: input “size of the list”
Step 2: input “Element”
Step 3: using sum function calculate summation of all numbers.
Step 4: calculate average.

# Average of a list
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(int(k))
sm=sum(A)
avg=sm/n
print("SUM = ",sm)
print("AVERAGE = ",avg)
Enter the size of the List ::5
Enter the number::
10
20
30
40
50
SUM = 150
AVERAGE = 30.0
Solidity - Conversions

Solidity allows implicit as well as explicit conversion. Solidity compiler allows implicit conversion between two data types provided no implicit conversion is possible and there is no loss of information. For example uint8 is convertible to uint16 but int8 is convertible to uint256 as int8 can contain negative value not allowed in uint256.
We can explicitly convert a data type to another using constructor syntax.
int8 y = -3;
uint x = uint(y);
//Now x = 0xfffff..fd == two complement representation of -3 in 256 bit format.
Conversion to smaller type costs higher order bits.
uint32 a = 0x12345678;
uint16 b = uint16(a); // b = 0x5678
Conversion to higher type adds padding bits to the left.
uint16 a = 0x1234;
uint32 b = uint32(a); // b = 0x00001234 
Conversion to smaller byte costs higher order data.
bytes2 a = 0x1234;
bytes1 b = bytes1(a); // b = 0x12
Conversion to larger byte add padding bits to the right.
bytes2 a = 0x1234;
bytes4 b = bytes4(a); // b = 0x12340000
Conversion between fixed size bytes and int is only possible when both are of same size.
bytes2 a = 0x1234;
uint32 b = uint16(a); // b = 0x00001234
uint32 c = uint32(bytes4(a)); // c = 0x12340000
uint8 d = uint8(uint16(a)); // d = 0x34
uint8 e = uint8(bytes1(a)); // e = 0x12
Hexadecimal numbers can be assigned to any integer type if no truncation is needed.
uint8 a = 12; // no error
uint32 b = 1234; // no error
uint16 c = 0x123456; // error, as truncation required to 0x3456

    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Java Examples - Implementation of Stack

How to implement stack ?
Following example shows how to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack.
public class MyStack {
   private int maxSize;
   private long[] stackArray;
   private int top;
   
   public MyStack(int s) {
      maxSize = s;
      stackArray = new long[maxSize];
      top = -1;
   }
   public void push(long j) {
      stackArray[++top] = j;
   }
   public long pop() {
      return stackArray[top--];
   }
   public long peek() {
      return stackArray[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
   public boolean isFull() {
      return (top == maxSize - 1);
   }
   public static void main(String[] args) {
      MyStack theStack = new MyStack(10); 
      theStack.push(10);
      theStack.push(20);
      theStack.push(30);
      theStack.push(40);
      theStack.push(50);
      
      while (!theStack.isEmpty()) {
         long value = theStack.pop();
         System.out.print(value);
         System.out.print(" ");
      }
      System.out.println("");
   }
}
The above code sample will produce the following result.
50 40 30 20 10

The following is an another sample to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack.
import java.util.*;

public class Demo {
   static void showpush(Stack stack1, int a) {
      stack1.push(new Integer(a));
      System.out.println("push(" + a + ")");
      System.out.println("stack: " + stack1);
   } 
   static void showpop(Stack stack1) {
      Integer a = (Integer) stack1.pop();
      System.out.println(a);
      System.out.println("stack: " + stack1);
   } 
   public static void main(String args[]) {
      Stack stack1 = new Stack();
      System.out.println("stack: " + stack1);
      showpush(stack1, 40);
      showpush(stack1, 50);
      showpush(stack1, 60);
      showpop(stack1);
      showpop(stack1);
      showpop(stack1);
      try {
         showpop(stack1);
      } catch (EmptyStackException e) {
         System.out.println("it Is Empty Stack");
      } 
   }
}
The above code sample will produce the following result.
stack: []
push(40)
stack: [40]
push(50)
stack: [40, 50]
push(60)
stack: [40, 50, 60]
60
stack: [40, 50]
50
stack: [40]
40
stack: []
it Is Empty Stack

 Print
 Add Notes
 Bookmark this page
Python program to extract Email-id from URL text file - GeeksforGeeks

29 Dec, 2020
Prerequisite : Pattern Matching with Python RegexGiven the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work.
Example :
Input : 
Hello
This is Geeksforgeeks
review-team@geeksforgeeks.org
contribute@geeksforgeeks.org
GfG is a portal for geeks
feedback@geeksforgeeks.org
careers@geeksforgeeks.org

Output :
[]
[]
['review-team@geeksforgeeks.org']
['contribute@geeksforgeeks.org']
[]
['feedback@geeksforgeeks.org']
['careers@geeksforgeeks.org']

 URL text file can be handled using urllib.request. For extracting the emails using regular expressions, re library can be used. For more details of Regular Expression, refer this.
# library that handles the URL stuffimport urllib.request  # Importing module required for# regular expressionsimport re  # Assign urlopen to a file object variablefhand = urllib.request.urlopen    ('https://media.geeksforgeeks.org/wp-content/uploads/e-mail-1.txt')  for line in fhand:    # Getting the text file    # content line by line.    s = line.decode().strip()      # regex for extracting all email-ids    # from the text file    reg = re.findall(r"[A-Za-z0-9._%+-]+"                     r"@[A-Za-z0-9.-]+"                     r"\.[A-Za-z]{2,4}", s)      # printing the list output    print(reg)
Output :
[]
[]
['review-team@geeksforgeeks.org']
['contribute@geeksforgeeks.org']
[]
['feedback@geeksforgeeks.org']
['careers@geeksforgeeks.org']
Python Regex-programs
python-regex
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
PYGLET – On Key Press Event - GeeksforGeeks

30 Jul, 2021
In this article we will see how we can trigger on key press event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A key on the keyboard was pressed (and held down). In pyglet 1.0 the default handler sets has_exit to True if the ESC key is pressed. Key press event is the major event to handle keyboard inputs.We can create a window with the help of command given below 
pyglet.window.Window(width, height, title)
Below is the syntax of the on key press event, this method get called when this event is triggered  :
@window.event       
def on_key_press(symbol, modifiers):
    print("Key is pressed")
Example : Below is the implementation
Python3
# importing pyglet moduleimport pygletimport pyglet.window.key  # width of windowwidth = 500  # height of windowheight = 500  # caption i.e title of the windowtitle = "Geeksforgeeks"  # creating a windowwindow = pyglet.window.Window(width, height, title)  # text text = "GeeksforGeeks"  # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text,                          font_name ='Times New Roman',                          font_size = 36,                          x = window.width//2, y = window.height//2,                          anchor_x ='center', anchor_y ='center')  new_label = pyglet.text.Label(text,                          font_name ='Times New Roman',                          font_size = 10,                          x = 25, y = 25)  # on draw event@window.eventdef on_draw():                # clearing the window    window.clear()          # drawing the label on the window    label.draw()        # key press event    @window.eventdef on_key_press(symbol, modifier):          print("Some key is pressed")          # key "C" get press    if symbol == pyglet.window.key.C:                  print("Key C is pressed")    # on hide event@window.eventdef on_hide():          # printing some message    print("Window is minimized")             # image for iconimg = image = pyglet.resource.image("logo.png")  # setting image as iconwindow.set_icon(img)                   # start running the applicationpyglet.app.run()
Output :  
Some key is pressed
Key C is pressed
 
varshagumber28
Python-gui
Python-Pyglet
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()
How to detect whether the website is being opened in a mobile device or a desktop in JavaScript ? - GeeksforGeeks

21 May, 2021
Using CSS Media Queries, we can easily know that a user is currently viewing our website in which device (using min-width and max-width). It is only limited to styling web pages, but we can control the functionality of the website according to the user’s device using the navigator userAgent Property in JavaScript.
We can get information about the user’s device. It returns a string containing the user browser’s name, version, operating system, etc.
Syntax:
navigator.userAgent 
Return Type: It returns the following string for a Windows desktop:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/90.0.4430.85 Safari/537.36
Example: Using this property, we can easily predict that it is opened on a Desktop or Mobile Device as shown in the below code.
HTML
<html><body>    <script>        /* Storing user's device details in a variable*/        let details = navigator.userAgent;          /* Creating a regular expression         containing some mobile devices keywords         to search it in details string*/        let regexp = /android|iphone|kindle|ipad/i;          /* Using test() method to search regexp in details        it returns boolean value*/        let isMobileDevice = regexp.test(details);          if (isMobileDevice) {            document.write("You are using a Mobile Device");        } else {            document.write("You are using Desktop");        }    </script></body></html>
Output: Following will be the output for desktop browser:
You are using Desktop
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider the following policies for preventing deadlock in a system with mutually exclusive resources.
I. Processes should acquire all their resources at the 
   beginning of execution.  If any resource is not  
   available, all resources acquired so far are released.
II. The resources are numbered uniquely, and processes are 
    allowed to request for resources only in increasing 
    resource numbers.
III. The resources are numbered uniquely, and processes are
     allowed to request  for resources only in decreasing 
     resource numbers.
IV. The resources are numbered uniquely. A process is allowed
    to request only for a resource with resource number larger
    than its currently held resources.
Which of the above policies can be used for preventing deadlock?(A) Any one of I and III but not II or IV(B) Any one of I, III and IV but not II(C) Any one of II and III but not I or IV(D) Any one of I, II, III and IVAnswer: (D)Explanation: If Ist is followed, then hold and wait will never happen.
II, III and IV are similar. If any of these is followed, cyclic wait will not be possible.Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Map of Vectors in C++ STL with Examples - GeeksforGeeks

16 Jan, 2020
Map in STL Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.
Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures.
Syntax:
map<key, vector<datatype>> map_of_vector;
OR
map<vector<datatype>, key> map_of_vector;

For example: Consider a simple problem where we have to check if a vector is visited or not.
// C++ program to demonstrate// use of map for vectors  #include <bits/stdc++.h>using namespace std;  map<vector<int>, int> vis;  // Print True if vector is visited// or False if not visitedvoid CheckVisited(vector<int> data){    if (vis.find(data) != vis.end()) {        cout << "True" << endl;    }    else {        cout << "False" << endl;    }}  // Driver codeint main(){    // Initializing some vectors    vector<int> data_1{ 10, 20, 30, 40 };    vector<int> data_2{ 5, 10, 15 };    vector<int> data_3{ 1, 3, 5, 7, 9, 11, 13 };      // Making some vectors as visited    vis[data_1] = 1;    vis[data_2] = 1;    vis[data_3] = 1;      // checking if these vectors are    // visited or not    vector<int> check_1 = { 5, 10, 15 };    vector<int> check_2 = { 2, 4, 6, 8, 10, 12 };      CheckVisited(check_1);    CheckVisited(check_2);      return 0;}
True
False

STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++
Sort the words in lexicographical order in Python

Sorting words in lexicographical order mean that we want to arrange them first by the first letter of the word. Then for the words whose first letter is the same, we arrange them within that group by the second letter and so on just like in a language's dictionary(not the data structure).
Python has 2 functions, sort and sorted for this type of order, let us look at how and when to use each of these methods.
In place sorting: when we want to sort the array/list in place, ie, changing the order in the current structure itself, we can use the sort method directly. For example,
my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
my_arr.sort()
print(my_arr)
This will give the output −
['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
As you can see here, the original array, my_arr has been modified. If you want to keep this array as it is and created a new array when sorting, you can use the sorted method. For example,
 Live Demo
my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)
# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)
This will give the output −
['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
['hello', 'apple', 'actor', 'people', 'dog']
As you can see here, the original array did not change.
Spring JDBC - Configure Data Source

Let us create a database table Student in our database TEST. I assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly.
CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);
Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code shown as follows −
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
   <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
   <property name = "username" value = "root"/>
   <property name = "password" value = "admin"/>
</bean>
In the next chapter, we'll write the first application using the database configured.
 Print
 Add Notes
 Bookmark this page
How to get sequence number in loops with JavaScript?

To get sequence number in loops, use the forEach() loop. Following is the code −
let studentDetails =
[
   {
      id: 101, details: [{name: 'John'}, {name: 'David'},{name: 'Bob'}]},
      {id:102, details: [{name:'Carol'},{name:'David'},
      {name:'Mike'}]
   }
];
var counter = 1;
studentDetails.forEach(function(k){
   k.details.forEach(function(f) {
         console.log(counter++);
      }
   );
});
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo159.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo159.js
1
2
3
4
5
6
How to implement MongoDB $or query?

The syntax is as follows for the $or query in MongoDB −
db.yourCollectionName.find({ $or : [ { "yourFieldName" : "yourValue1" }, {"yourFieldName":"yourValue2"},...........N ] } ).pretty();
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.orDemo.insertOne({"UserName":"Larry","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9491fd4cf1f7a64fa4df4c")
}
> db.orDemo.insertOne({"UserName":"David","UserAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9492074cf1f7a64fa4df4d")
}
> db.orDemo.insertOne({"UserName":"Mike","UserAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94920e4cf1f7a64fa4df4e")
}
> db.orDemo.insertOne({"UserName":"Sam","UserAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9492144cf1f7a64fa4df4f")
}
> db.orDemo.insertOne({"UserName":"Carol","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94921d4cf1f7a64fa4df50")
}
> db.orDemo.insertOne({"UserName":"Bob","UserAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94922c4cf1f7a64fa4df51")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.orDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"),
   "UserName" : "Larry",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c9492074cf1f7a64fa4df4d"),
   "UserName" : "David",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c94920e4cf1f7a64fa4df4e"),
   "UserName" : "Mike",
   "UserAge" : 25
}
{
   "_id" : ObjectId("5c9492144cf1f7a64fa4df4f"),
   "UserName" : "Sam",
   "UserAge" : 20
}
{
   "_id" : ObjectId("5c94921d4cf1f7a64fa4df50"),
   "UserName" : "Carol",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c94922c4cf1f7a64fa4df51"),
   "UserName" : "Bob",
   "UserAge" : 22
}
Here is the query for $or −
> db.orDemo.find({ $or : [ { "UserName" : "Carol" }, {"UserName":"Larry"} ] } ).pretty();
The following is the output:
{
   "_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"),
   "UserName" : "Larry",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c94921d4cf1f7a64fa4df50"),
   "UserName" : "Carol",
   "UserAge" : 24
}
How to display mean in a histogram using ggplot2 in R?

To display mean in a histogram using ggplot2, we can use geom_vline function where we need to define the x-intercept value as the mean of the column for which we want to create the histogram. Also, we can change the size of the line for mean in the histogram by using size argument inside geom_vline function.
Consider the below data frame −
x<-rnorm(20000)
df<-data.frame(x)
Loading ggplot2 package and creating histogram of x −
library(ggplot2)
ggplot(df,aes(x))+geom_histogram(bins=20)
Creating histogram of x with mean displayed on the plot −
ggplot(df,aes(x))+geom_histogram(bins=20)+geom_vline(aes(xintercept=mean(x),size=1))