code-rag-bench/online-tutorials huggingface dataset:
How to Preserve Insertion Order of Java HashSet Elements? - GeeksforGeeks

07 Jan, 2021
When elements get from the HashSet due to hashing the order they inserted is not maintained while retrieval. HashSet stores the elements by using a mechanism called hashing. We can achieve the given task using LinkedHashSet. The LinkedHashSet class implements a doubly-linked list so that it can traverse through all the elements.
Example:
Input : HashSetInput = {c, a, b}
Output: HashSetPrint = {c, a, b}

Input : HashSetInput = {"first", "second"}
Output: HashSetPrint = {"first", "second"}
Implementation With HashSet: (Order Not Maintained)
Syntax:
HashSet<String> num = new HashSet<String>();
Approach:
Create HashSet object.Insert multiple elements in the HashSet.Print the HashSet.(Order not maintained)
Create HashSet object.
Insert multiple elements in the HashSet.
Print the HashSet.(Order not maintained)
Below is the implementation of the above approach:
Java
// Preserve insertion order of Java HashSet elements// Order not maintained because HashSet usedimport java.util.HashSet;import java.util.Set;  public class PreserveHashSetOrderExample {      public static void main(String[] args)    {          Set<Integer> hSetNumbers = new HashSet<Integer>();          hSetNumbers.add(1);        hSetNumbers.add(13);        hSetNumbers.add(2);        hSetNumbers.add(4);          for (Integer number : hSetNumbers) {            System.out.println(number);        }    }}
1
2
4
13
Implementation With LinkedHashSet: (Order Maintained)
Syntax:
HashSet<String> num = new LinkedHashSet<String>();
Approach:
Create a HashSet object and initialize it with the constructor of LinkedHashSet.Insert multiple elements in the HashSet.Print the HashSet.(Order maintained)
Create a HashSet object and initialize it with the constructor of LinkedHashSet.
Insert multiple elements in the HashSet.
Print the HashSet.(Order maintained)
Below is the implementation of the above approach:
Java
// Preserve insertion order of Java HashSet elements// Using LinkedHashSetimport java.util.LinkedHashSet;import java.util.Set;  public class PreserveHashSetOrderExample {      public static void main(String[] args)    {          Set<Integer> setNumbers            = new LinkedHashSet<Integer>();          setNumbers.add(1);        setNumbers.add(13);        setNumbers.add(2);        setNumbers.add(4);          for (Integer number : setNumbers) {            System.out.println(number);        }    }}
1
13
2
4
java-hashset
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
JavaScript array.includes inside nested array returning false where as searched name is in array

It is a well-known dilemma that when we use includes() inside nested arrays i.e., multidimensional
array, it does not work, there exists a Array.prototype.flat() function which flats the
array and then searches through but it’s browser support is not very good yet.
So our job is to create a includesMultiDimension() function that takes in an array and a string
and returns a boolean based on the presence/absence of that string in the array.
There exist many solutions to this problem, most of them includes recursion, heavy array
function, loops and what not.
What we are going to discuss here is by far the easiest way to check for presence/absence of
string in nested arrays.
The code for this is −
const names = ['Ram', 'Shyam', 'Laxman', [
   'Jay', 'Jessica', [
      'Vikram'
   ]
]];
const includesMultiDimension = (arr, str) =>
JSON.stringify(arr).includes(str);
console.log(includesMultiDimension(names, 'Vikram'));
This one line solution includes converting the array into a JSON string so that we can simply
apply includes to it.
The console output will be −
True
C++ Array (print an element) | Set 2 | Practice | GeeksforGeeks

Given an array A[] of N integers and an index Key. Your task is to print the element present at index key in the array.
 
Example 1:
Input:
5 2
10 20 30 40 50
Output:
30
 
Example 2:
Input:
7 4
10 20 30 40 50 60 70
Output:
50
 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function findElementAtIndex() which takes the array A[], its size N and an integer Key as inputs and returns the element present at index Key.

Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
 
Constraints:
1 ≤ N ≤ 100
0 ≤ Key ≤ N - 1
1 ≤ A[i] ≤ 100
0
rsbly7300952 weeks ago
class Solution{   public:   int findElementAtIndex(int a[], int n, int key)    {       return a[key];   }};
0
ayushsunilkadam3 weeks ago
return a[key];
0
crsongirkar21 month ago
class Solution{   public:   int findElementAtIndex(int a[], int n, int key)    {       return a[key];       // Your code goes here   }};
0
0niharika22 months ago
return a[key];
0
amans603312 months ago
class Solution{   public:   int findElementAtIndex(int a[], int n, int key)    {       return a[key];   }};
0
ishankumarsingh262 months ago
class Solution{
    public:
    int findElementAtIndex(int a[], int n, int key) 
    {
        return a[key];
    }
};
+1
sakshamraj2292 months ago
class Solution{
    public:
    int findElementAtIndex(int a[], int n, int key) 
    {
        return a[key];
    }
};
0
samarthsaxena3123 months ago
class Solution{   public:   int findElementAtIndex(int a[], int n, int key)    {      for(int i=0;i<n;i++)      {          if(key==i)          {              return a[i];              break;          }      }   }};
 
0
helloutkarsh983 months ago
    int findElementAtIndex(int a[], int n, int key)    {      return a[key];   }
-1
viploveparsai13 months ago
class Solution{   public:   int findElementAtIndex(int a[], int n, int key)    {       // Your code goes here       return a[key];   }}; 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to create an image bullets in HTML ? - GeeksforGeeks

12 Jan, 2021
In this article, we have given some list items and the task is to create a list items with image bullets.  This task can be done by using the list-style-image property in CSS.  This property is used to set the image that will be used as the list item marker.  
Syntax:
list-style-image: url; 
Example: Below code illustrates that how to create image bullets using css.  
HTML
<!DOCTYPE html><html>  <head>    <title>        How to create an image bullets in HTML?    </title>      <style>        ul {            list-style-image: url("https://contribute.geeksforgeeks.org/wp-content/uploads/listitem-1.png");        }    </style></head>  <body>    <h1 style="color:green;">        GeeksforGeeks    </h1>      <h2>        How to create an image bullets in HTML?    </h2>        <p>List of fruits</p>        <ul>        <li>apple</li>        <li>mango</li>        <li>banana</li>        <li>grapes</li>        <li>papaya</li>    </ul></body>  </html>
Output  
Supported Browsers are listed below:
Google Chrome
Internet Explorer
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.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
How to get the list of all COBOL-DB2 programs using a DB2 table TAB1?

SYSIBM.SYSTABAUTH is a DB2 system table which records the privileges that users/program hold on tables and views. We can use this table to find out the list of programs accessing a particular table and what action the program is performing on the table like SELECT, UPDATE, INSERT or DELETE. The below SQL query can be fired on SYSTABAUTH in order to get list of programs.
SELECT GRANTEE, SELECTAUTH, UPDATEAUTH, INSERTAUTH, DELETEAUTH FROM SYSIBM.SYSABAUTH
WHERE GRANTEETYPE = ‘P’ AND TNAME = ‘TAB1’
The column SELECTAUTH, UPDATEAUTH, INSERTAUTH and DELETEAUTH represents SELECT, UPDATE, INSERT and DELETE authority respectively. In the WHERE clause we will add a GRANTEETYPE predicate as ‘P’ to make sure only program names are returned (and not the users). We can give the table name predicate for the TNAME column.
Python - Chart Properties

Python has excellent libraries for data visualization. A combination of Pandas, numpy and matplotlib can help in creating in nearly all types of visualizations charts. In this chapter we will get started with looking at some simple chart and the various properties of the chart.
We use numpy library to create the required numbers to be mapped for creating the chart and the pyplot method in matplotlib to draws the actual chart.
import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Simple Plot
plt.plot(x,y)
Its output is as follows −
We can apply labels to the axes as well as a title for the chart using appropriate methods from the library as shown below.
import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Labeling the Axes and Title
plt.title("Graph Drawing") 
plt.xlabel("Time") 
plt.ylabel("Distance") 
#Simple Plot
plt.plot(x,y)
Its output is as follows −
The style as well as colour for the line in the chart can be specified using appropriate methods from the library as shown below.
import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Labeling the Axes and Title
plt.title("Graph Drawing") 
plt.xlabel("Time") 
plt.ylabel("Distance") 

# Formatting the line colors
plt.plot(x,y,'r')

# Formatting the line type  
plt.plot(x,y,'>') 
Its output is as follows −
The chart can be saved in different image file formats using appropriate methods from the library as shown below.
import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Labeling the Axes and Title
plt.title("Graph Drawing") 
plt.xlabel("Time") 
plt.ylabel("Distance") 

# Formatting the line colors
plt.plot(x,y,'r')

# Formatting the line type  
plt.plot(x,y,'>') 

# save in pdf formats
plt.savefig('timevsdist.pdf', format='pdf')
The above code creates the pdf file in the default path of the python environment. 

    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
Prime factors in java

Factors are the numbers we multiply to get another number.
factors of 14 are 2 and 7, because 2 × 7 = 14.
Some numbers can be factored in more than one way.
16 can be factored as 1 × 16, 2 × 8, or 4 × 4.
A number that can only be factored as 1 times itself is called a prime number.
The first few primes are 2, 3, 5, 7, 11, and 13.
The list of all the prime-number factors of a given number is the prime factors of a number. The factorization of a number into its prime factors and expression of the number as a product of its prime factors is known as the prime factorization of that number. The prime factorization of a number includes ONLY the prime factors, not any products of those prime factors.
import java.util.Scanner;

public class PrimeFactors {
   public static void main(String args[]){
      int number;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number ::");
      number = sc.nextInt();
     
      for(int i = 2; i< number; i++) {
         while(number%i == 0) {
            System.out.println(i+" ");
            number = number/i;
         }
      }
      if(number >2) {
         System.out.println(number);
      }
   }
}
Enter a number
24
2
2
2
3
Double.IsNaN() Method in C# - GeeksforGeeks

13 Feb, 2019
In C#, Double.IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN).
Syntax: public static bool IsNaN (double d);
Parameter:d: It is a double-precision floating-point number of type System.Double
Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False.
Example:
Input  : d = 0.0 / 0.0 
Output : True

Input  : d = 1.734
Output : False

Code: To demonstrate the Double.IsNaN(Double) method.
// C# code to demonstrate // Double.IsNaN(Double) method using System;  class GFG {           // Main Method    public static void Main(String[] args)     {           // first example         Double f1 = 1.0 / 0.0;           bool res = Double.IsNaN(f1);           // printing the output         if (res)             Console.WriteLine(f1 + " is NaN");         else            Console.WriteLine(f1 + " is not NaN");           // second example         double f2 = 0.0 / 0.0;           bool res1 = Double.IsNaN(f2);           // printing the output         if (res1)             Console.WriteLine(f2 + " is NaN");         else            Console.WriteLine(f2 + " is not NaN");     } } 
Infinity is not NaN
NaN is NaN

Note:
If we divide any value by 0 directly, the Compiler will show an error. So, in the above example, 0 is stored in a variable first.
Every floating point operation returns a NaN to show that the result of the operation is undefined.
CSharp-Double-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
Extension Method in C#
C# | Abstract Classes
C# | String.IndexOf( ) Method | Set - 1
Common Language Runtime (CLR) in C#
C# | Arrays
HashSet in C# with Examples
C# | Replace() Method
SQL Tryit Editor v1.6

SELECT * FROM Customers;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
C# program to replace all spaces in a string with ‘%20’

We have a sample string with spaces −
str ="Hello World !";
Use the Replace() method in C# to replace all spaces in a string with ‘%20’ −
str2 = str.Replace(" ", "%20");
You can try to run the following code to replace all spaces in a string with ‘%20’.
Live Demo
using System;
class Demo {
   static void Main() {
      String str, str2;
      str ="Hello World !";
      Console.WriteLine("String: "+str);
      str2 = str.Replace(" ", "%20");
      Console.WriteLine("String (After replacing): "+str2);
   }
}
String: Hello World !
String (After replacing): Hello%20World%20!
How to Automatically Import Your Favorite Libraries into IPython or a Jupyter Notebook | by Will Koehrsen | Towards Data Science

If you often use interactive IPython sessions or Jupyter Notebooks and you’re getting tired of importing the same libraries over and over, try this:
Navigate to ~/.ipython/profile_defaultCreate a folder called startup if it’s not already thereAdd a new Python file called start.pyPut your favorite imports in this fileLaunch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!
Navigate to ~/.ipython/profile_default
Create a folder called startup if it’s not already there
Add a new Python file called start.py
Put your favorite imports in this file
Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!
Here are the steps in visual form. First, the location of start.py:
Here is the contents of my start.py:
Now, when I launch an IPython session, I see this:
We can confirm that the libraries have been loaded by inspecting globals() :
globals()['pd']<module 'pandas' from '/usr/local/lib/python3.6/site-packages/pandas/__init__.py'>globals()['np']<module 'numpy' from '/usr/local/lib/python3.6/site-packages/numpy/__init__.py'>
We’re all good to use our interactive session now without having to type the commands to load these libraries! This also works in Jupyter Notebook.
The file can be named anything ( start.py is easy to remember) and you can have multiple files in startup/. They are executed in lexicographical order when IPython is launched.
If you’re running this in a Jupyter Notebook, you won’t get a cell with the imports so when you share the notebook, make sure to copy over the start.py contents into the first cell. This will let people know what libraries you are using. (As an alternative, you can use the default_cell Jupyter Notebook extension I wrote.)
If you work on multiple computers, you’ll have to repeat the steps. Make sure to use the same start.py script so you get the same imports!
Thanks to this Stack Overflow answer and the official docs
This is certainly not life-changing (unlike writing about data science) but it saves you a few seconds every time you start IPython. It’s also useful as a demonstration of how you can customize your work environment to be as efficient as possible. There are many other tips you can find by reading documentation (such as for IPython magic commands), experimenting on your own, or even following helpful Twitter accounts. If you find yourself frustrated with an inefficiency like typing import pandas as pd ten times a day, don’t just accept it, find a better way to work.
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
Collectors groupingBy() method in Java with Examples - GeeksforGeeks

29 Jul, 2021
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL’s GROUP BY clause. 
Syntax:  
public static Collector<T, ?, Map<K, List>> groupingBy(Function classifier)  
Type Parameter: This method takes two type parameters: 
T- It is the type of the input elements. 
K- It is the type the input elements to be converted.
Parameters: This method accepts two mandatory parameters:  
Function- It is the property which is to be applied to the input elements. 
Classifier- It is used to map input elements into the destination map.
Return value: It returns a collector as a map. 
Below is the program implementation of groupingBy() method:Program 1: 
Java
// Java program to demonstrate// Collectors groupingBy() method import java.util.*;import java.util.function.Function;import java.util.stream.Collectors; public class GFG {    public static void main(String[] args)    {         // Get the List        List<String> g            = Arrays.asList("geeks", "for", "geeks");         // Collect the list as map        // by groupingBy() method        Map<String, Long> result            = g.stream().collect(                Collectors.groupingBy(                    Function.identity(),                    Collectors.counting()));         // Print the result        System.out.println(result);    }}
{geeks=2, for=1}
 
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-
manikarora059
Java - util package
Java-Collectors
Java-Functions
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Multidimensional Arrays in Java
Euler Totient Function | Practice | GeeksforGeeks

Find the Euler Totient Function (ETF) Φ(N) for an input N. ETF is the count of numbers in {1, 2, 3, ..., N} that are relatively prime to N, i.e., the numbers whose GCD (Greatest Common Divisor) with N is 1.
 
Example 1:
Input:
N = 11
Output:
10
Explanation:
From 1 to 11,
1,2,3,4,5,6,7,8,9,10
are relatively prime to 11.

Example 2:
Input:
N = 16
Output:
8
Explanation:
From 1 to 16
1,3,5,7,9,11,13,15 
are relatively prime
to 16.


Your Task:
You don't need to read input or print anything. Your task is to complete the function ETF() which takes one integer value N, as input parameter and return the value of Φ(N).
 
Expected Time Complexity: O(NLog N)
Expected Space Complexity: O(1)
 
Constraints:
1<=N<=105
-1
Nikhil Kumar1 year ago
Nikhil Kumar
long long int gcd(long long int a, long long int b){        if (b == 0)            return a;        return gcd(b, a % b);    }
    // function to find totient of n    long long ETF(long long N){        long long count=0;        for(long long i=1; i<=N; i++){            if(gcd(N, i)==1)                count++;        }        return count;        // code here    }
N logN is not getting accepted? why?
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
EnumSet range() Method in Java - GeeksforGeeks

02 Jul, 2018
The java.util.EnumSet.range(E start_point, E end_point) method in Java is used to create an enum set with the elements defined by the specified range in the parameters.
Syntax:
Enum_set = EnumSet.range(E start_point, E end_point)
Parameters: The method accepts two parameters of the object type of enum:
start_point: This refers to the starting element that is needed to be added to the enum set.
end_point: This refers to the last element which is needed to be added to the enum set.
Return Value: The method returns the enum set created by the elements mentioned within the specified range.
Exceptions: The method throws two types of exception:
NullPointerException is thrown if any of the starting or the last element is NULL.
IllegalArgumentException is thrown when the first element is greater than the last element with respect to the position.
Below programs illustrate the use of range() method:Program 1:
// Java program to demonstrate range() methodimport java.util.*;  // Creating an enum of GFG typeenum GFG {    Welcome,    To,    The,    World,    of,    Geeks};  public class Enum_Set_Demo {      public static void main(String[] args)    {          // Creating an EnumSet        EnumSet<GFG> e_set;          // Input the values using range()        e_set = EnumSet.range(GFG.The, GFG.Geeks);          // Displaying the new set        System.out.println("The enum set is: " + e_set);    }}
The enum set is: [The, World, of, Geeks]

Program 2:
// Java program to demonstrate range() methodimport java.util.*;  // Creating an enum of CARS typeenum CARS {    RANGE_ROVER,    MUSTANG,    CAMARO,    AUDI,    BMW};  public class Enum_Set_Demo {      public static void main(String[] args)    {          // Creating an EnumSet        EnumSet<CARS> e_set;          // Input the values using range()        e_set = EnumSet.range(CARS.RANGE_ROVER, CARS.CAMARO);          // Displaying the new set        System.out.println("The enum set is: " + e_set);    }}
The enum set is: [RANGE_ROVER, MUSTANG, CAMARO]

java-EnumSet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
Get distinct record values in MongoDB?

You can use distinct() method in MongoDB to get distinct record values. The syntax is as follows −
db.yourCollectionName.distinct(“yourFieldName”);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows −
> db.distinctRecordDemo.insertOne({"StudentId":1,"StudentName":"John","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a78299b97a65744c1b50")
}
> db.distinctRecordDemo.insertOne({"StudentId":2,"StudentName":"John","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a78b99b97a65744c1b51")
}
> db.distinctRecordDemo.insertOne({"StudentId":3,"StudentName":"Carol","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a79a99b97a65744c1b52")
}
> db.distinctRecordDemo.insertOne({"StudentId":4,"StudentName":"Carol","StudentAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7a499b97a65744c1b53")
}
> db.distinctRecordDemo.insertOne({"StudentId":5,"StudentName":"Sam","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7b499b97a65744c1b54")
}
> db.distinctRecordDemo.insertOne({"StudentId":6,"StudentName":"Mike","StudentAge":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7c799b97a65744c1b55")
}
> db.distinctRecordDemo.insertOne({"StudentId":7,"StudentName":"Sam","StudentAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7d399b97a65744c1b56")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.distinctRecordDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c77a78299b97a65744c1b50"),
   "StudentId" : 1,
   "StudentName" : "John",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c77a78b99b97a65744c1b51"),
   "StudentId" : 2,
   "StudentName" : "John",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5c77a79a99b97a65744c1b52"),
   "StudentId" : 3,
   "StudentName" : "Carol",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c77a7a499b97a65744c1b53"),
   "StudentId" : 4,
   "StudentName" : "Carol",
   "StudentAge" : 26
}
{
   "_id" : ObjectId("5c77a7b499b97a65744c1b54"),
   "StudentId" : 5,
   "StudentName" : "Sam",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c77a7c799b97a65744c1b55"),
   "StudentId" : 6,
   "StudentName" : "Mike",
   "StudentAge" : 27
}
{
   "_id" : ObjectId("5c77a7d399b97a65744c1b56"),
   "StudentId" : 7,
   "StudentName" : "Sam",
   "StudentAge" : 28
}
Here is the query to get distinct records values in MongoDB.
Case 1 − Here the field is “StudentName”.
The query is as follows −
> db.distinctRecordDemo.distinct("StudentName");
The following is the output displaying distinct record for StudentName −
[ "John", "Carol", "Sam", "Mike" ]
Case 2 − Here the field is “StudentAge”.
The query is as follows −
> db.distinctRecordDemo.distinct("StudentAge");
The following is the output displaying distinct record for StudentAge −
[ 21, 22, 26, 24, 27, 28 ]
How to write inline if statement for print in Python?

Python provides two ways to write inline if statements. These are:
1. if condition: statement
2. s1 if condition else s2
Note that second type of if cannot be used without an else. Now you can use these inline in a print statement as well. For example,
a = True
if a: print("Hello")
This will give the output:
Hello
a = False
print("True" if a else "False")
This will give the output:
False
Calculate the Root of a Equation within an interval in R Programming - uniroot() Function - GeeksforGeeks

12 Jun, 2020
uniroot() function in R Language is used to calculate the root of an equation with the lower and upper range of the interval passed as arguments.
Syntax: uniroot(fun, interval, lower, upper)
Parameters:fun: function with the equationinterval: with upper and lower range of rootlower: lower end point of the intervalupper: upper end point of the interval
Example 1:
# R program to calculate root of an equation  # Function with equationfun <- function(x) {2 * x ^ 2 - 4 * x -10}  # Calling uniroot() functionuniroot(fun, lower = 0, upper = 4)
Output:
$root
[1] 3.449485

$f.root
[1] -4.310493e-05

$iter
[1] 5

$init.it
[1] NA

$estim.prec
[1] 6.103516e-05

Example 2:
# R program to calculate root of an equation  # Function with equationfun <- function(x) {2 * x ^ 2 - 4 * x -10}  # Calling uniroot() functionuniroot(fun, c(0, 4))$rootuniroot(fun, lower = -4, upper = 0)$root
Output:
[1] 3.449485
[1] -1.44949

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
ggplot2 - Themes

In this chapter, we will focus on using customized theme which is used for changing the look and feel of workspace. We will use “ggthemes” package to understand the concept of theme management in workspace of R.
Let us implement following steps to use the required theme within mentioned dataset.
Install “ggthemes” package with the required package in R workspace.
> install.packages("ggthemes")
> Library(ggthemes)

Implement new theme to generate legends of manufacturers with year of production and displacement.
> library(ggthemes)
> ggplot(mpg, aes(year, displ, color=factor(manufacturer)))+
+ geom_point()+ggtitle("This plot looks a lot different from the default")+
+ theme_economist()+scale_colour_economist()

It can be observed that the default size of the tick text, legends and other elements are little small with previous theme management. It is incredibly easy to change the size of all the text elements at once. This can be done on creating a custom theme which we can observe in below step that the sizes of all the elements are relative (rel()) to the base_size.
> theme_set(theme_gray(base_size = 30))
> ggplot(mpg, aes(x=year, y=class))+geom_point(color="red")

 Print
 Add Notes
 Bookmark this page
Explain the characteristics and operations of arrays in C language

An array is a homogeneous sequential collection of data items over a single variable name.
For example, int student[30];
Here, student is an array name holds 30 collection of data item, with a single variable name.
The characteristics of arrays are as follows −
An array is always stored in consecutive memory location.
An array is always stored in consecutive memory location.
It can store multiple value of similar type, which can be referred with single name.
It can store multiple value of similar type, which can be referred with single name.
The pointer points to the first location of memory block, which is allocated to the
array name.
The pointer points to the first location of memory block, which is allocated to the
array name.
An array can either be an integer, character, or float data type that can be initialised only during the declaration.
An array can either be an integer, character, or float data type that can be initialised only during the declaration.
The particular element of an array can be modified separately without changing the
other elements.
The particular element of an array can be modified separately without changing the
other elements.
All elements of an array can be distinguishing with the help of index number.
All elements of an array can be distinguishing with the help of index number.
The operations of an array include −
Searching − It is used to find whether particular element is present or not.
Searching − It is used to find whether particular element is present or not.
Sorting − Helps in arranging the elements in an array either in an ascending or descending order.
Sorting − Helps in arranging the elements in an array either in an ascending or descending order.
Traversing − Processing every element in an array, sequentially.
Traversing − Processing every element in an array, sequentially.
Inserting − Helps in inserting elements in an array.
Inserting − Helps in inserting elements in an array.
Deleting − helps in deleting the element in an array.
Deleting − helps in deleting the element in an array.
Following is the C program for searching an element in an array −
 Live Demo
#include <stdio.h>
#define MAX 100 // Maximum array size
int main(){
   int array[MAX];
   int size, i, search, found;
   printf("Enter size of array: ");
   scanf("%d", &size);
   printf("Enter elements in array: ");
   for(i=0; i<size; i++){
      scanf("%d", &array[i]);
   }
   printf("\nEnter element to search: ");
   scanf("%d", &search);
   found = 0;
   for(i=0; i<size; i++){
      if(array[i] == search){
         found = 1;
         break;
      }
   }
   if(found == 1){
      printf("\n%d is found at position %d", search, i + 1);
   } else {
      printf("\n%d is not found in the array", search);
   }
   return 0;
}
The output is as follows −
Enter size of array: 5
Enter elements in array: 11 24 13 12 45
Enter element to search: 13
13 found at position 3found
Creating a Function module in ABAP to take any table and write it to the screen

SAP List Viewer is used to add an ALV component and provides a flexible environment to display lists and tabular structure. A standard output consists of header, toolbar, and an output table. The user can adjust the settings to add column display, aggregations, and sorting options using additional dialog boxes.
You can use following code to display any table:
DATA: go_alv TYPE REF TO cl_salv_table.
   CALL METHODcl_salv_table=>factory
   IMPORTING
      r_salv_table = go_alv
   CHANGING
      t_table     = itab.
 go_alv->display( ).
Another Dynamic Way to Output Any Internal Table is by using field-symbol, this is a particular field type in ABAP. Without going into the details of it, you must know that a field symbol works like a pointer without pointer arithmetic, but has a value semantics.
FIELD-SYMBOLS:<row> TYPE ANY.
FIELD-SYMBOLS:<comp> TYPE ANY.
The typing ANY is necessary because the field symbol should be able to refer to data of any type. And this is what our loop looks like now using a dynamic assignment to the various components of the work area:
LOOP ATitab_flight INTO row.
   DO.
      ASSIGN COMPONENTsy-index OF STRUCTURE <row> TO <wa_comp>.
      IF sy-subrc <>0.
         SKIP.
      EXIT.
      ENDIF.
         WRITE <wa_comp>.
   ENDDO.
ENDLOOP
Can we create a table with a space in name in MySQL?

To create a table with a space in the table name in MySQL, you must use backticks otherwise you will get an error.
Let us first see what error will arise by creating a table with a space in the name i.e. “Demo Table” table name below:
mysql> create table Demo Table
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeFirstName varchar(20),
   EmployeeLastName varchar(20),
   EmployeeAge int,
   EmployeeSalary int,
   EmployeeAddress varchar(200)
);
ERROR 1064 (42000): You have an error in your syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'Table37
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeFirstName varchar(' at line 1 )
Let us use the concept of backticks for table name to remove the error. The query to create a table with a space in MySQL is as follows:
mysql> create table `Demo Table37`
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeFirstName varchar(20),
   EmployeeLastName varchar(20),
   EmployeeAge int,
   EmployeeSalary int,
   EmployeeAddress varchar(200)
);
Query OK, 0 rows affected (0.66 sec)

Above, we have set the table name with space surrounded by backtick symbol, therefore no error:
`Demo Table37`
Explain the functions fread() and fwrite() used in files in C

Write a C program for storing the details of 5 students into a file and print the same using fread() and fwrite()
The fread() function reads the entire record at a time.
fread( & structure variable, size of (structure variable), no of records, file pointer);
struct emp{
   int eno;
   char ename [30];
   float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
The fwrite() function writes an entire record at a time.
fwrite( & structure variable , size of structure variable, no of records, file pointer);
struct emp{
   int eno:
   char ename [30];
   float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);
#include<stdio.h>
struct student{
   int sno;
   char sname [30];
   float marks;
   char temp;
};
main ( ){
   struct student s[60];
   int i;
   FILE *fp;
   fp = fopen ("student1.txt", "w");
   for (i=0; i<2; i++){
      printf ("enter details of student %d\n", i+1);
      printf("student number:");
      scanf("%d",&s[i].sno);
      scanf("%c",&s[i].temp);
      printf("student name:");
      gets(s[i].sname);
      printf("student marks:");
      scanf("%f",&s[i].marks);
      fwrite(&s[i], sizeof(s[i]),1,fp);
   }
   fclose (fp);
   fp = fopen ("student1.txt", "r");
   for (i=0; i<2; i++){
      printf ("details of student %d are\n", i+1);
      fread (&s[i], sizeof (s[i]) ,1,fp);
      printf("student number = %d\n", s[i]. sno);
      printf("student name = %s\n", s[i]. sname);
      printf("marks = %f\n", s[i]. marks);
   }
   fclose(fp);
   getch( );
}
enter details of student 1
student number:1
student name:pinky
student marks:56
enter details of student 2
student number:2
student name:rosy
student marks:87
details of student 1 are
student number = 1
student name = pinky
marks = 56.000000
details of student 2 are
student number = 2
student name = rosy
marks = 87.000000
Python 3 - String isalnum() Method

The isalnum() method checks whether the string consists of alphanumeric characters.
Following is the syntax for isalnum() method −
str.isa1num()

NA
This method returns true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
The following example shows the usage of isalnum() method.
#!/usr/bin/python3

str = "this2016"  # No space in this string
print (str.isalnum())

str = "this is string example....wow!!!"
print (str.isalnum())
When we run the above program, it produces the following result −
True
False


    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
Program to convert List of String to List of Integer in Java

Here’s our List of String −
List<String> listString = Arrays.asList("25", "50", "75", "100", "125", "150");
Now, convert the list of string to list of integer −
List<Integer> listInteger = listString.stream().map(Integer::parseInt).collect(Collectors.toList());
Following is the program to convert List of String to List of Integer in Java −
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class Demo {
   public static void main(String[] args) {
      List<String> listString = Arrays.asList("25", "50", "75", "100", "125", "150");
      System.out.println("List of String = " + listString);
      List<Integer> listInteger = listString.stream().map(Integer::parseInt)
         .collect(Collectors.toList());
      System.out.println("List of Integer (converted from List of String) = " + listInteger);
   }
}
List of String = [25, 50, 75, 100, 125, 150]
List of Integer (converted from List of String) = [25, 50, 75, 100, 125, 150]
Enter key press event in JavaScript?

For ENTER key press event, you can call a function on −
onkeypress=”yourFunctionName”
Use the ENTER’s keycode 13.
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/
4.7.0/css/font-awesome.min.css">
</head>
<body>
<input id="enterDemo" type="text" onkeypress="return
enterKeyPressed(event)" />
<script>
   function enterKeyPressed(event) {
      if (event.keyCode == 13) {
         console.log("Enter key is pressed");
         return true;
      } else {
         return false;
      }
   }
</script>
</body>
</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 −
On pressing ENTER key, the following output is visible on console −
Python | Printing String with double quotes

22 Apr, 2020
Many times, while working with Python strings, we have a problem in which we need to use double quotes in a string and then wish to print it. This kind of problem occurs in many domains like day-day programming and web-development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using backslash (“\”)This is one way to solve this problem. In this, we just employ a backslash before a double quote and it is escaped.
# Python3 code to demonstrate working of # Printing String with double quotes# Using backslash  # initializing string# using backslashtest_str = "geeks\"for\"geeks"  # printing stringprint("The string escaped with backslash : " + test_str)
The string escaped with backslash : geeks"for"geeks

 
Method #2 : Using triple quotesThis is one more way in python to print and initialize a string. Apart from multiline comment, triple quotes are also good way of escaping.
# Python3 code to demonstrate working of # Printing String with double quotes# Using triple quotes  # initializing string# using triple quotestest_str = """geeks"for"geeks"""  # printing stringprint("The string escaped with triple quotes : " + test_str)
The string escaped with triple quotes : geeks"for"geeks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Insert Multiple Rows

13 Sep, 2021
Insertion in a table is a DML (Data manipulation language) operation in SQL. When we want to store data we need to insert the data into the database. We use the INSERT statement to insert the data into the database.  In this article, we see how to insert individual as well as multiple rows in a database using the INSERT statement in the MSSQL server.
Creating a Database: Use the below command to create a database named GeeksforGeeks:
Query:
CREATE DATABASE GeeksforGeeks;
Output:
Using the Database: To use the GeeksforGeeks database use the below command:
Query:
USE GeeksforGeeks
Output:
Creating a Table: Create a table employee_details with  4 columns using the following SQL query: 
Query:
CREATE TABLE employee_details(
   emp_id VARCHAR(8),
   emp_name VARCHAR(20),
   emp_dept_id VARCHAR(20),
   emp_age INT);
Output:
Verifying the table: To view the description of the tables in the database using the following SQL query:
Query:
EXEC sp_columns employee_details;
Output:
The query for Inserting rows into the Table  :
Inserting rows into employee_details table using the following SQL query:
1. Inserting individual rows into the table :
Query:
INSERT INTO employee_details VALUES('E40001','PRADEEP','E101',36);
INSERT INTO employee_details VALUES('E40002','ASHOK','E102',28);
INSERT INTO employee_details VALUES('E40003','PAVAN KUMAR','E103',28); 
Output:
2. Viewing the inserted data:
Query:
SELECT * FROM employee_details;
Output:
3. Inserting multiple rows into the table:
Query:
INSERT INTO employee_details VALUES
  ('E40004','SANTHOSH','E102',25),
  ('E40005','THAMAN','E103',26),
('E40006','HARSH','E101',25),
  ('E40007','SAMHITH','E102',26);
Output:
4. Viewing the inserted data now:
Query:
SELECT * FROM employee_details;
Output:
Picked
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.