code-rag-bench/online-tutorials huggingface dataset:
numpy.searchsorted() in Python

10 Dec, 2018
numpy.searchsorted() function is used to find the indices into a sorted array arr such that, if elements are inserted before the indices, the order of arr would be still preserved. Here, binary search is used to find the required insertion indices.
Syntax : numpy.searchsorted(arr, num, side=’left’, sorter=None)
Parameters :arr : [array_like] Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.num : [array_like]The Values which we want to insert into arr.side : [‘left’, ‘right’], optional.If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).num : [array_like, Optional] array of integer indices that sort array a into ascending order. They are typically the result of argsort.
Return : [indices], Array of insertion points with the same shape as num.
Code #1 : Working
# Python program explaining# searchsorted() function   import numpy as geek  # input arrayin_arr = [2, 3, 4, 5, 6]print ("Input array : ", in_arr)  # the number which we want to insertnum = 4print("The number which we want to insert : ", num)     out_ind = geek.searchsorted(in_arr, num) print ("Output indices to maintain sorted array : ", out_ind)
Output :
Input array :  [2, 3, 4, 5, 6]
The number which we want to insert :  4
Output indices to maintain sorted array :  2

 Code #2 :
# Python program explaining# searchsorted() function   import numpy as geek  # input arrayin_arr = [2, 3, 4, 5, 6]print ("Input array : ", in_arr)  # the number which we want to insertnum = 4print("The number which we want to insert : ", num)     out_ind = geek.searchsorted(in_arr, num, side ='right') print ("Output indices to maintain sorted array : ", out_ind)
Output :
Input array :  [2, 3, 4, 5, 6]
The number which we want to insert :  4
Output indices to maintain sorted array :  3

 Code #3 :
# Python program explaining# searchsorted() function   import numpy as geek  # input arrayin_arr = [2, 3, 4, 5, 6]print ("Input array : ", in_arr)  # the numbers which we want to insertnum = [4, 8, 0]print("The number which we want to insert : ", num)     out_ind = geek.searchsorted(in_arr, num) print ("Output indices to maintain sorted array : ", out_ind)
Output :
Input array :  [2, 3, 4, 5, 6]
The number which we want to insert :  [4, 8, 0]
Output indices to maintain sorted array :  [2 5 0]

Python numpy-Sorting Searching
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.linalg.eig() Method in Python

10 Aug, 2020
In NumPy we can compute the eigenvalues and right eigenvectors of a given square array with the help of numpy.linalg.eig(). It will take a square array as a parameter and it will return two values first one is eigenvalues of the array and second is the right eigenvectors of a given square array.
Syntax: numpy.linalg.eig()
Parameter: An square array.
Return: It will return two values first is eigenvalues and second is eigenvectors.
Example 1:
Python
import numpy as np    mat = np.mat("1 -2;1 3")  # Original matrixprint(mat)print("")evalue, evect = np.linalg.eig(mat)  # Eigenvalues of the said matrix"print(evalue)print("")  # Eigenvectors of the said matrixprint(evect)
Output:
[[ 1 -2]
 [ 1  3]]

[2.+1.j 2.-1.j]

[[ 0.81649658+0.j          0.81649658-0.j        ]
 [-0.40824829-0.40824829j -0.40824829+0.40824829j]]

Example 2:
Python
import numpy as np    mat = np.mat("1 2 3;1 3 4;3 2 1")  # Original matrixprint(mat)print("")evalue, evect = np.linalg.eig(mat)  # Eigenvalues of the said matrix"print(evalue)print("")  # Eigenvectors of the said matrixprint(evect)
Output:
[[1 2 3]
 [1 3 4]
 [3 2 1]]

[ 6.70156212  0.29843788 -2.        ]

[[-0.5113361  -0.42932334 -0.40482045]
 [-0.69070311  0.7945835  -0.52048344]
 [-0.5113361  -0.42932334  0.75180941]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
HTML | DOM image naturalWidth property - GeeksforGeeks

21 Dec, 2020
naturalWidth : property is used to get the original width of an image. Since the width of an image to be displayed on the webpage can be modified using the ‘width’ attribute of the <img> tag, hence the naturalWidth property becomes useful in situations where the original width of the image is required rather than the customized one. It is a read-only property.
Syntax : 
imageObject.naturalWidth
Return Value: It returns the original width of the image in pixels.
Example: 
html
<html> <body>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190602171808/629-300x255.png"id="image" alt="" width="250" height="205"class="alignnone size-medium wp-image-1092360" />    <br>    <br>    <button type="button" onclick="getWidth()">Click</button>    <div id="text"></div>    <script>        function getWidth() {            var imgObject = document.getElementById("image");            var output = document.getElementById("text");            output.innerHTML = "Width of image: " + imgObject.width +            "<br>naturalWidth of image: " + imgObject.naturalWidth;        }    </script></body> </html>
Output: Before click:  
After click:  
 
Google Chrome
Internet Explorer 9.0 or above
Mozilla Firefox
Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
arorakashish0911
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
SQL Query to Add Ranking Positions of Rows in a Database With RANK() - GeeksforGeeks

13 Apr, 2021
In this article, we will discuss the overview of SQL function RANK and then our main focus will be on Add Ranking Positions of Rows in a Database With RANK() in SQL. Let’s discuss it one by one.
Overview :Generally, when max/min commands are executed, a single row is displayed as output. RANK() is an SQL function introduced in order to rank the rows according to some attribute in the table. Based on the record of the existing value, the RANK function will help the column to be ranked accordingly.
Syntax :
RANK() OVER(ORDER BY Any Column)
Steps to implement RANK function :Here, we will discuss the steps to implement the RANK function in SQL. 
Step-1: Reference table :Consider a table is created based on marks of students in the class that contains data displayed below.
MATHEMATICS
99
85
91
94
99
88
92
92
94
88
91
91
90
89
Step-2: Creating a table :Now, the SQL statement used to create the table is given as follows.
CREATE TABLE MarkList
(
id int,
name varchar(20),
mathematics int, 
physics int,
chemistry int
);
Step-3: Inserting data :Here, we will insert the rows into the table as follows.
insert into MarkList values( 501,'Surya',99,97,85);
insert into MarkList values(502,'Charan',99,93,88);
insert into MarkList values(503,'Sravan',91,98,94);
insert into MarkList values(504,'Ram',92,99,82);
insert into MarkList values(505,'Aryan',94,99,88);
insert into MarkList values(506,'Sathwik',91,88,91);
insert into MarkList values(507,'Madhav',90,97,89);
Step-4: Verifying and ranking data :Now, if we want ranks based on the scores of mathematics, then the query is written as follows.
SELECT id, name, mathematics,
RANK() OVER(ORDER BY Mathematics DESC) 
as 
'Rank' from MarkList;
Output :The output will be as follows.
MATHEMATICS
99
1
99
1
94
3
92
4
91
5
91
5
90
7
Explanation :
When the SQL command is executed, the function checks for the order and assigns the ranks to the respective rows.
Then the table is displayed with the ranks as per the given code.
Other Methods :     There are many other methods that can be used in the place of RANK(). Some of them are listed here.
ROW_NUMBER() just adds the row number in the place of the rank.
DENSE_RANK() just gives the next number as the next rank. This does not depend on the frequency of other ranks.
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows
Batch Script - MORE

This batch command displays the contents of a file or files, one screen at a time.
More [filename]

Where filename is the file whose contents need to be listed one screen at a time.
@echo off
More C:\tp\lists.txt
Directory of C:\Program Files
The above command will display the contents of the file lists.txt one screen at a time. Following is an example of an output. Note the -- More (12%) – at the end of the screen. In order to proceed and display the remaining contents of the file, you need to enter a key.
12/22/2015 02:31 AM   <DIR>       .
12/22/2015 02:31 AM   <DIR>       ..
12/15/2015 11:14 PM   <DIR>       Application Verifier
12/18/2015 05:06 PM   <DIR>       Bonjour
12/26/2015 08:01 PM   <DIR>       CCleaner
12/18/2015 05:05 PM   <DIR>       Common Files
12/17/2015 11:04 AM   <DIR>       Git
12/15/2015 11:09 PM   <DIR>       IIS
12/15/2015 11:10 PM   <DIR>       IIS Express
12/15/2015 10:16 PM   <DIR>       Intel
03/18/2014 02:24 AM   <DIR>       Internet Explorer
12/18/2015 05:06 PM   <DIR>       iPod
12/18/2015 05:06 PM   <DIR>       iTunes
12/15/2015 11:16 PM   <DIR>       Microsoft Identity Extensions
12/15/2015 11:46 PM   <DIR>       Microsoft Office
12/22/2015 02:31 AM   <DIR>       Microsoft Silverlight
12/15/2015 11:15 PM   <DIR>       Microsoft SQL Server
12/15/2015 11:15 PM   <DIR>       Microsoft SQL Server Compact Edition
12/15/2015 10:59 PM   <DIR>       Microsoft Visual Studio 12.0
-- More (12%) --

 Print
 Add Notes
 Bookmark this page
Python | Matching elements count - GeeksforGeeks

19 Feb, 2020
Sometimes, while working with lists we need to handle two lists and search for the matches, and return just the count of indices of the match. Querying whole list for the this process is not feasible when the size of master list is very large, hence having just the match indices helps in this cause. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list comprehension + index() + len()This problem can potentially be solved using the index function of python to get the wanted indices and list comprehension can be used to extend this to the whole string. The len() is used to return total count of match.
# Python3 code to demonstrate# Matching elements count# using list comprehension and index() + len()  # initializing liststest_list1 = [5, 4, 1, 3, 2]test_list2 = [1, 2]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # using list comprehension and index() + len()# Matching elements countres = len([test_list1.index(i) for i in test_list2])  # print resultprint("The Match indices list count is : " + str(res))
The original list 1 : [5, 4, 1, 3, 2]
The original list 2 : [1, 2]
The Match indices list count is : 2

 
Method #2 : Using enumerate() + len() + list comprehensionThe enumerate function can be used to produce the key value pair for the list being it’s index and value and we can store them using list comprehension. The len() is used to return total count of match.
# Python3 code to demonstrate# Matching elements count# using list comprehension and enumerate() + len()  # initializing liststest_list1 = [5, 4, 1, 3, 2]test_list2 = [1, 2]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # using list comprehension and enumerate() + len()# Matching elements countres = len([key for key, val in enumerate(test_list1) if val in set(test_list2)])  # print resultprint("The Match indices list count is : " + str(res))
The original list 1 : [5, 4, 1, 3, 2]
The original list 2 : [1, 2]
The Match indices list count is : 2

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Python 3 - os.pipe() Method

The method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading and writing, respectively
Following is the syntax for pipe() method −
os.pipe()

NA
This method returns a pair of file descriptors.
The following example shows the usage of pipe() method.
#!/usr/bin/python3
import os, sys

print ("The child will write text to a pipe and ")
print ("the parent will read the text written by child...")

# file descriptors r, w for reading and writing
r, w = os.pipe() 

processid = os.fork()
if processid:
   # This is the parent process 
   # Closes file descriptor w
   os.close(w)
   r = os.fdopen(r)
   print ("Parent reading")
   str = r.read()
   print ("text =", str   )
   sys.exit(0)
else:
   # This is the child process
   os.close(r)
   w = os.fdopen(w, 'w')
   print ("Child writing")
   w.write("Text written by child...")
   w.close()
   print ("Child closing")
   sys.exit(0)
When we run the above program, it produces the following result −
The child will write text to a pipe and 
the parent will read the text written by child...
Parent reading
('text =', 'Text written by child...')
The child will write text to a pipe and 
the parent will read the text written by child...
Child writing
Child closing.


    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
How to install the latest PowerShell module version?

Although simply running Install-Module command picks up the latest version of the module, we can still use the -RequiredVersion and -MinimumVersion parameter to install the latest version manually. Below command directly installs the latest available version of the module.
In this example we are using 7Zip4PowerShell module.
Install-Module 7Zip4PowerShell -Scope AllUsers -Force -Verbose
To manually install the latest version of the PowerShell module, there are two methods.
Use the -RequiredVersion parameter if you know the latest version of the module.
Use the -MinimumVersion parameter if you know the minor version of the module and it will pick up the latest version.
Using -RequiredVersion Parameter
This parameter installs the specific version of the module. To installs the latest version, we first need to identify the all available versions and then pick the latest version from it and install it.
We can check all available versions using the Find-Module version.
Find-Module 7zip4PowerShell -AllVersions
Here, we have the latest version 1.13.0 of the module 7Zip4PowerShell and we are going to install it.
Install-Module 7Zip4PowerShell -RequiredVersion 1.13.0 -Scope AllUsers -Force -Verbose
If you don't know one of its versions but not the latest version then use -MinimumVersion parameter and it will automatically pick up the latest version.
Install-Module 7Zip4PowerShell -MinimumVersion 1.9.0 -Scope AllUsers -Force -Verbose
The above command will install module version 1.13.0 because it is its latest version.
How do we display the thickness of the border of an element in HTML?

Use the border attribute in HTML to display the thickness of the border.
Note − This attribute is not supported in HTML5.
You can try to run the following code to learn how to implement border attribute in HTML −
<!DOCTYPE html>
<html>
   <body>
      <h2>Cricketers</h2>
      <table style="width:100%" border="1">
         <th>Name</th>
         <tr>
            <td>Sachin Tendulkar</td>
         </tr>
         <tr>
            <td>Virat Kohli</td>
         </tr>
      </table>
   </body>
</html>
Use CSS instead, since the border attribute deprecated in HTML5.
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
         }
      </style>
   </head>
   <body>
      <h2>Cricketers</h2>
      <table style="width:100%">
         <caption>Indian Cricketers</caption>
         <th>Name</th>
         <tr>
            <td>Sachin Tendulkar</td>
         </tr>
         <tr>
            <td>Virat Kohli</td>
         </tr>
      </table>
   </body>
</html>
How to use the ‘except’ clause with multiple exceptions in Python?

It is possible to define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under except clause.
In general, the syntax for multiple exceptions is as follows
Except(Exception1, Exception2,...ExceptionN) as e:
When we define except clause in this way, we expect the same code to throw different exceptions. Also, we want to take the action in each case.
Example code
import sys
try:
d = 8
d = d + '5'
except(TypeError, SyntaxError)as e:
print sys.exc_info()
We get output as shown
(<type 'exceptions.TypeError'>, TypeError("unsupported operand type(s) for
 +: 'int' and 'str'",), <traceback object at 0x0000000002954748>)
How to create a table with a caption?

To create a table with caption in HTML, use the <caption> tag. Caption gets added inside the table, immediately after the <table> tag.
You can try to run the following code to create a table with caption in HTML
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, td, th { border: 1px solid black; }
      </style>
   </head>
   <body>
      <table>
         <caption>Our Technologies</caption>
         <tr>
            <th>IDE</th>
            <th>Database</th>
         </tr>
         <tr>
            <td>NetBeans IDE</td>
            <td>MySQL</td>
         </tr>
      </table>
   </body>
</html>
How to change border color in Tkinter widget?

23 Nov, 2021
Prerequisites: Tkinter GUI, Tkinter Widgets
Tkinter is Python’s standard GUI package which provides us with a variety of common GUI elements such as buttons, menus, and various kinds of entry fields and display areas which we can use to build out an interface. These elements are called Tkinter Widgets.
Among all color options for a widget, there is no direct method to change the border color of the widget. As the border color of a widget is tied to the background color of the widget, it is impossible to set it individually. But, we do have some methods to color the border of a widget and those methods are discussed below.
Instead of using the default border of a widget, we can use the Frame widget as an alternative border, where we can set the background color of the Frame widget to any color we want. This method works with every widget.
Import Tkinter module
Create a window
Create a border variable with Frame widget with background color as its attributes
Create any widget with the border variable as an attribute
Place the widget on the window created
Example:
Python3
# import tkinterfrom tkinter import * # Create Tk objectwindow = Tk() # Set the window titlewindow.title('GFG') # Create a Frame for borderborder_color = Frame(window, background="red") # Label Widget inside the Framelabel = Label(border_color, text="This is a Label widget", bd=0) # Place the widgets with border Framelabel.pack(padx=1, pady=1)border_color.pack(padx=40, pady=40) window.mainloop()
Output:
We can also use a highlighted background and highlight color together to get a border color for our widget. We can even adjust the thickness of the border using the highlight thickness attribute. This method only works for some widgets like Entry, Scale, Text e.t.c.
Import Tkinter module
Create a window
Create a widget with highlightthickness set to desired border thickness
Configure highlightbackground and highlightcolor attributes to the desired border-color
Place the widget on the window created
Example:
Python3
# import tkinterfrom tkinter import * # Create Tk objectwindow = Tk() # Set the window titlewindow.title('GFG') # Entry Widget# highlightthickness for thickness of the borderentry = Entry(highlightthickness=2) # highlightbackground and highlightcolor for the border colorentry.config(highlightbackground = "red", highlightcolor= "red") # Place the widgets in windowentry.pack(padx=20, pady=20) window.mainloop()
Output:
Note: It is recommended to use Method 1 for setting the border color of a widget as Method 2 may or may not work for some widgets. But Method 1 works universally on any widget.
punamsingh628700
Picked
Python Tkinter-exercises
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to Install Dart Sass in Windows?

29 Oct, 2021
Dart is a programming language designed for client development such as for the web and mobile apps. It is developed by Google and can also be used to build server and desktop applications. Dart is an object-oriented, class-based, garbage-collected language with C-style syntax. Dart can compile to either native code or JavaScript. It supports interfaces, mixins, abstract classes, reified generics, and type inference. Dart initially had a mixed reception and the Dart initiative has been criticized by some for fragmenting the web, due to the original plans to include a Dart VM in Chrome. Those plans were dropped in 2015 with the 1.9 release of Dart to focus instead on compiling Dart to JavaScript. In August 2018, Dart 2.0 was released, with language changes including a sound type system.
Dart is an object-oriented programming language with support for inheritance, interfaces, and optional typing features. It also supports interfaces, mixins, abstract classes, reified generics, static typing, and a strong type system.
Dart is an open-source programming language and it comes with a set of tools for compiling and executing Dart Code. It is recognized as an ECMA standard and is available with a BSD license.
Dart is cross-platform and supports all major operating systems. The Dart compiler comes with its own Virtual Machine which allows Dart programs to run on every system.
Follow the below steps to install dart Saas n Windows:
Step 1: In your browser navigate to this link.
Step 2: After going to this link choose the preferable file according to your pc & download the file.
Step 3: Then extract the file & copy the path & make it available to you.
Step 4: Search for the system environment variable in the search bar of your computer.
Step 5: Then click on the environment variable.
Step 6: Then click on the Path & then click on New.
 Step 7: Then you have to give Variable Name as Path & then in Variable Value you have to put the folder path which you have copied in Step 3. Then you have to click Ok
Now open the command prompt. There you have to execute the below command:
saas --version
This command will give the proper output. If you find the output then you have successfully installed the Dart Saas.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LocalDate isAfter() method in Java with Examples

29 Nov, 2018
The isAfter() method of LocalDate class in Java checks if this date is after the specified date.
Syntax:
public boolean isAfter(ChronoLocalDate date2)

Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null.
Return Value: The function returns true if this date is after the specified date.
Below programs illustrate the isAfter() method of LocalDate in Java:
Program 1:
// Program to illustrate the isAfter() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");        // Parses the second date        LocalDate dt2 = LocalDate.parse("2017-11-27");          // Checks        System.out.println(dt1.isAfter(dt2));    }}
true

Program 2:
// Program to illustrate the isAfter() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");        // Parses the second date        LocalDate dt2 = LocalDate.parse("2019-11-27");          // Checks        System.out.println(dt1.isAfter(dt2));    }}
false

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#isAfter(java.time.chrono.ChronoLocalDate)
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
Introduction to Java
Gson - Null Object Support

Gson by default generates optimized Json content ignoring the NULL values. But GsonBuilder provides flags to show NULL values in the Json output using the GsonBuilder.serializeNulls() method.
GsonBuilder builder = new GsonBuilder(); 
builder.serializeNulls(); 
Gson gson = builder.create(); 

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
import com.google.gson.Gson;  

public class GsonTester { 
   public static void main(String args[]) { 
   
      Gson gson = new Gson();  
      
      Student student = new Student(); 
      student.setRollNo(1);  
      String jsonString = gson.toJson(student); 
      
      System.out.println(jsonString);  
      student = gson.fromJson(jsonString, Student.class); 
      System.out.println(student); 
   }      
} 

class Student { 
   private int rollNo; 
   private String name;  
   
   public int getRollNo() { 
      return rollNo; 
   }  
   
   public void setRollNo(int rollNo) { 
      this.rollNo = rollNo; 
   } 
   
   public String getName() { 
      return name; 
   }  
   
   public void setName(String name) { 
      this.name = name; 
   } 
   
   public String toString() { 
      return "Student[ name = "+name+", roll no: "+rollNo+ "]"; 
   } 
}
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester

Verify the output.
{"rollNo": 1} 
Student[ name = null, roll no: 1] 

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;  

public class GsonTester { 
   public static void main(String args[]) { 
   
      GsonBuilder builder = new GsonBuilder(); 
      builder.serializeNulls(); 
      builder.setPrettyPrinting(); 
      Gson gson = builder.create();  
      
      Student student = new Student(); 
      student.setRollNo(1);  
      String jsonString = gson.toJson(student); 
      
      System.out.println(jsonString);  
      student = gson.fromJson(jsonString, Student.class); 
      System.out.println(student); 
   }      
} 
class Student { 
   private int rollNo; 
   private String name;  
   
   public int getRollNo() { 
      return rollNo; 
   }  
   
   public void setRollNo(int rollNo) { 
      this.rollNo = rollNo; 
   }  
   
   public String getName() { 
      return name; 
   }  
   
   public void setName(String name) { 
      this.name = name; 
   } 
   
   public String toString() { 
      return "Student[ name = "+name+", roll no: "+rollNo+ "]"; 
   } 
}
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester

Verify the output.
{ 
   "rollNo": 1, 
   "name": null 
} 
Student[ name = null, roll no: 1] 

 Print
 Add Notes
 Bookmark this page
Ruby | Hash merge function - GeeksforGeeks

07 Jan, 2020
Hash#merge() is a Hash class method which combines two hash arrays and their content.
Syntax: Hash.merge()
Parameter: Hash values
Return: combine two hash arrays
Example #1 :
# Ruby code for Hash.merge() method  # declaring Hash valuea = {a:100, b:200}  # declaring Hash valueb = {a:100, c:300, b:200}  # declaring Hash valuec = {a:100}    # merge Valueputs "Hash a merge form : #{a.merge(b)}\n\n"  puts "Hash b merge form : #{b.merge(c)}\n\n"  puts "Hash c merge form : #{c.merge(a)}\n\n"
Output :
Hash a merge form : {:a=>100, :b=>200, :c=>300}

Hash b merge form : {:a=>100, :c=>300, :b=>200}

Hash c merge form : {:a=>100, :b=>200}


Example #2 :
# Ruby code for Hash.merge() method  # declaring Hash valuea = { "a" => 100, "b" => 200 }  # declaring Hash valueb = {"a" => 100}  # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200}  # merge Valueputs "Hash a merge form : #{a.merge(b)}\n\n"  puts "Hash b merge form : #{b.merge(c)}\n\n"  puts "Hash c merge form : #{c.merge(a)}\n\n"
Output :
Hash a merge form : {"a"=>100, "b"=>200}

Hash b merge form : {"a"=>100, "c"=>300, "b"=>200}

Hash c merge form : {"a"=>100, "c"=>300, "b"=>200}

Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Array slice() function
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
skill - Unix, Linux Command

skill [signal to send] [options] process selection criteria
snice [new priority] [options] process selection criteria




The default signal for skill is TERM. Use -l or -L to list available signals.
Particularly useful signals include HUP, INT, KILL, STOP, CONT, and 0.
Alternate signals may be specified in three ways: -9 -SIGKILL -KILL.


The default priority for snice is +4. (snice +4 ...)
Priority numbers range from +20 (slowest) to -20 (fastest).
Negative priority numbers are restricted to administrative users.
















Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to use image height and width attribute in HTML Page?

To add an image in an HTML page, <img> tag is used. With that, we need to use the attributes height and width to set the height and width of the image in pixels. Just keep in mind to specify both these attributes.
You can try the following code to add height and width attribute to the image in an HTML page −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Document</title>
   </head>

   <body>
      <img src = ”/green/images/logo.png” alt = "We Learners" width = ”170” height = ”70”>
   </body>
</html>
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks

28 Jun, 2021
The ratio of male to female students in a college for five years is plotted in the following line graph. If the number of female students doubled in 2009, by what percent did the number of male students increase in 2009?(A) 120(B) 140(C) 160(D) 180Answer: (B)Explanation:
Let x represent the males and y represent the females.

In 2008.
x / y = 2.5 -----------(1)

In 2009.
M / 2y = 3-------------(2)

where M is the total number of males in 2009.

Now x = 2.5y (from (1))
and M = 6y ( from (2))

hence increased number of males in 2009 are 
M - x = 6y - 2.5y = 3.5y

Now the increase in % of males =

(change in no of males / initial number)*100

= (3.5y / x )*100 = (3.5 / 2.5)*100 = 140 
                                 (given x/y = 2.5)

Hence, B is the right option.
Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to store query output in temp MongoDB database?

For this, in a single query, simply work with forEach() and store output in a temp db. Let us first create a collection with documents −
> db.demo43.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25d4b3cfb11e5c34d898e5")
}
> db.demo43.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25d4b8cfb11e5c34d898e6")
}
> db.demo43.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25d4bbcfb11e5c34d898e7")
}
Display all documents from a collection with the help of find() method −
> db.demo43.find();
This will produce the following output −
{ "_id" : ObjectId("5e25d4b3cfb11e5c34d898e5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e25d4b8cfb11e5c34d898e6"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e25d4bbcfb11e5c34d898e7"), "StudentName" : "David" }
Following is the query to store query output in temp db −
> db.demo43.find().forEach(function(myDocument) { db.demo44.insert(myDocument); } )
Display all documents from a collection with the help of find() method −
> db.demo44.find();
This will produce the following output −
{ "_id" : ObjectId("5e25d4b3cfb11e5c34d898e5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e25d4b8cfb11e5c34d898e6"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e25d4bbcfb11e5c34d898e7"), "StudentName" : "David" }
Python | Initialize list with empty dictionaries

28 Aug, 2019
While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it’s utility in web development to store records. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using {} + "*" operatorThis task can be performed using the “*” operator. We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.
# Python3 code to demonstrate working of# Initialize list with empty dictionaries# using {} + "*" operator  # Initialize list with empty dictionaries# using {} + "*" operatorres = [{}] * 6  print("The list of empty dictionaries is : " + str(res))
The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

 
Method #2 : Using {} + list comprehensionThis is perhaps the better and correct way to perform this task. We initialize the each index of list with dictionary, this way, we have independently referring dictionaries and don’t point to single reference.
# Python3 code to demonstrate working of# Initialize list with empty dictionaries# using {} + list comprehension  # Initialize list with empty dictionaries# using {} + "*" operatorres = [{} for sub in range(6)]  print("The list of empty dictionaries is : " + str(res))
The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split Pandas Dataframe by Rows

11 Mar, 2022
We can try different approaches for splitting Dataframe to get the desired results. Let’s take an example of a dataset of diamonds.  
Python3
# importing librariesimport seaborn as snsimport pandas as pdimport numpy as np # data needs not to be downloaded separatelydf  = sns.load_dataset('diamonds')df.head()
Output:  
Method 1: Splitting Pandas Dataframe by row indexIn the below code, the dataframe is divided into two parts, first 1000 rows, and remaining rows. We can see the shape of the newly formed dataframes as the output of the given code. 
Python3
# splitting dataframe by row indexdf_1 = df.iloc[:1000,:]df_2 = df.iloc[1000:,:]print("Shape of new dataframes - {} , {}".format(df_1.shape, df_2.shape))
Output:  
Method 2: Splitting Pandas Dataframe by groups formed from unique column valuesHere, we will first grouped the data by column value “color”. The newly formed dataframe consists of grouped data with color = “E”. 
Python3
# splitting dataframe by groups# grouping by particular dataframe columngrouped = df.groupby(df.color)df_new = grouped.get_group("E")df_new
Output:  
Method 3 : Splitting Pandas Dataframe in predetermined sized chunksIn the above code, we can see that we have formed a new dataset of a size of 0.6 i.e. 60% of total rows (or length of the dataset), which now consists of 32364 rows. These rows are selected randomly.  
Python3
# splitting dataframe in a particular sizedf_split = df.sample(frac=0.6,random_state=200)df_split.reset_index()
Output:  
 
akivashor
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Can we have integers as elements of an enum in Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can define an enumeration using the keyword enum followed by the name of the enumeration as −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Just like arrays, the elements/constants in an enumeration are identified using numbers starting from 0 in the above example the days are identified using numbers as shown in the following illustration −
No, we can have only strings as elements in an enumeration. Using strings in it, generates a compile time error.
In the following java example, we are trying to have 3 integer values as elements of an enum.
enum EnumTest {
   10024, 5336, 9987
}
EnumTest.java:1: error: <identifier> expected
   enum EnumTest {
               ^
EnumTest.java:2: error: ',', '}', or ';' expected
   10024, 5336, 9987
   ^
EnumTest.java:2: error: '}' expected
   10024, 5336, 9987
      ^
3 errors
Instead you can have integer values to the elements of an enum.
enum StudentMarks {
   //Constants with values
   Krishna(86), Katyayani(75), Bhanu(89), Bhargav(70), Lata(90);
   //Instance variable
   private int marks;
   //Constructor to initialize the instance variable
   StudentMarks(int marks) {
      this.marks = marks;
   }
   public static void getMarks(int model){
      StudentMarks marks[] = StudentMarks.values();
      System.out.println("Price of: "+marks[model]+" is "+marks[model].marks);
   }
}
public class Sample{
   public static void main(String args[]){
      StudentMarks m[] = StudentMarks.values();
      for(int i = 0; i<m.length; i++ ) {
         StudentMarks.getMarks(i);
      }
   }
}
Price of: Krishna is 86
Price of: Katyayani is 75
Price of: Bhanu is 89
Price of: Bhargav is 70
Price of: Lata is 90
Increase border line thickness of ggplot2 plot in R

24 Jun, 2021
In this article, we are going to see how to change the borderline thickness using the ggplot2 bar plot in R Programming Language.
First, you need to install the ggplot2 package if it is not previously installed in R Studio. To install and load write the below command in R Console :
install.packages("ggplot2")
library(ggplot2)
For creating a simple bar plot we will use the function geom_bar( ).
Syntax:
geom_bar(stat, fill, color, width)
Parameters :  
stat : Set the stat parameter to identify the mode.
fill : Represents color inside the bars.
color : Represents color of outlines of the bars.
width : Represents width of the bars.
Let’s a Data Frame which has two vectors “match” and “run” and store it in a variable “runs”.
R
# Inserting dataruns <- data.frame(match=c("M-1","M-2","M-3","M-4"),                   run=c(33, 45, 66, 50))  head(runs)
Output:
Bar Plot
R
# Bar Plot library(ggplot2)    IPL <-ggplot(data=runs, aes(x=match, y=run)) +  geom_bar(stat="identity",fill="white",color="black")+  theme_classic()  IPL
Output:
Inside the function geom_bar( ), use the keyword size and assign a value to change the thickness of the border. In our case, we have assigned a value of 2 to the size. We can observe that the thickness of the border line has increased.
R
# Changing the border thicknesslibrary(ggplot2)    IPL <-ggplot(data=runs, aes(x=match, y=run)) +  geom_bar(stat="identity",fill="white",color="black",size=2)+  theme_classic()  IPL
Output:
Example 2: Consider a Data Frame which consists of information about marks obtained by students in an exam.
R
# Inserting datamarks <- data.frame(student=c("S-1","S-2","S-3","S-4","S-5"),                   mark=c(90, 85, 75, 78, 98))  # Changing the border thicknesslibrary(ggplot2)    RESULT <-ggplot(data=marks, aes(x=student, y=mark)) +  geom_bar(stat="identity",fill="yellow",color="navy",size=4,alpha=0.1)+  theme_classic()  RESULT
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
R - if statement
How to filter R DataFrame by values in a column?
Vectorized Operations in NumPy

18 Feb, 2022
Numpy arrays are homogeneous in nature means it is an array that contains data of a single type only. Python’s lists and tuples are unrestricted in the type of data they contain. The concept of vectorized operations on NumPy allows the use of more optimal and pre-compiled functions and mathematical operations on NumPy array objects and data sequences. The Output and Operations will speed up when compared to simple non-vectorized operations.
Example 1: Using vectorized sum method on NumPy array. We will compare the vectorized sum method along with simple non-vectorized operation i.e the iterative method to calculate the sum of numbers from 0 – 14,999. 
Python3
# importing the modulesimport numpy as npimport timeit # vectorized sumprint(np.sum(np.arange(15000))) print("Time taken by vectorized sum : ", end = "")%timeit np.sum(np.arange(15000)) # iterative sumtotal = 0for item in range(0, 15000):    total += itema = totalprint("\n" + str(a)) print("Time taken by iterative sum : ", end = "")%timeit a
Output :  
 
The above example shows the more optimal nature of vectorized operations of NumPy when compared with non-vectorized operations. This means when computational efficiency is the key factor in a program and we should avoid using these simple operations, rather we should use NumPy vectorized functions.
Example 2: Here we will compare NumPy exponential function with the python built-in math library exponential function to calculate the exponential value of each entry in a particular object. 
Python3
# importing the modulesimport numpy as npimport timeitimport math # vectorized operationprint("Time taken by vectorized operation : ", end = "")%timeit np.exp(np.arange(150)) # non-vectorized operationprint("Time taken by non-vectorized operation : ", end = "")%timeit [math.exp(item) for item in range(150)]
Output :  
 
Here as we can see NumPy vectorized operations are more optimized in calculating value and along with one more limitation of Python math library i.e math library range limit, as it is not suitable for very large value, unlike NumPy vectorized operation which can be used to calculate the exponential value of very large range limit as well. 
 
The above two examples justify the optimal nature of NumPy vectorized functions and operations when compared and used in place of simple or non-vectorized functions or operations in a python program or script.
 
developer0hye
punamsingh628700
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Throwable toString() method in Java with Examples

06 Feb, 2019
The toString() method of Java.lang.Throwable class used to return a String representation of this Throwable which consists of the name of the class of this object, a colon and a space(“: “) and a string which is same as result of invoking this object’s getLocalizedMessage() method and If getLocalizedMessage returns null, then just the class name is returned.
Syntax:
public String toString()
Return Value: This method returns String representation of this Throwable if a Exception occurs.
Below programs illustrate the toString() method of Throwable class:
Example 1:
// Java program to demonstrate// the toString() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {              testException();        }          catch (Throwable e) {              // print using tostring()            System.out.println("Exception: "                               + e.toString());        }    }      // method which throws Exception    public static void testException()        throws Exception    {          throw new Exception("New Exception Thrown");    }}
Exception: java.lang.Exception: New Exception Thrown

Example 2:
// Java program to demonstrate// the toString() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {        try {              // divide two numbers            int a = 4, b = 0;              int c = a / b;        }        catch (Throwable e) {              // print using tostring()            System.out.println("Exception: "                               + e.toString());        }    }}
Exception: java.lang.ArithmeticException: / by zero

References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#toString()
Java-Exception Handling
Java-Exceptions
Java-Functions
Java-lang package
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java