code-rag-bench/online-tutorials huggingface dataset:
TestNG - HTML and XML Reports

TestNG comes with certain predefined listeners as part of the library. These listeners are by default added to any test execution and generate different HTML and XML reports for any test execution. The report is generated by default under the folder named testoutput and can be changed to any other folder by configuring it. These reports consist of certain HTML and XML reports that are TestNG specific.
Create a java class, say, SampleTest.java in /work/testng/src.
import org.testng.Assert;
import org.testng.annotations.Test;

public class SampleTest {
   @Test
   public void testMethodOne() {
      Assert.assertTrue(true);
   }

   @Test
   public void testMethodTwo() {
      Assert.assertTrue(false);
   }

   @Test(dependsOnMethods = {"testMethodTwo"})
   public void testMethodThree() {
      Assert.assertTrue(true);
   }
}
The preceding test class contains three test methods out of which testMethodOne and testMethodThree will pass when executed, whereas testMethodTwo is made to fail by passing a false Boolean value to the Assert.assertTrue method, which is used for truth conditions in the tests.
Create testng.xml in /work/testng/src to execute test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<suite name = "Simple HTML-XML Suite">

   <test name = "Simple HTML-XML test">
      <classes>
         <class name = "SampleTest" />
      </classes>
   </test>
</suite>
Compile the SampleTest class using javac.
/work/testng/src$ javac SampleTest.java
Now, run the testng.xml.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
===============================================
   Simple HTML-XML Suite
   Total tests run: 3, Failures: 1, Skips: 1
===============================================

Now, go to the /work/testng/src/test-output folder. Open the index.html on your default web browser. You will see the following HTML report −
Now, open the file /work/testng/src$/test-output/testing-results.xml in the default XML editor on your system, and you will see the following content in the XML file −
TestNG, by default, generates multiple reports as part of its test execution. These reports mainly include TestNG HTML report, TestNG email-able report, TestNG report XML, and JUnit report XML files. These files can be found under the output report folder (in this case, test-output).
This default report generation can be disabled while running the tests by setting the value of the property useDefaultListeners to false. This property can be set while using build tools like Ant or Maven.

    38 Lectures 
     4.5 hours 

 Lets Kode It

    15 Lectures 
     1.5 hours 

 Quaatso Learning

    28 Lectures 
     3 hours 

 Dezlearn Education
 Print
 Add Notes
 Bookmark this page
How to provide & remove user access to/from DB2 object? Give the DB2 commands?

DB2 has a concept of DCL, through which we can control the access to DB2 objects like table, plan, etc. DCL stands for Data Control Language and using this we can provide and remove user access to the DB2 objects.
GRANT command will give the user access to the mentioned object and REVOKE command will remove the user access.
For example, if we have to provide SELECT and UPDATE access on the ORDERS table to user REL123X then we will fire below command.
GRANT SELECT, UPDATE ON ORDERS TO REL123X
If we want to provide INSERT access, then we will use the below command.
GRANT INSERT ON ORDERS TO REL123X
If we want to revoke all the access on the ORDERS table for user REL123X then we will use the below command.
REVOKE ALL ON ORDERS FROM REL123X
If we want to revoke UPDATE access on the ORDERS table for user REL123X then we will use the below command.
REVOKE UPDATE ON ORDERS FROM REL123X
If we want to revoke INSERT access on the ORDERS table for user REL123X then we will use the below command.
REVOKE INSERT ON ORDERS FROM REL123X
The important point to note here is that not all users of DB2 can execute the Data control language (DCL) GRANT and REVOKE statement. We need special DBA privileges on our userid to use DCL statements. In a real world scenario, there is a dedicated team which provides access to the database objects based on the roles assigned to the individuals.
Maximum weight path ending at any element of last row in a matrix in C++

In this problem, we are given an integer n and a matrix of size n X n which contains the weight of the cell. Our task is to create a program that will find the maximum weight path ending at any element of the last row in a matrix. While finding the path the traversal will start from top-left (0,0) and the valid moves will be down and diagonal, no left move is allowed.
Let’s take an example to understand the problem,
Input −
n = 3
Mat[3][3] ={
   {4, 3, 1}
   {5, 8, 9}
   {6, 7, 2}}
Output  −
19
Explanation −
All paths that can be used will be
Path1: 4+5+6 = 15
Path2: 4+8+7 = 19
Path3: 4+8+2 = 12
Path4: 4+5+7 = 16
As out of these the best possible path is path2 with weight 19
So, one possible solution can be calculating all paths and then compare them, but this will be an inefficient approach when n large number.
An effective solution will be using dynamic programming as this is a type of overlapping problem. Starting from the root their are n branches that can provide the desired result.
We will create a matrix that will store the maximum weight of the given paths that are traversed to reach that cell in the matrix.
This we will which is the maximum sum in the last row of the matrix and print it.
Program to solve the problem,
 Live Demo
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
int maxCost(int matrix[][MAX], int N) {
   int sumMat[N][N];
   memset(sumMat, 0, sizeof(sumMat));
   int maxSum = 0;
   sumMat[0][0] = matrix[0][0];
   for (int i=1; i<N; i++)
      sumMat[i][0] = matrix[i][0] + sumMat[i-1][0];
   for (int i=1; i<N; i++)
   for (int j=1; j<i+1&&j<N; j++)
      sumMat[i][j] = matrix[i][j] + max(sumMat[i-1][j-1], sumMat[i-1][j]);
   for (int i=0; i<N; i++)
      if (maxSum < sumMat[N-1][i]) maxSum = sumMat[N-1][i];
      return maxSum;
}
int main(){
   int mat[MAX][MAX] ={
      {5 , 6 , 1 },
      {2 , 11 , 10 },
      {15, 3 , 2 }};
   int N = 3;
   cout<<"Maximum Path Sum for top-left cell to last row is : "<<maxCost(mat, N)<<endl;
   return 0;
}
Maximum Path Sum for top-left cell to last row is : 22
Python program to Count the Number of occurrences of a key-value pair in a text file - GeeksforGeeks

29 Dec, 2020
Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file.
Examples:
Input File:
Coin:H
Coin:T
Coin:H
Coin:H
Coin:H
Coin:T
Coin:H
Coin:T
Coin:H
Coin:H

Output:
The count of coin:h is 7
The count of coin:t is 3

Input File:
geeks:G
for:F
geeks:G
geeks:G
geek:H
for:F
geek:H

Output:
The count of geeks:g is 3
The count of for:f is 2
The count of geek:h is 2

The approach is very simple. Maintain another dictionary (say d) that will store the count of occurrence of each key-value pair of the file. Store the key-value pair of the text file as a key in the dictionary. Now iterate through the key-value pairs of the file. If the pair is present in the dictionary then increment the value of that pair by one otherwise insert the pair and set its value to one.
Below is the implementation.
Text file:
# Python program to count the# occurrences of key-value pair# in the text file    # opening text filef = open("file.txt", "r")d = dict()  for res in f:    # removing new line and extra    # space characters    res = res.strip()      # changing ase to prevent matching    # errors    res = res.lower()      # separating key-value pairs    lines = res.split()      for line in lines:          if line in d:              # If the key-value pair            # is present in d then             # increment its value by one            d[line] = d[line]+1        else:              # Insert the key-value pair            # in the dictionary and sets            # its value to one            d[line] = 1  f.close()  # Printing Resultfor key in list(d.keys()):    print("The count of {} is {}".format(key,d[key]))
Output :
Python dictionary-programs
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
What is init.d in Linux Service Management? - GeeksforGeeks

28 Nov, 2021
In Linux there are several services that can be started and stopped manually in the system, some of their services are ssh, HTTP, tor, apache, etc. To start and run these services we used to simply type 
service "service name" start/stop/status/restart
Example:  
service ssh start
And to check if this service is running we type the command  
service ssh status
In this simple manner, we are using service management in Linux but what actually happens and how it actually works in the background. 
All these service works on several scripts and these scripts are stored in /etc/init.d location, this init.d is a daemon which is the first process of the Linux system. Then other processes, services, daemons, and threads are started by init. So init.d is a configuration database for the init process. Now let’s check some daemon scripts by printing some processes, a daemon script holds functions like start, stop, status and restart. Let’s check ssh as an example. 
cat /etc/init.d/ssh
Output: 
Now to you know about the daemon script lets also check what is inside of init.d directory, to do this we will simply list out all the fines inside the location 
ls /etc/init.d/
Output: 
 
We used to type simple command service ssh start. But now, in this case, we will do it the other way which is also simple.  
/etc/init.d/ssh start
and the same way you can stop  
/etc/init.d/ssh stop
sumitgumber28
coderdildillip
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
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
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Python - Substring concatenation by Separator - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python Lists, we can have problem in which we need to perform the concatenation of strings in a list till the separator. This can have application in domains in which we need chunked data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we perform the task of joining in loop conditional statements and re initialize string to empty on separator occurrence.
# Python3 code to demonstrate working of # Substring concatenation by Separator# Using loop  # initializing listtest_list = ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']  # printing original listprint("The original list is : " + str(test_list))  # initializing K K = '*'  # Substring concatenation by Separator# Using loopres = []temp = ''for sub in test_list:    if sub != '*':        temp += sub    else:        res.append(temp)        temp = ''if temp:    res.append(temp)  # printing result print("The list after String concatenation : " + str(res)) 
The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']

 
Method #2 : Using join() + split() + list comprehensionThe combination of above functions can be used to perform this task. In this, we perform the task of concatenation using join(). The list construction is done using list comprehension.
# Python3 code to demonstrate working of # Substring concatenation by Separator# Using join() + split() + list comprehension  # initializing listtest_list = ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']  # printing original listprint("The original list is : " + str(test_list))  # initializing K K = '*'  # Substring concatenation by Separator# Using join() + split() + list comprehensionres = [ele for ele in ''.join(test_list).split(K) if ele]  # printing result print("The list after String concatenation : " + str(res)) 
The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Node.js GM minify() Function - GeeksforGeeks

11 Oct, 2021
The minify() function is an inbuilt function in the GraphicsMagick library which is used to minify the image. The function returns the true value on success.
Syntax:
minify( factor )
Parameters: This function accepts single parameter as mentioned above and described below:
factor: This parameter is used to specify the factor by which the image need to be minify.
Return Value: This function returns the GraphicsMagick object.
Example 1:
// Include gm libraryvar gm = require('gm');  // Import the imagegm('1.png')  // Invoke borderColor() function// and set border color to green.borderColor('Green')  // Invoke resize function.border(10, 30)  // Invoke minify function.minify(3)  // Process and Write the image.write("minify1.png", function (err) {  if (!err) console.log('done');});
Output:
Example 2:
// Include gm libraryvar gm = require('gm');  //Import the imagegm(600, 300, 'white')  // set the color for the stroke.stroke("green", 3)  // Set the font .font("Helvetica.ttf", 60)  // Call to drawText Function.drawText(100, 280, "GeeksforGeeks!")  // Invoke borderColor() function// and set border color to green.borderColor("Green")  // Invoke border function.border(62, 32)  // Invoke minify() function.minify(2)  // Process and write the image .write("minify2.png", function (err) {  if (!err) console.log('done');});
Output:
Reference:
http://www.graphicsmagick.org/GraphicsMagick.html
https://www.npmjs.com/package/gm
Image-Processing
Node.js-GM
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
How to connect Node.js with React.js ?
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Arc Testing

Arc Testing is nothing but branch testing. A Branch is the outcome of a decision. So branch coverage is a measure of outcomes of a branch. Determining the number of branches in a method is easy as a the output of a branch has usually two outcomes (True of False).
Branch testing focusses on executing each condition in a decision in order to test all possible outcomes at least once. Every branch (decision) taken each way, true and false. It helps in validating all the branches in the code making sure that no branch leads to abnormal behaviour of the application. More on Branch coverage is covered in Branch Testing chapter.
Decision Coverage=(Number of decision outcomes executed/Total number of decision outcomes)*100%

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
Difference between Abstract and Concrete Data Structure - GeeksforGeeks

15 Jun, 2021
In this article we will discuss the differences between Abstract and Concrete data structure or type.
Abstract Data Types(ADT) : It is a type (or class) of objects whose behaviour is defined by a set of values and a set of operations. The user interacts with the interface, using the operations that have been specified by the abstract data type. It offers a high level use of a concept independent of it’s implementation. They  package data structure and operations on them hiding internal details.
Examples –Use a class with private data and public functions to represent the record.
public class date
{
 private int day;
 private string  month;
 private int year;
};
public  void increment ()
{
 return day;
}
Concrete Data Types(CDT) : A concrete data type is the opposite of an abstract data type. It is a specialized solution-oriented data type that represents a well-defined single solution domain concept. A concrete data type is rarely reusable beyond its original use, but can be embedded or composed with other data types to form larger data types. They are direct implementations of a relatively simple concept. It does not hide anything. 
Examples – Use a struct with public data and no functions to represent the record 
struct  date
{
 int day;
 string month;
 int year;
};
Difference Between Class And Object :There are many differences between object and class. Some differences between object and class are given below:
Abstract Data Types or structure (ADT)
Concrete Data Types or structure (CDT)
Picked
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Preemptive and Non-Preemptive Scheduling
Phases of a Compiler
Introduction of Process Synchronization
Differences between IPv4 and IPv6
Three address code in Compiler
Third Normal Form (3NF)
Difference between Internal and External fragmentation
Hamming Code in Computer Network
Second Normal Form (2NF)
C Program to find IP Address, Subnet Mask & Default Gateway

C programming language can be used to find the details of the Internet connection of the system. Now, let’s learn about the basics terms that we need in this problem.
IP Address − IP Address stands for Internet Protocol address. An IP address is a fixed numerical identification number that is associated with each device. IP address allows communication of your device using IP address over the internet.
Subnet Mask − A 32-bit component of the IP address. The subnet mask differentiates the network component of IP address into two parts of the IP address. One being network address and other being a network address. Subnet is the number that is design subs that connect to the networks and complete the IP address of the system connected to the network.
Default Gateway − It is an access point or IP router of a computer that is connected to the network. This default gateway is the gateway that is defined by the computer by default until any other mask gateway is used by an application. This gateway is the connecting route of the network of the systems to the rest of the internet. Failure of this network may disconnect the subnetwork to the internet.
Now, as we have learned all statements related to our work. We now can use code snippets and programs to display these things.
In C programming language there are two methods that can be used in order to check the IP’s of the system.
System command
Excel command
C programming language provides system() function in stdlib library that can be used to excess the ip configuration of the system using ipcofig. In the call of the function we will pass the full address of the ipconfig file that is needed to be extracted.
#include <stdio.h>
#include <stdlib.h>
int main(){
   system("c:\\windows\\system32\\ipconfig");
   return 0;
}
Another way to fetch the IP details of the system is by using the excel() function. This function needs more than one parameter as in the code.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
   execl("c:\\windows\\system32\\ipconfig", "ipconfig", 0);
   return 0;
}
The output of these codes depends on the system. IP details of a system are confidential so the outputs are not displayed here but you can run the code and your system to display details.
Java - FileWriter Class

This class inherits from the OutputStreamWriter class. The class is used for writing streams of characters.
This class has several constructors to create required objects. Following is a list.
FileWriter(File file)
This constructor creates a FileWriter object given a File object.
FileWriter(File file, boolean append)
This constructor creates a FileWriter object given a File object with a boolean indicating whether or not to append the data written.
FileWriter(FileDescriptor fd)
This constructor creates a FileWriter object associated with the given file descriptor.
FileWriter(String fileName)
This constructor creates a FileWriter object, given a file name.
FileWriter(String fileName, boolean append)
This constructor creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Once you have FileWriter object in hand, then there is a list of helper methods, which can be used to manipulate the files.
public void write(int c) throws IOException
Writes a single character.
public void write(char [] c, int offset, int len)
Writes a portion of an array of characters starting from offset and with a length of len.
public void write(String s, int offset, int len)
Write a portion of a String starting from offset and with a length of len.
Following is an example to demonstrate class −
import java.io.*;
public class FileRead {

   public static void main(String args[])throws IOException {
      File file = new File("Hello1.txt");
      
      // creates the file
      file.createNewFile();
      
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      
      // Writes the content to the file
      writer.write("This\n is\n an\n example\n"); 
      writer.flush();
      writer.close();

      // Creates a FileReader Object
      FileReader fr = new FileReader(file); 
      char [] a = new char[50];
      fr.read(a);   // reads the content to the array
      
      for(char c : a)
         System.out.print(c);   // prints the characters one by one
      fr.close();
   }
}
This will produce the following result −
This
is
an
example


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python String endswith() Method - GeeksforGeeks

05 Aug, 2021
Python String endswith() method returns True if a string ends with the given suffix otherwise returns False.
Syntax:
str.endswith(suffix, start, end)
Parameters: 
suffix: Suffix is nothing but a string that needs to be checked. 
start: Starting position from where suffix is needed to be checked within the string. 
end: Ending position + 1 from where suffix is needed to be checked within the string.  
Note: If start and end index is not provided then by default it takes 0 and length -1 as starting and ending indexes where ending index is not included in our search.
Returns: It returns True if the string ends with the given suffix otherwise return False. 
Python
# Python code shows the working of# .endswith() function  text = "geeks for geeks."  # returns Falseresult = text.endswith('for geeks')print (result)  # returns Trueresult = text.endswith('geeks.')print (result)  # returns Trueresult = text.endswith('for geeks.')print (result)  # returns Trueresult = text.endswith('geeks for geeks.')print (result)
Output: 
False
True
True
True
Python
# Python code shows the working of# .endswith() function  text = "geeks for geeks."  # start parameter: 10result = text.endswith('geeks.', 10)print(result)  # Both start and end is provided# start: 10, end: 16 - 1# Returns Falseresult = text.endswith('geeks', 10, 16)print result  # returns Trueresult = text.endswith('geeks', 10, 15)print result
Output: 
True
True
False 
a98banerjee
AmiyaRanjanRout
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
How to update a MySQL column by subtracting a value with some conditions?

Let us first create a table −
mysql> create table DemoTable
(
   Score int
);
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(29);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(24);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(32);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Score |
+-------+
|    45 |
|    29 |
|    56 |
|    24 |
|    32 |
+-------+
5 rows in set (0.00 sec)
Following is the query to update MySQL column by subtracting a value with some conditions −
mysql> update DemoTable set Score=Score-2 where Score > 30;
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Score |
+-------+
|    43 |
|    29 |
|    54 |
|    24 |
|    30 |
+-------+
5 rows in set (0.00 sec)
How do I remove lines between ListViews on Android using Kotlin?

This example demonstrates how to remove lines between ListViews on Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingStart="4dp"
   tools:context=".MainActivity">
<ListView
   android:id="@+id/listView"
   android:layout_width="wrap_content"
   android:layout_height="match_parent"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var listView: ListView
   var mobilePhones = arrayOf("Samsung", "Iphone", "Nokia", "Alcatel", "Blackberry", "Oppo", "Sony")
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      listView = findViewById(R.id.listView)
      val adapter: ArrayAdapter<Any?> = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, mobilePhones)
      listView.adapter = adapter
      listView.divider = null
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
Python | Pandas Series.dt.year - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.year attribute return a numpy array containing year of the datetime in the underlying data of the given series object.
Syntax: Series.dt.year
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.year attribute to return the year of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',                '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.year attribute to return the year of the datetime in the underlying data of the given Series object.
# return the yearresult = sr.dt.year  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.year attribute has successfully accessed and returned the year of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.year attribute to return the year of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                       periods = 5, freq = 'H'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.year attribute to return the year of the datetime in the underlying data of the given Series object.
# return the yearresult = sr.dt.year  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.year attribute has successfully accessed and returned the year of the datetime in the underlying data of the given series object.
Python pandas-series-datetime
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 ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
JavaScript - Array some() Method

Javascript array some() method tests whether some element in the array passes the test implemented by the provided function.
Its syntax is as follows −
array.some(callback[, thisObject]);

callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
If some element pass the test, then it returns true, otherwise false.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.some) {
   Array.prototype.some = function(fun /*, thisp*/) {
      var len = this.length;
      if (typeof fun != "function")
      throw new TypeError();
      
      var thisp = arguments[1];
      for (var i = 0; i < len; i++) {
         if (i in this && fun.call(thisp, this[i], i, this))
         return true;
      }
      return false;
   };
}
Try the following example.
<html>
   <head>
      <title>JavaScript Array some Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         if (!Array.prototype.some) {
            Array.prototype.some = function(fun /*, thisp*/) {
               var len = this.length;
               if (typeof fun != "function")
               throw new TypeError();
               
               var thisp = arguments[1];
               for (var i = 0; i < len; i++) {
                  if (i in this && fun.call(thisp, this[i], i, this))
                  return true;
               }
               return false;
            };
         }
         
         function isBigEnough(element, index, array) {
            return (element >= 10);
         }
         
         var retval = [2, 5, 8, 1, 4].some(isBigEnough);
         document.write("Returned value is : " + retval );
         
         var retval = [12, 5, 8, 1, 4].some(isBigEnough);
         document.write("<br />Returned value is : " + retval );
      </script>      
   </body>
</html>
Returned value is : false
Returned value is : true 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to find the sum of rows and columns of a given matrix using Numpy?

In this problem, we will find the sum of all the rows and all the columns separately. We will use the sum() function for obtaining the sum.
Step 1: Import numpy.
Step 2: Create a numpy matrix of mxn dimension.
Step 3: Obtain the sum of all the rows.
Step 4: Obtain the sum of all the columns.
import numpy as np

a = np.matrix('10 20; 30 40')
print("Our matrix: \n", a)

sum_of_rows = np.sum(a, axis = 0)
print("\nSum of all the rows: ", sum_of_rows)

sum_of_cols = np.sum(a, axis = 1)
print("\nSum of all the columns: \n", sum_of_cols)
Our matrix:
 [[10 20]
 [30 40]]
Sum of all the rows:  [[40 60]]
Sum of all the columns:
 [[30]
 [70]]
The np.sum() function takes an additional matrix called the 'axis'. Axis takes two values. Either 0 or 1. If axis=0, it tells the sum() function to consider only the rows. If axis = 1, it tells the sum() function to consider only the columns.
Python 3 - os.write() Method

The method write() writes the string str to file descriptor fd. Return the number of bytes actually written.
Following is the syntax for write() method −
os.write(fd, str)

fd − This is the file descriptor.
fd − This is the file descriptor.
str − This is the string to be written.
str − This is the string to be written.
This method returns the number of bytes actually written.
The following example shows the usage of write() method.
# !/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "f1.txt", os.O_RDWR|os.O_CREAT )

# Write one string
line = "this is test" 

# string needs to be converted byte object
b = str.encode(line)
ret = os.write(fd, b)

# ret consists of number of bytes written to f1.txt
print ("the number of bytes written: ", ret)

# Close opened file
os.close( fd)

print ("Closed the file successfully!!")
When we run the above program, it produces the following result −
the number of bytes written: 12
Closed the file successfully!!


    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
What is the best way to run all Python files in a directory?

The fastest and easiest way to run all Python files in a directory is to use loops. You can use bash to do this for you.
For example, create a new file called run_all_py.sh and write the following in it:
for f in *.py; do python"$f"; done
 Now run the file using 
$ bash run_all_py.sh
 You could also use xargs to parallely execute these files(Only available on UNIX).
$ ls *.py|xargs -n 1 -P 4 python
How to dynamically create radio buttons using an array in JavaScript?

To dynamically create radio button using an array, use the concept of createElement() and
appendChild().
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
</body>
<script>
   var gender = ['Male', 'Female'];
   gender.forEach((genederValue, i) => {
      var labelValue = document.createElement('label');
      labelValue.innerHTML = genederValue;
      var inputValue = document.createElement('input');
      inputValue.type = "radio";
      inputValue.name = genederValue;
      inputValue.genederValue = i;
      document.body.appendChild(labelValue);
      document.body.appendChild(inputValue);
   });
</script>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the
file. Select the option “Open with live server” in VS Code editor.
This will produce the following output −
How can we create a MySQL view with GROUP BY clause?

We can use GROUP BY to group values from a column, and, if we want, we can perform calculations on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column. To understand GROUP BY clause with views we are creating a view named ‘Info’ using the base table ‘Student_info’ having the following data −
mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
+------+---------+------------+------------+
6 rows in set (0.00 sec)
Create or Replace View view_name AS Select_statements FROM table GROUP BY expression1, expression2, ... expression_n;

mysql> Create or Replace View Info AS select Subject, COUNT(*) FROM Student_info GROUP BY Subject;
Query OK, 0 rows affected (0.10 sec)

mysql> Select * from info;
+------------+----------+
| Subject    | COUNT(*) |
+------------+----------+
| Computers  |    3     |
| Economics  |    1     |
| History    |    1     |
| Literature |    1     |
+------------+----------+
4 rows in set (0.00 sec)

mysql> Create or Replace View Info AS select Subject,Name, COUNT(Subject) FROM Student_info GROUP BY Subject, Name;
Query OK, 0 rows affected (0.05 sec)
The query above will have two columns in GROUP BY clause.
mysql> Select * from info;
+------------+---------+----------------+
| Subject    | Name    | COUNT(Subject) |
+------------+---------+----------------+
| Computers  | Mohan   |       1        |
| Computers  | Ram     |       1        |
| Computers  | Raman   |       1        |
| Economics  | Shyam   |       1        |
| History    | YashPal |       1        |
| Literature | Gaurav  |       1        |
+------------+---------+----------------+
6 rows in set (0.00 sec)
The above result sets show that GROUP BY clause groups a set of rows into a set of summary rows by values of columns.
Difference Between JDBC and Hibernate

JDBC is acronym of Java database connectivity. It is used to connect your application to the database and transactions . It is an open source Java api.  
Hibernate is also used for connect your application to database and to do database related transactions but with different approach. It has a object relationship library which mapped the tables and columns of the database with the java object. It enables object oriented programming in database. Hibernate provides HQL to access the data from the database.


1
Basic 
It is database connectivity technology 
It is a framework,
2
Lazy Loading 
It does not support lazy loading 
Hibernate support lazy loading 
3
Transaction management 
We need to maintain explicitly database connection and transaction.  
Hibernate itself manage all transaction 
4.
Caching 
We need to write code for implementing caching  
Hibernates provides two types of caching :
First level Cache 
Second level cache
No Extra code is required to use first level cache.
5.
Performance 
Low performance
High Performance 
@Entity
public class User {
   @Id
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class HibernateConnectionExample {
   public static void main(String[] args) {
      //get session factory to start transcation
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      User user = (User) session.get(User.class, new Integer(2));
      System.out.println("User ID= "+user.getId());
      System.out.println("User Name= "+user.getName());
      //Close resources
      tx.commit();
      sessionFactory.close();
   }
}
class JDBCConnectionExample {
   public static void main(String a[]) {
      String url = "jdbc:oracle:thin:@localhost:1521:local";
      String user = "sys";
      String password = "abc123";
      String sql = "select * from user";
      Connection con=null;
      try {
         DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
         //Reference to connection interface
         con = DriverManager.getConnection(url,user,password);
         Statement st = con.createStatement();
         int respCode = st.executeUpdate(sql);
         con.close();
      }
      catch(Exception ex) {
         System.err.println(ex);
      }
   }
}
How to create a Polygon using JavaFX?

A polygon is a closed figure formed using n number of lines existing in the same plane. In JavaFX a polygon is represented by the javafx.scene.shape.Polygon class.
To create a polygon you need to −
Instantiate this class.
Instantiate this class.
Pass the start and endpoints, of the line segments to draw a polygon to the class either by passing them as arguments to the constructor or, using the getPoints() method as −
Pass the start and endpoints, of the line segments to draw a polygon to the class either by passing them as arguments to the constructor or, using the getPoints() method as −
polygon.getPoints().addAll(new Double[]{ List of XY coordinates separated by
commas });
Add the created node (shape) to the Group object.
Add the created node (shape) to the Group object.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Polygon;
public class DrawingPolygon extends Application {
   public void start(Stage stage) {
      //Drawing a polygon
      Polygon polygon1 = new Polygon();
      //Setting the properties of the ellipse
      polygon1.getPoints().addAll(new Double[]{
         250.0, 50.0, 175.0, 150.0,
         175.0, 250.0, 200.0, 250.0,
         350.0, 150.0
      });
      //Setting other properties
      polygon1.setFill(Color.DARKCYAN);
      polygon1.setStrokeWidth(8.0);
      polygon1.setStroke(Color.DARKSLATEGREY);
      //Drawing a polygon
      Polygon polygon2 = new Polygon();
      //Setting the properties of the ellipse
      polygon2.getPoints().addAll(new Double[]{
         410.0, 160.0, 430.0, 130.0, 470.0, 130.0,
         490.0, 160.0, 470.0, 200.0, 430.0, 200.0
      });
      //Setting other properties
      polygon2.setFill(Color.CHOCOLATE);
      polygon2.setStrokeWidth(8.0);
      polygon2.setStroke(Color.BROWN);
      //Setting the Scene
      Group root = new Group(polygon1, polygon2);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Drawing Polygon");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
PHP - Function fgetcsv()

The fgetcsv() function can parse a line from an open file and check for CSV fields.  This function stops returning on a new line at a specified length or EOF, whichever comes first. This function returns CSV fields in the array on success or false on failure and EOF. 
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] )

 This function is similar to fgets() function except that fgetcsv() function parses the line it reads for fields in CSV format and returns an array containing the fields read. The fgetcsv() function can return false on error, including the end of a file. 
<?php
   $file = fopen("/PhpProject/EmpDetails.csv", "r"); 
   echo fgetcsv($file);
   fclose($file);
?>
Array
(
   [0] => Chandra
   [1] => Ravi
   [2] => Adithya
   [3] => Sai
)

<?php
   $file = fopen("/PhpProject/EmpDetails.csv", "r"); 

   while(! feof($file)) {
      print_r(fgetcsv($file));
   }
   fclose($file);
?> 
Array
(
    [0] =>  Chandra
    [1] =>  Ravi
    [2] =>  Adithya
    [3] =>  Sai
)
Array
(
    [0] =>  Dev
    [1] =>  Jai
    [2] =>  Ramesh
    [3] =>  Raja
)


    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
How to show multiple colorbars in Matplotlib?

To show multiple colorbars in matplotlib, we can take the following steps−
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Initialize a variable N for the number of sample data.
Create random data1 using numpy.
Display data as an image, i.e., on a 2D regular raster, with data1.
Add a colorbar to a plot.
Repeat steps 4, 5, and 6, with different datasets and axes.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
N = 10
data1 = np.random.rand(N, N)
im1 = ax1.imshow(data1, cmap='hot')
plt.colorbar(im1, cax=ax1)
data2 = np.random.rand(N, N)
im2 = ax2.imshow(data2, cmap='plasma')
plt.colorbar(im2, cax=ax2)
plt.show()